Skip to content

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.

experimental: setup cell UI (#4026)

Myles Scolnickeea8b9116252
diff --git a/frontend/src/__tests__/CellStatus.test.tsx b/frontend/src/__tests__/CellStatus.test.tsx
new file mode 100644
index 0000000000..274a483cca
--- /dev/null
+++ b/frontend/src/__tests__/CellStatus.test.tsx
@@ -0,0 +1,262 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import {
+ CellStatusComponent,
+ ElapsedTime,
+ formatElapsedTime,
+} from "../components/editor/cell/CellStatus";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { render } from "@testing-library/react";
+import type { Seconds } from "@/utils/time";
+import { TooltipProvider } from "@/components/ui/tooltip";
+
+// Mock date-fns to have consistent date formatting in tests
+vi.mock("date-fns", () => ({
+ formatDistanceToNow: () => "5 minutes",
+}));
+
+describe("formatElapsedTime", () => {
+ test("formats milliseconds correctly", () => {
+ expect(formatElapsedTime(500)).toBe("500ms");
+ expect(formatElapsedTime(50)).toBe("50ms");
+ });
+
+ test("formats seconds correctly", () => {
+ expect(formatElapsedTime(1500)).toBe("1.50s");
+ expect(formatElapsedTime(2340)).toBe("2.34s");
+ });
+
+ test("formats minutes and seconds correctly", () => {
+ expect(formatElapsedTime(60 * 1000)).toBe("1m0s");
+ expect(formatElapsedTime(90 * 1000)).toBe("1m30s");
+ expect(formatElapsedTime(89 * 1000)).toBe("1m29s");
+ expect(formatElapsedTime(91 * 1000)).toBe("1m31s");
+ expect(formatElapsedTime(150 * 1000)).toBe("2m30s");
+ expect(formatElapsedTime(151 * 1000)).toBe("2m31s");
+ });
+
+ test("handles null input", () => {
+ expect(formatElapsedTime(null)).toBe("");
+ });
+});
+
+describe("ElapsedTime component", () => {
+ test("renders elapsed time correctly", () => {
+ const { container } = render(
+ <TooltipProvider>
+ <ElapsedTime elapsedTime="1.50s" />
+ </TooltipProvider>,
+ );
+ expect(container).toMatchSnapshot();
+ });
+});
+
+describe("CellStatusComponent", () => {
+ // Mock date for consistent testing
+ const mockDate = new Date(2024, 0, 1, 12, 0, 0);
+ const originalDate = global.Date;
+
+ beforeEach(() => {
+ global.Date = class extends Date {
+ static override now() {
+ return mockDate.getTime();
+ }
+ } as typeof Date;
+ });
+
+ afterEach(() => {
+ global.Date = originalDate;
+ });
+
+ // Base props that will be modified for different test cases
+ const baseProps = {
+ editing: true,
+ edited: false,
+ disabled: false,
+ staleInputs: false,
+ status: "idle" as const,
+ interrupted: false,
+ elapsedTime: null,
+ runStartTimestamp: null,
+ lastRunStartTimestamp: null,
+ uninstantiated: false,
+ };
+
+ test("returns null when not editing", () => {
+ const { container } = render(
+ <TooltipProvider>
+ <CellStatusComponent {...baseProps} editing={false} />
+ </TooltipProvider>,
+ );
+ expect(container.firstChild).toBeNull();
+ });
+
+ test("renders disabled and stale state", () => {
+ const props = {
+ ...baseProps,
+ disabled: true,
+ staleInputs: true,
+ lastRunStartTimestamp: 1_704_096_000 as Seconds, // Jan 1, 2024 12:00:00
+ };
+
+ const { container } = render(
+ <TooltipProvider>
+ <CellStatusComponent {...props} />
+ </TooltipProvider>,
+ );
+ expect(container).toMatchSnapshot();
+ });
+
+ test("renders disabled state", () => {
+ const props = {
+ ...baseProps,
+ disabled: true,
+ lastRunStartTimestamp: 1_704_096_000 as Seconds,
+ };
+
+ const { container } = render(
+ <TooltipProvider>
+ <CellStatusComponent {...props} />
+ </TooltipProvider>,
+ );
+ expect(container).toMatchSnapshot();
+ });
+
+ test("renders disabled transitively state", () => {
+ const props = {
+ ...baseProps,
+ status: "disabled-transitively" as const,
+ lastRunStartTimestamp: 1_704_096_000 as Seconds,
+ };
+
+ const { container } = render(
+ <TooltipProvider>
+ <CellStatusComponent {...props} />
+ </TooltipProvider>,
+ );
+ expect(container).toMatchSnapshot();
+ });
+
+ test("renders stale and disabled transitively state", () => {
+ const props = {
+ ...baseProps,
+ status: "disabled-transitively" as const,
+ staleInputs: true,
+ lastRunStartTimestamp: 1_704_096_000 as Seconds,
+ };
+
+ const { container } = render(
+ <TooltipProvider>
+ <CellStatusComponent {...props} />
+ </TooltipProvider>,
+ );
+ expect(container).toMatchSnapshot();
+ });
+
+ test("renders running state", () => {
+ const props = {
+ ...baseProps,
+ status: "running" as const,
+ runStartTimestamp: 1_704_096_000 as Seconds,
+ lastRunStartTimestamp: 1_704_096_000 as Seconds,
+ };
+
+ const { container } = render(
+ <TooltipProvider>
+ <CellStatusComponent {...props} />
+ </TooltipProvider>,
+ );
+ expect(container).toMatchSnapshot();
+ });
+
+ test("renders queued state", () => {
+ const props = {
+ ...baseProps,
+ status: "queued" as const,
+ lastRunStartTimestamp: 1_704_096_000 as Seconds,
+ };
+
+ const { container } = render(
+ <TooltipProvider>
+ <CellStatusComponent {...props} />
+ </TooltipProvider>,
+ );
+ expect(container).toMatchSnapshot();
+ });
+
+ test("renders uninstantiated state", () => {
+ const props = {
+ ...baseProps,
+ uninstantiated: true,
+ };
+
+ const { container } = render(
+ <TooltipProvider>
+ <CellStatusComponent {...props} />
+ </TooltipProvider>,
+ );
+ expect(container).toMatchSnapshot();
+ });
+
+ test("renders interrupted state", () => {
+ const props = {
+ ...baseProps,
+ interrupted: true,
+ elapsedTime: 1500,
+ lastRunStartTimestamp: 1_704_096_000 as Seconds,
+ };
+
+ const { container } = render(
+ <TooltipProvider>
+ <CellStatusComponent {...props} />
+ </TooltipProvider>,
+ );
+ expect(container).toMatchSnapshot();
+ });
+
+ test("renders edited state", () => {
+ const props = {
+ ...baseProps,
+ edited: true,
+ elapsedTime: 1500,
+ lastRunStartTimestamp: 1_704_096_000 as Seconds,
+ };
+
+ const { container } = render(
+ <TooltipProvider>
+ <CellStatusComponent {...props} />
+ </TooltipProvider>,
+ );
+ expect(container).toMatchSnapshot();
+ });
+
+ test("renders stale inputs state", () => {
+ const props = {
+ ...baseProps,
+ staleInputs: true,
+ elapsedTime: 1500,
+ lastRunStartTimestamp: 1_704_096_000 as Seconds,
+ };
+
+ const { container } = render(
+ <TooltipProvider>
+ <CellStatusComponent {...props} />
+ </TooltipProvider>,
+ );
+ expect(container).toMatchSnapshot();
+ });
+
+ test("renders completed run with elapsed time", () => {
+ const props = {
+ ...baseProps,
+ elapsedTime: 1500,
+ lastRunStartTimestamp: 1_704_096_000 as Seconds,
+ };
+
+ const { container } = render(
+ <TooltipProvider>
+ <CellStatusComponent {...props} />
+ </TooltipProvider>,
+ );
+ expect(container).toMatchSnapshot();
+ });
+});
diff --git a/frontend/src/__tests__/__snapshots__/CellStatus.test.tsx.snap b/frontend/src/__tests__/__snapshots__/CellStatus.test.tsx.snap
new file mode 100644
index 0000000000..e36381aa0c
--- /dev/null
+++ b/frontend/src/__tests__/__snapshots__/CellStatus.test.tsx.snap
@@ -0,0 +1,511 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`CellStatusComponent > renders completed run with elapsed time 1`] = `
+<div>
+ <div
+ class="cell-status-icon elapsed-time hover-action"
+ data-state="closed"
+ data-status="idle"
+ data-testid="cell-status"
+ >
+ <span>
+ 1.50s
+ </span>
+ </div>
+</div>
+`;
+
+exports[`CellStatusComponent > renders disabled and stale state 1`] = `
+<div>
+ <div
+ class="cell-status-icon cell-status-stale"
+ data-state="closed"
+ data-status="stale"
+ data-testid="cell-status"
+ >
+ <div
+ class="multi-icon relative w-fit"
+ >
+ <svg
+ class="lucide lucide-ban h-5 w-5"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="1.5"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <circle
+ cx="12"
+ cy="12"
+ r="10"
+ />
+ <path
+ d="m4.9 4.9 14.2 14.2"
+ />
+ </svg>
+ <div
+ class="second-icon absolute bottom-[-2px] right-[-2px] rounded-full"
+ >
+ <svg
+ class="lucide lucide-refresh-cw h-3 w-3"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2.5"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"
+ />
+ <path
+ d="M21 3v5h-5"
+ />
+ <path
+ d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"
+ />
+ <path
+ d="M8 16H3v5"
+ />
+ </svg>
+ </div>
+ </div>
+ </div>
+</div>
+`;
+
+exports[`CellStatusComponent > renders disabled state 1`] = `
+<div>
+ <div
+ class="cell-status-icon cell-status-disabled"
+ data-state="closed"
+ data-status="disabled"
+ data-testid="cell-status"
+ >
+ <svg
+ class="lucide lucide-ban h-5 w-5"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="1.5"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <circle
+ cx="12"
+ cy="12"
+ r="10"
+ />
+ <path
+ d="m4.9 4.9 14.2 14.2"
+ />
+ </svg>
+ </div>
+</div>
+`;
+
+exports[`CellStatusComponent > renders disabled transitively state 1`] = `
+<div>
+ <div
+ class="cell-status-icon cell-status-stale"
+ data-state="closed"
+ data-status="disabled-transitively"
+ data-testid="cell-status"
+ >
+ <div
+ class="multi-icon relative w-fit"
+ >
+ <svg
+ class="lucide lucide-workflow h-5 w-5"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="1.5"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <rect
+ height="8"
+ rx="2"
+ width="8"
+ x="3"
+ y="3"
+ />
+ <path
+ d="M7 11v4a2 2 0 0 0 2 2h4"
+ />
+ <rect
+ height="8"
+ rx="2"
+ width="8"
+ x="13"
+ y="13"
+ />
+ </svg>
+ <div
+ class="second-icon absolute top-[-2px] left-[-2px] rounded-full"
+ >
+ <svg
+ class="lucide lucide-ban h-3 w-3"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2.5"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <circle
+ cx="12"
+ cy="12"
+ r="10"
+ />
+ <path
+ d="m4.9 4.9 14.2 14.2"
+ />
+ </svg>
+ </div>
+ </div>
+ </div>
+</div>
+`;
+
+exports[`CellStatusComponent > renders edited state 1`] = `
+<div>
+ <div
+ class="cell-status-icon flex items-center gap-2"
+ >
+ <div
+ class="cell-status-stale"
+ data-state="closed"
+ data-status="outdated"
+ data-testid="cell-status"
+ >
+ <svg
+ class="lucide lucide-refresh-cw h-5 w-5"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="1.5"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"
+ />
+ <path
+ d="M21 3v5h-5"
+ />
+ <path
+ d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"
+ />
+ <path
+ d="M8 16H3v5"
+ />
+ </svg>
+ </div>
+ <div
+ class="elapsed-time hover-action"
+ data-state="closed"
+ data-status="outdated"
+ data-testid="cell-status"
+ >
+ <span>
+ 1.50s
+ </span>
+ </div>
+ </div>
+</div>
+`;
+
+exports[`CellStatusComponent > renders interrupted state 1`] = `
+<div>
+ <div
+ class="cell-status-icon flex items-center gap-2"
+ >
+ <div
+ class="cell-status-stale"
+ data-state="closed"
+ data-status="outdated"
+ data-testid="cell-status"
+ >
+ <svg
+ class="lucide lucide-refresh-cw h-5 w-5"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="1.5"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"
+ />
+ <path
+ d="M21 3v5h-5"
+ />
+ <path
+ d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"
+ />
+ <path
+ d="M8 16H3v5"
+ />
+ </svg>
+ </div>
+ <div
+ class="elapsed-time hover-action"
+ data-state="closed"
+ data-status="outdated"
+ data-testid="cell-status"
+ >
+ <span>
+ 1.50s
+ </span>
+ </div>
+ </div>
+</div>
+`;
+
+exports[`CellStatusComponent > renders queued state 1`] = `
+<div>
+ <div
+ class="cell-status-icon cell-status-queued"
+ data-state="closed"
+ data-status="queued"
+ data-testid="cell-status"
+ >
+ <svg
+ class="lucide lucide-ellipsis h-5 w-5"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="1.5"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <circle
+ cx="12"
+ cy="12"
+ r="1"
+ />
+ <circle
+ cx="19"
+ cy="12"
+ r="1"
+ />
+ <circle
+ cx="5"
+ cy="12"
+ r="1"
+ />
+ </svg>
+ </div>
+</div>
+`;
+
+exports[`CellStatusComponent > renders running state 1`] = `
+<div>
+ <div
+ class="cell-status-icon elapsed-time running"
+ data-state="closed"
+ data-status="running"
+ data-testid="cell-status"
+ >
+ <span>
+ 0ms
+ </span>
+ </div>
+</div>
+`;
+
+exports[`CellStatusComponent > renders stale and disabled transitively state 1`] = `
+<div>
+ <div
+ class="cell-status-icon cell-status-stale"
+ data-state="closed"
+ data-status="stale"
+ data-testid="cell-status"
+ >
+ <div
+ class="multi-icon relative w-fit"
+ >
+ <svg
+ class="lucide lucide-refresh-cw h-5 w-5"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="1"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"
+ />
+ <path
+ d="M21 3v5h-5"
+ />
+ <path
+ d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"
+ />
+ <path
+ d="M8 16H3v5"
+ />
+ </svg>
+ <div
+ class="second-icon absolute bottom-[-2px] right-[-2px] rounded-full"
+ >
+ <svg
+ class="lucide lucide-ban h-3 w-3"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2.5"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <circle
+ cx="12"
+ cy="12"
+ r="10"
+ />
+ <path
+ d="m4.9 4.9 14.2 14.2"
+ />
+ </svg>
+ </div>
+ </div>
+ </div>
+</div>
+`;
+
+exports[`CellStatusComponent > renders stale inputs state 1`] = `
+<div>
+ <div
+ class="cell-status-icon flex items-center gap-2"
+ >
+ <div
+ class="cell-status-stale"
+ data-state="closed"
+ data-status="outdated"
+ data-testid="cell-status"
+ >
+ <svg
+ class="lucide lucide-refresh-cw h-5 w-5"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="1.5"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"
+ />
+ <path
+ d="M21 3v5h-5"
+ />
+ <path
+ d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"
+ />
+ <path
+ d="M8 16H3v5"
+ />
+ </svg>
+ </div>
+ <div
+ class="elapsed-time hover-action"
+ data-state="closed"
+ data-status="outdated"
+ data-testid="cell-status"
+ >
+ <span>
+ 1.50s
+ </span>
+ </div>
+ </div>
+</div>
+`;
+
+exports[`CellStatusComponent > renders uninstantiated state 1`] = `
+<div>
+ <div
+ class="cell-status-icon flex items-center gap-2"
+ >
+ <div
+ class="cell-status-stale"
+ data-state="closed"
+ data-status="outdated"
+ data-testid="cell-status"
+ >
+ <svg
+ class="lucide lucide-refresh-cw h-5 w-5"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="1.5"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"
+ />
+ <path
+ d="M21 3v5h-5"
+ />
+ <path
+ d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"
+ />
+ <path
+ d="M8 16H3v5"
+ />
+ </svg>
+ </div>
+ </div>
+</div>
+`;
+
+exports[`ElapsedTime component > renders elapsed time correctly 1`] = `
+<div>
+ <span
+ class="tracking-wide font-semibold"
+ >
+ 1.50s
+ </span>
+</div>
+`;
diff --git a/frontend/src/__tests__/components/editor/cell/CellStatus.test.ts b/frontend/src/__tests__/components/editor/cell/CellStatus.test.ts
deleted file mode 100644
index d3b5c5f801..0000000000
--- a/frontend/src/__tests__/components/editor/cell/CellStatus.test.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-/* Copyright 2024 Marimo. All rights reserved. */
-import { formatElapsedTime } from "../../../../components/editor/cell/CellStatus";
-import { describe, expect, test } from "vitest";
-
-describe("formatElapsedTime", () => {
- test("formats milliseconds correctly", () => {
- expect(formatElapsedTime(500)).toBe("500ms");
- expect(formatElapsedTime(50)).toBe("50ms");
- });
-
- test("formats seconds correctly", () => {
- expect(formatElapsedTime(1500)).toBe("1.50s");
- expect(formatElapsedTime(2340)).toBe("2.34s");
- });
-
- test("formats minutes and seconds correctly", () => {
- expect(formatElapsedTime(60 * 1000)).toBe("1m0s");
- expect(formatElapsedTime(90 * 1000)).toBe("1m30s");
- expect(formatElapsedTime(89 * 1000)).toBe("1m29s");
- expect(formatElapsedTime(91 * 1000)).toBe("1m31s");
- expect(formatElapsedTime(150 * 1000)).toBe("2m30s");
- expect(formatElapsedTime(151 * 1000)).toBe("2m31s");
- });
-
- test("handles null input", () => {
- expect(formatElapsedTime(null)).toBe("");
- });
-});
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsx
index ecc9090d24..17d5342a72 100644
--- a/frontend/src/components/editor/Cell.tsx
+++ b/frontend/src/components/editor/Cell.tsx
@@ -15,7 +15,7 @@ import { saveCellConfig, sendStdin } from "@/core/network/requests";
import { autocompletionKeymap } from "@/core/codemirror/cm";
import type { UserConfig } from "../../core/config/config-schema";
import type { CellData, CellRuntimeState } from "../../core/cells/types";
-import type { CellActions } from "../../core/cells/cells";
+import { SETUP_CELL_ID, type CellActions } from "../../core/cells/cells";
import { isUninstantiated } from "../../core/cells/utils";
import { derefNotNull } from "../../utils/dereference";
import { OutputArea } from "./Output";
@@ -49,7 +49,7 @@ import { CollapsedCellBanner, CollapseToggle } from "./cell/collapse";
import { canCollapseOutline } from "@/core/dom/outline";
import { StopButton } from "@/components/editor/cell/StopButton";
import type { CellConfig, RuntimeState } from "@/core/network/types";
-import { MoreHorizontalIcon } from "lucide-react";
+import { HelpCircleIcon, MoreHorizontalIcon } from "lucide-react";
import { Toolbar, ToolbarItem } from "@/components/editor/cell/toolbar";
import { cn } from "@/utils/cn";
import { isErrorMime } from "@/core/mime";
@@ -57,8 +57,9 @@ import { HideCodeButton } from "./code/readonly-python-code";
import { useResizeObserver } from "@/hooks/useResizeObserver";
import type { LanguageAdapterType } from "@/core/codemirror/language/types";
import { Events } from "@/utils/events";
-import { TooltipProvider } from "@/components/ui/tooltip";
+import { Tooltip, TooltipProvider } from "@/components/ui/tooltip";
import { useRunCell } from "./cell/useRunCells";
+import type { Milliseconds, Seconds } from "@/utils/time";
/**
* Hook for handling cell completion logic
@@ -360,8 +361,17 @@ export interface CellProps
*/
allowFocus: boolean;
userConfig: UserConfig;
+ /**
+ * If true, the cell is allowed to be moved left and right.
+ */
canMoveX: boolean;
+ /**
+ * If true, the cell is collapsed.
+ */
isCollapsed: boolean;
+ /**
+ * The number of cells in the column.
+ */
collapseCount: number;
}
@@ -401,6 +411,19 @@ const CellComponent = (
edited,
);
+ if (id === SETUP_CELL_ID) {
+ return (
+ <SetupCellComponent
+ {...props}
+ editorView={editorView}
+ setEditorView={(ev) => {
+ editorView.current = ev;
+ }}
+ outputStale={outputStale}
+ />
+ );
+ }
+
if (mode === "edit") {
return (
<EditableCellComponent
@@ -546,13 +569,6 @@ const EditableCellComponent = ({
// Callback to get the editor view.
const getEditorView = useCallback(() => editorView.current, [editorView]);
- const createBelow = useEvent((opts: { code?: string } = {}) =>
- actions.createNewCell({ cellId, before: false, ...opts }),
- );
- const createAbove = useEvent((opts: { code?: string } = {}) =>
- actions.createNewCell({ cellId, before: true, ...opts }),
- );
-
// Use the extracted hooks
const { closeCompletionHandler, resumeCompletionHandler } = useCellCompletion(
cellRef,
@@ -684,7 +700,7 @@ const EditableCellComponent = ({
// TODO(akshayka): Move to our own Tooltip component once it's easier
// to get the tooltip to show next to the cursor ...
// https://github.com/radix-ui/primitives/discussions/1090
- const cellTitle = () => {
+ const renderCellTitle = () => {
if (cellConfig.disabled) {
return "This cell is disabled";
}
@@ -694,21 +710,6 @@ const EditableCellComponent = ({
return undefined;
};
- const cellStatusComponent = (
- <CellStatusComponent
- status={status}
- staleInputs={staleInputs}
- interrupted={interrupted}
- editing={true}
- edited={edited}
- disabled={cellConfig.disabled ?? false}
- elapsedTime={runElapsedTimeMs}
- runStartTimestamp={runStartTimestamp}
- uninstantiated={uninstantiated}
- lastRunStartTimestamp={lastRunStartTimestamp}
- />
- );
-
return (
<TooltipProvider>
<CellActionsContextMenu
@@ -728,7 +729,7 @@ const EditableCellComponent = ({
onKeyDown={resumeCompletionHandler}
cellId={cellId}
canMoveX={canMoveX}
- title={cellTitle()}
+ title={renderCellTitle()}
>
<div
className={className}
@@ -755,28 +756,18 @@ const EditableCellComponent = ({
onRun={runCell}
/>
</div>
- <div
+ <CellLeftSideActions
+ cellId={cellId}
className={cn(
- "absolute flex flex-col gap-[2px] justify-center h-full left-[-34px] z-20",
isMarkdownCodeHidden && hasOutputAbove && "-top-7",
isMarkdownCodeHidden && hasOutputBelow && "-bottom-8",
isMarkdownCodeHidden &&
isCellButtonsInline &&
"-left-[3.8rem]",
)}
- >
- <CreateCellButton
- tooltipContent={renderShortcut("cell.createAbove")}
- appClosed={appClosed}
- onClick={appClosed ? undefined : createAbove}
- />
- <div className="flex-1" />
- <CreateCellButton
- tooltipContent={renderShortcut("cell.createBelow")}
- appClosed={appClosed}
- onClick={appClosed ? undefined : createBelow}
- />
- </div>
+ appClosed={appClosed}
+ actions={actions}
+ />
<CellEditor
theme={theme}
showPlaceholder={showPlaceholder}
@@ -797,18 +788,21 @@ const EditableCellComponent = ({
languageAdapter={languageAdapter}
setLanguageAdapter={setLanguageAdapter}
/>
- <div
+ <CellRightSideActions
className={cn(
- "shoulder-right z-20",
isMarkdownCodeHidden && cellOutput === "below" && "top-14",
)}
- >
- {!isCellStatusInline && cellStatusComponent}
- <div className="flex gap-2 items-end">
- <CellDragHandle />
- {isCellStatusInline && cellStatusComponent}
- </div>
- </div>
+ edited={edited}
+ status={status}
+ isCellStatusInline={isCellStatusInline}
+ uninstantiated={uninstantiated}
+ disabled={cellConfig.disabled}
+ runElapsedTimeMs={runElapsedTimeMs}
+ runStartTimestamp={runStartTimestamp}
+ lastRunStartTimestamp={lastRunStartTimestamp}
+ staleInputs={staleInputs}
+ interrupted={interrupted}
+ />
<div className="shoulder-bottom hover-action">
{canDelete && isCellCodeShown && (
<DeleteButton
@@ -854,6 +848,96 @@ 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}
+ />
+ );
+
+ return (
+ <div className={cn("shoulder-right z-20", className)}>
+ {!isCellStatusInline && cellStatusComponent}
+ <div className="flex gap-2 items-end">
+ <CellDragHandle />
+ {isCellStatusInline && cellStatusComponent}
+ </div>
+ </div>
+ );
+};
+
+const CellLeftSideActions = (props: {
+ className?: string;
+ cellId: CellId;
+ appClosed: boolean;
+ actions: CellComponentActions;
+}) => {
+ const { className, appClosed, actions, cellId } = props;
+
+ const createBelow = useEvent((opts: { code?: string } = {}) =>
+ actions.createNewCell({ cellId, before: false, ...opts }),
+ );
+ const createAbove = useEvent((opts: { code?: string } = {}) =>
+ 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")}
+ appClosed={appClosed}
+ onClick={appClosed ? undefined : createAbove}
+ />
+ <div className="flex-1" />
+ <CreateCellButton
+ tooltipContent={renderShortcut("cell.createBelow")}
+ appClosed={appClosed}
+ onClick={appClosed ? undefined : createBelow}
+ />
+ </div>
+ );
+};
+
interface CellToolbarProps {
edited: boolean;
appClosed: boolean;
@@ -865,6 +949,7 @@ interface CellToolbarProps {
cellActionDropdownRef: React.RefObject<CellActionsDropdownHandle>;
cellId: CellId;
name: string;
+ includeCellActions?: boolean;
getEditorView: () => EditorView | null;
onRun: () => void;
}
@@ -882,6 +967,7 @@ const CellToolbar = ({
cellId,
getEditorView,
name,
+ includeCellActions = true,
}: CellToolbarProps) => {
return (
<Toolbar
@@ -899,25 +985,301 @@ const CellToolbar = ({
needsRun={needsRun}
/>
<StopButton status={status} appClosed={appClosed} />
- <CellActionsDropdown
- ref={cellActionDropdownRef}
+ {includeCellActions && (
+ <CellActionsDropdown
+ ref={cellActionDropdownRef}
+ cellId={cellId}
+ status={status}
+ getEditorView={getEditorView}
+ name={name}
+ config={cellConfig}
+ hasOutput={hasOutput}
+ hasConsoleOutput={hasConsoleOutput}
+ >
+ <ToolbarItem
+ variant={"green"}
+ tooltip={null}
+ data-testid="cell-actions-button"
+ >
+ <MoreHorizontalIcon strokeWidth={1.5} />
+ </ToolbarItem>
+ </CellActionsDropdown>
+ )}
+ </Toolbar>
+ );
+};
+
+/**
+ * A cell that is not allowed to be deleted or moved.
+ * It also has no outputs.
+ */
+const SetupCellComponent = ({
+ theme,
+ showPlaceholder,
+ allowFocus,
+ id: cellId,
+ code,
+ output,
+ consoleOutputs,
+ status,
+ runStartTimestamp,
+ lastRunStartTimestamp,
+ runElapsedTimeMs,
+ edited,
+ interrupted,
+ errored,
+ stopped,
+ staleInputs,
+ serializedEditorState,
+ debuggerActive,
+ appClosed,
+ canDelete,
+ actions,
+ deleteCell,
+ userConfig,
+ config: cellConfig,
+ canMoveX,
+ name,
+ editorView,
+ setEditorView,
+}: CellProps & {
+ editorView: React.RefObject<EditorView>;
+ setEditorView: (view: EditorView) => void;
+ outputStale: boolean;
+}) => {
+ const cellRef = useRef<HTMLDivElement>(null);
+ const cellActionDropdownRef = useRef<CellActionsDropdownHandle>(null);
+ // DOM node where the editorView will be mounted
+ const editorViewParentRef = useRef<HTMLDivElement>(null);
+
+ const setAiCompletionCell = useSetAtom(aiCompletionCellAtom);
+ const runCell = useRunCell(cellId);
+
+ const disabledOrAncestorDisabled =
+ cellConfig.disabled || status === "disabled-transitively";
+
+ const uninstantiated = isUninstantiated({
+ executionTime: runElapsedTimeMs,
+ status,
+ errored,
+ interrupted,
+ stopped,
+ });
+
+ const needsRun =
+ edited || interrupted || (staleInputs && !disabledOrAncestorDisabled);
+ const loading = status === "running" || status === "queued";
+
+ // console output is cleared immediately on run, so check for queued instead
+ // of loading to determine staleness
+ const consoleOutputStale =
+ (status === "queued" || edited || staleInputs) && !interrupted;
+
+ // Callback to get the editor view.
+ const getEditorView = useCallback(() => editorView.current, [editorView]);
+
+ // Use the extracted hooks
+ const { closeCompletionHandler, resumeCompletionHandler } = useCellCompletion(
+ cellRef,
+ editorView,
+ );
+
+ // Hotkey listeners
+ useCellHotkeys(
+ cellRef,
+ cellId,
+ runCell,
+ actions,
+ canMoveX,
+ cellConfig,
+ editorView,
+ setAiCompletionCell,
+ cellActionDropdownRef,
+ );
+
+ // Other keyboard listeners
+ useCellKeyboardListener(
+ cellRef,
+ cellId,
+ actions,
+ Functions.NOOP,
+ userConfig,
+ true,
+ );
+
+ const hasOutput = !isOutputEmpty(output);
+ const hasConsoleOutput = consoleOutputs.length > 0;
+ const isErrorOutput = isErrorMime(output?.mimetype);
+
+ const className = clsx(
+ "marimo-cell",
+ "hover-actions-parent z-10 border shadow-sm",
+ "!border-[var(--blue-5)] !rounded-sm",
+ {
+ "needs-run": needsRun,
+ "has-error": errored,
+ stopped: stopped,
+ },
+ );
+
+ const HTMLId = HTMLCellId.create(cellId);
+
+ const handleRefactorWithAI = useEvent((opts: { prompt: string }) => {
+ setAiCompletionCell({ cellId, initialPrompt: opts.prompt });
+ });
+
+ // TODO(akshayka): Move to our own Tooltip component once it's easier
+ // to get the tooltip to show next to the cursor ...
+ // https://github.com/radix-ui/primitives/discussions/1090
+ const renderCellTitle = () => {
+ if (cellConfig.disabled) {
+ return "This cell is disabled";
+ }
+ if (status === "disabled-transitively") {
+ return "This cell has a disabled ancestor";
+ }
+ return undefined;
+ };
+
+ return (
+ <TooltipProvider>
+ <CellActionsContextMenu
cellId={cellId}
+ config={cellConfig}
status={status}
getEditorView={getEditorView}
- name={name}
- config={cellConfig}
hasOutput={hasOutput}
hasConsoleOutput={hasConsoleOutput}
+ name={name}
>
- <ToolbarItem
- variant={"green"}
- tooltip={null}
- data-testid="cell-actions-button"
+ <div
+ className={className}
+ data-status={status}
+ id={HTMLId}
+ ref={cellRef}
+ onBlur={closeCompletionHandler}
+ onKeyDown={resumeCompletionHandler}
+ title={renderCellTitle()}
+ data-cell-id={cellId}
+ data-cell-name={name}
+ data-setup-cell={true}
>
- <MoreHorizontalIcon strokeWidth={1.5} />
- </ToolbarItem>
- </CellActionsDropdown>
- </Toolbar>
+ <div className={cn("tray")} data-hidden={false}>
+ <div className="absolute right-2 -top-4 z-10">
+ <CellToolbar
+ edited={edited}
+ appClosed={appClosed}
+ status={status}
+ cellConfig={cellConfig}
+ needsRun={needsRun}
+ hasOutput={hasOutput}
+ hasConsoleOutput={hasConsoleOutput}
+ cellActionDropdownRef={cellActionDropdownRef}
+ cellId={cellId}
+ name={name}
+ getEditorView={getEditorView}
+ onRun={runCell}
+ includeCellActions={false}
+ />
+ </div>
+ <CellEditor
+ theme={theme}
+ showPlaceholder={showPlaceholder}
+ allowFocus={allowFocus}
+ id={cellId}
+ code={code}
+ config={cellConfig}
+ status={status}
+ serializedEditorState={serializedEditorState}
+ runCell={runCell}
+ setEditorView={setEditorView}
+ userConfig={userConfig}
+ editorViewRef={editorView}
+ editorViewParentRef={editorViewParentRef}
+ hidden={false}
+ hasOutput={hasOutput}
+ temporarilyShowCode={Functions.NOOP}
+ languageAdapter={"python"}
+ setLanguageAdapter={Functions.NOOP}
+ showLanguageToggles={false}
+ />
+ <CellRightSideActions
+ edited={edited}
+ status={status}
+ isCellStatusInline={false}
+ uninstantiated={uninstantiated}
+ disabled={cellConfig.disabled}
+ runElapsedTimeMs={runElapsedTimeMs}
+ runStartTimestamp={runStartTimestamp}
+ lastRunStartTimestamp={lastRunStartTimestamp}
+ staleInputs={staleInputs}
+ interrupted={interrupted}
+ />
+ <div className="shoulder-bottom hover-action">
+ {canDelete && (
+ <DeleteButton
+ appClosed={appClosed}
+ status={status}
+ onClick={() => {
+ if (!loading && !appClosed) {
+ deleteCell({ cellId });
+ }
+ }}
+ />
+ )}
+ </div>
+ </div>
+ <div className="py-1 px-2 flex justify-end gap-2 last:rounded-b">
+ <span className="text-muted-foreground text-xs font-bold">
+ setup cell
+ </span>
+ <Tooltip
+ content={
+ <span className="max-w-16">
+ This <b>setup cell</b> is guaranteed to run before all other
+ cells. Include <br />
+ initialization or imports and constants required by top-level
+ functions.
+ </span>
+ }
+ >
+ <HelpCircleIcon
+ size={16}
+ strokeWidth={1.5}
+ className="rounded-lg text-muted-foreground"
+ />
+ </Tooltip>
+ </div>
+ {isErrorOutput && (
+ <OutputArea
+ allowExpand={true}
+ forceExpand={true}
+ output={output}
+ className="output-area"
+ cellId={cellId}
+ stale={false}
+ />
+ )}
+ <ConsoleOutput
+ consoleOutputs={consoleOutputs}
+ stale={consoleOutputStale}
+ // Don't show name
+ cellName={"_"}
+ onRefactorWithAI={handleRefactorWithAI}
+ onSubmitDebugger={(text, index) => {
+ actions.setStdinResponse({
+ cellId,
+ response: text,
+ outputIndex: index,
+ });
+ sendStdin({ text });
+ }}
+ cellId={cellId}
+ debuggerActive={debuggerActive}
+ />
+ </div>
+ </CellActionsContextMenu>
+ </TooltipProvider>
);
};
diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsx
index 0d5cb9b2d6..241ad57c8e 100644
--- a/frontend/src/components/editor/actions/useNotebookActions.tsx
+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx
@@ -37,6 +37,7 @@ import {
GithubIcon,
MessagesSquareIcon,
YoutubeIcon,
+ DiamondPlusIcon,
} from "lucide-react";
import { commandPaletteAtom } from "../controls/command-palette";
import {
@@ -81,6 +82,7 @@ import { settingDialogAtom } from "@/components/app-config/state";
import { AddDatabaseDialogContent } from "../database/add-database-form";
import { useHideAllMarkdownCode } from "./useHideAllMarkdownCode";
import { Constants } from "@/core/constants";
+import { getFeatureFlag } from "@/core/config/feature-flag";
const NOOP_HANDLER = (event?: Event) => {
event?.preventDefault();
@@ -96,8 +98,12 @@ export function useNotebookActions() {
const kioskMode = useAtomValue(kioskModeAtom);
const hideAllMarkdownCode = useHideAllMarkdownCode();
- const { updateCellConfig, undoDeleteCell, clearAllCellOutputs } =
- useCellActions();
+ const {
+ updateCellConfig,
+ undoDeleteCell,
+ clearAllCellOutputs,
+ upsertSetupCell,
+ } = useCellActions();
const restartKernel = useRestartKernel();
const runAllCells = useRunAllCells();
const copyNotebook = useCopyNotebook(filename);
@@ -369,6 +375,16 @@ export function useNotebookActions() {
label: "Hide all markdown code",
handle: hideAllMarkdownCode,
},
+ {
+ icon: <DiamondPlusIcon size={14} strokeWidth={1.5} />,
+ label: "Add setup cell",
+ hidden: !getFeatureFlag("setup_cell"),
+ handle: () => {
+ upsertSetupCell({
+ code: "# Initialization code that runs before all other cells",
+ });
+ },
+ },
{
icon: <XCircleIcon size={14} strokeWidth={1.5} />,
label: "Clear all outputs",
diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx
index fe93047653..ab948fccf9 100644
--- a/frontend/src/components/editor/cell/code/cell-editor.tsx
+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx
@@ -58,6 +58,7 @@ export interface CellEditorProps
hidden?: boolean;
hasOutput?: boolean;
languageAdapter: LanguageAdapterType | undefined;
+ showLanguageToggles?: boolean;
setLanguageAdapter: React.Dispatch<
React.SetStateAction<LanguageAdapterType | undefined>
>;
@@ -86,6 +87,7 @@ const CellEditorInternal = ({
temporarilyShowCode,
languageAdapter,
setLanguageAdapter,
+ showLanguageToggles = true,
}: CellEditorProps) => {
const [aiCompletionCell, setAiCompletionCell] = useAtom(aiCompletionCellAtom);
const setLastFocusedCellId = useSetLastFocusedCellId();
@@ -400,7 +402,7 @@ const CellEditorInternal = ({
editorView={editorViewRef.current}
ref={editorViewParentRef}
/>
- {!hidden && (
+ {!hidden && showLanguageToggles && (
<div className="absolute top-1 right-5">
<LanguageToggles
code={code}
diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsx
index 30bc972ff6..a9c95e4b7a 100644
--- a/frontend/src/components/editor/renderers/CellArray.tsx
+++ b/frontend/src/components/editor/renderers/CellArray.tsx
@@ -11,6 +11,7 @@ import {
columnIdsAtom,
type NotebookState,
useCellActions,
+ SETUP_CELL_ID,
} from "../../../core/cells/cells";
import type { AppConfig, UserConfig } from "../../../core/config/config-schema";
import type { AppMode } from "../../../core/mode";
@@ -63,6 +64,8 @@ interface CellArrayProps {
export const CellArray: React.FC<CellArrayProps> = (props) => {
const columnIds = useAtomValue(columnIdsAtom);
+
+ // Setup context for sorting
return (
<SortableCellsProvider multiColumn={props.appConfig.width === "columns"}>
<SortableContext
@@ -114,6 +117,7 @@ const CellArrayInternal: React.FC<CellArrayProps> = ({
const columns = notebook.cellIds.getColumns();
const hasOnlyOneCell = notebook.cellIds.hasOnlyOneId();
+ const hasSetupCell = notebook.cellIds.inOrderIds.includes(SETUP_CELL_ID);
return (
<VerticalLayoutWrapper
@@ -132,7 +136,7 @@ const CellArrayInternal: React.FC<CellArrayProps> = ({
)}
>
{columns.map((column, index) => (
- <SortableColumn
+ <CellColumn
key={column.id}
column={column}
index={index}
@@ -146,6 +150,7 @@ const CellArrayInternal: React.FC<CellArrayProps> = ({
theme={theme}
hasOnlyOneCell={hasOnlyOneCell}
invisible={invisible}
+ hasSetupCell={hasSetupCell}
onDeleteCell={onDeleteCell}
/>
))}
@@ -155,7 +160,10 @@ const CellArrayInternal: React.FC<CellArrayProps> = ({
);
};
-const SortableColumn: React.FC<{
+/**
+ * A single column of cells.
+ */
+const CellColumn: React.FC<{
column: CollapsibleTree<CellId>;
index: number;
columnsLength: number;
@@ -168,6 +176,7 @@ const SortableColumn: React.FC<{
theme: Theme;
hasOnlyOneCell: boolean;
invisible: boolean;
+ hasSetupCell: boolean;
onDeleteCell: (payload: { cellId: CellId }) => void;
}> = ({
column,
@@ -182,8 +191,11 @@ const SortableColumn: React.FC<{
theme,
hasOnlyOneCell,
invisible,
+ hasSetupCell,
onDeleteCell,
}) => {
+ const appClosed = connStatus.state !== WebSocketState.OPEN;
+
return (
<Column
columnId={column.id}
@@ -206,7 +218,40 @@ const SortableColumn: React.FC<{
items={column.topLevelIds}
strategy={verticalListSortingStrategy}
>
+ {/* Render the setup cell first, always */}
+ {index === 0 && hasSetupCell && (
+ <Cell
+ key={SETUP_CELL_ID}
+ theme={theme}
+ showPlaceholder={false}
+ allowFocus={!invisible}
+ {...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}
+ appClosed={appClosed}
+ ref={notebook.cellHandles[SETUP_CELL_ID]}
+ userConfig={userConfig}
+ isCollapsed={false}
+ collapseCount={0}
+ canMoveX={false}
+ actions={actions}
+ deleteCell={onDeleteCell}
+ />
+ )}
+
{column.topLevelIds.map((cellId) => {
+ // Skip the setup cell later
+ if (cellId === SETUP_CELL_ID) {
+ return null;
+ }
+
const cellData = notebook.cellData[cellId];
const cellRuntime = notebook.cellRuntime[cellId];
return (
@@ -235,7 +280,7 @@ const SortableColumn: React.FC<{
serializedEditorState={cellData.serializedEditorState}
canDelete={!hasOnlyOneCell}
mode={mode}
- appClosed={connStatus.state !== WebSocketState.OPEN}
+ appClosed={appClosed}
ref={notebook.cellHandles[cellId]}
userConfig={userConfig}
debuggerActive={cellRuntime.debuggerActive}
diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.ts
index f2fe26602f..1afebac7b4 100644
--- a/frontend/src/core/cells/__tests__/cells.test.ts
+++ b/frontend/src/core/cells/__tests__/cells.test.ts
@@ -10,6 +10,7 @@ import {
} from "vitest";
import {
type NotebookState,
+ SETUP_CELL_ID,
exportedForTesting,
flattenTopLevelNotebookCells,
} from "../cells";
@@ -1914,4 +1915,53 @@ describe("cell reducer", () => {
"
`);
});
+
+ it("can create and update a setup cell", () => {
+ // Create the setup cell
+ actions.upsertSetupCell({ code: "# Setup code" });
+
+ // Check that setup cell was created
+ expect(state.cellData[SETUP_CELL_ID].id).toBe(SETUP_CELL_ID);
+ expect(state.cellData[SETUP_CELL_ID].name).toBe("setup");
+ expect(state.cellData[SETUP_CELL_ID].code).toBe("# Setup code");
+ expect(state.cellData[SETUP_CELL_ID].edited).toBe(true);
+ expect(state.cellIds.inOrderIds).toContain(SETUP_CELL_ID);
+
+ // Update the setup cell
+ actions.upsertSetupCell({ code: "# Updated setup code" });
+
+ // Check that the same setup cell was updated, not duplicated
+ expect(state.cellData[SETUP_CELL_ID].code).toBe("# Updated setup code");
+ expect(state.cellData[SETUP_CELL_ID].edited).toBe(true);
+ expect(state.cellIds.inOrderIds).toContain(SETUP_CELL_ID);
+ });
+
+ it("can delete and undelete the setup cell", () => {
+ // Create the setup cell
+ actions.upsertSetupCell({ code: "# Setup code" });
+
+ // Check that setup cell was created
+ expect(state.cellData[SETUP_CELL_ID].id).toBe(SETUP_CELL_ID);
+ expect(state.cellData[SETUP_CELL_ID].name).toBe("setup");
+ expect(state.cellData[SETUP_CELL_ID].code).toBe("# Setup code");
+ expect(state.cellData[SETUP_CELL_ID].edited).toBe(true);
+ expect(state.cellIds.inOrderIds).toContain(SETUP_CELL_ID);
+
+ // Delete the setup cell
+ actions.deleteCell({ cellId: SETUP_CELL_ID });
+
+ // Check that setup cell was deleted
+ expect(state.cellData[SETUP_CELL_ID]).toBeDefined(); // we keep old state
+ expect(state.cellIds.inOrderIds).not.toContain(SETUP_CELL_ID);
+
+ // Undo delete the setup cell
+ actions.undoDeleteCell();
+
+ // Check that setup cell was restored
+ expect(state.cellData[SETUP_CELL_ID].id).toBe(SETUP_CELL_ID);
+ expect(state.cellData[SETUP_CELL_ID].name).toBe("setup");
+ expect(state.cellData[SETUP_CELL_ID].code).toBe("# Setup code");
+ expect(state.cellData[SETUP_CELL_ID].edited).toBe(true);
+ expect(state.cellIds.inOrderIds).toContain(SETUP_CELL_ID);
+ });
});
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index f6a8f68d7d..866421a0ad 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -51,6 +51,11 @@ import { isEqual, zip } from "lodash-es";
import { isErrorMime } from "../mime";
export const SCRATCH_CELL_ID = "__scratch__" as CellId;
+export const SETUP_CELL_ID = "setup" as CellId;
+
+export function isSetupCell(cellId: CellId): boolean {
+ return cellId === SETUP_CELL_ID;
+}
/**
* The state of the notebook.
@@ -83,6 +88,7 @@ export interface NotebookState {
serializedEditorState: any;
column: CellColumnId;
index: CellIndex;
+ isSetupCell: boolean;
}>;
/**
* Key of cell to scroll to; typically set by actions that re-order the cell
@@ -617,6 +623,7 @@ const {
serializedEditorState: serializedEditorState,
column: column.id,
index: cellIndex,
+ isSetupCell: cellId === SETUP_CELL_ID,
},
],
scrollKey: scrollKey,
@@ -634,9 +641,10 @@ const {
serializedEditorState = { doc: "" },
column,
index,
+ isSetupCell,
} = mostRecentlyDeleted;
- const cellId = CellId.create();
+ const cellId = isSetupCell ? SETUP_CELL_ID : CellId.create();
const undoCell = createCell({
id: cellId,
name,
@@ -1194,6 +1202,45 @@ const {
cellRuntime: newCellRuntime,
};
},
+ upsertSetupCell: (state, action: { code: string }) => {
+ const { code } = action;
+
+ // First check if setup cell already exists
+ if (SETUP_CELL_ID in state.cellData) {
+ // Update existing setup cell
+ return updateCellData(state, SETUP_CELL_ID, (cell) => ({
+ ...cell,
+ code,
+ edited: code.trim() !== cell.lastCodeRun?.trim(),
+ }));
+ }
+
+ return {
+ ...state,
+ cellIds: state.cellIds.insertId(
+ SETUP_CELL_ID,
+ state.cellIds.atOrThrow(0).id,
+ 0,
+ ),
+ cellData: {
+ ...state.cellData,
+ [SETUP_CELL_ID]: createCell({
+ id: SETUP_CELL_ID,
+ name: SETUP_CELL_ID,
+ code,
+ edited: Boolean(code),
+ }),
+ },
+ cellRuntime: {
+ ...state.cellRuntime,
+ [SETUP_CELL_ID]: createCellRuntimeState(),
+ },
+ cellHandles: {
+ ...state.cellHandles,
+ [SETUP_CELL_ID]: createRef(),
+ },
+ };
+ },
});
// Helper function to update a cell in the array
diff --git a/frontend/src/core/cells/names.ts b/frontend/src/core/cells/names.ts
index e8e62219db..b41d11df7b 100644
--- a/frontend/src/core/cells/names.ts
+++ b/frontend/src/core/cells/names.ts
@@ -2,8 +2,8 @@
export const DEFAULT_CELL_NAME = "_";
-// Generated with `python scripts/print_banned_cell_names.py`
const DISALLOWED_NAMES = new Set([
+ // Generated with `python scripts/print_banned_cell_names.py`
"__*",
"marimo",
"app",
@@ -44,6 +44,8 @@ const DISALLOWED_NAMES = new Set([
"with",
"yield",
"None",
+ // Special case for the setup cell
+ "setup",
]);
/**
diff --git a/frontend/src/core/config/feature-flag.tsx b/frontend/src/core/config/feature-flag.tsx
index 16e65dcf80..98ca70b798 100644
--- a/frontend/src/core/config/feature-flag.tsx
+++ b/frontend/src/core/config/feature-flag.tsx
@@ -13,6 +13,7 @@ export interface ExperimentalFeatures {
scratchpad: boolean;
rtc_v2: boolean;
reactive_tests: boolean;
+ setup_cell: boolean;
// Add new feature flags here
}
@@ -23,6 +24,7 @@ const defaultValues: ExperimentalFeatures = {
scratchpad: true,
rtc_v2: false,
reactive_tests: false,
+ setup_cell: false,
};
export function getFeatureFlag<T extends keyof ExperimentalFeatures>(