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
fix(frontend): restore scratchpad editor after panel hide (#10384)
Shahmir Varqha22fd6e761784
diff --git a/frontend/src/components/editor/cell/code/__tests__/cell-editor-activity-lifecycle.test.ts b/frontend/src/components/editor/cell/code/__tests__/cell-editor-activity-lifecycle.test.tsnew file mode 100644index 0000000000..b95d51446c--- /dev/null+++ b/frontend/src/components/editor/cell/code/__tests__/cell-editor-activity-lifecycle.test.ts@@ -0,0 +1,250 @@+/* Copyright 2026 Marimo. All rights reserved. */++/**+ * Simulates React Activity's effect teardown when mode switches to "hidden":+ * all useEffect cleanups run. On "visible", setups re-run (cleanups do not run+ * again). Component state and DOM are preserved — only effects cycle.+ *+ * Registration order matches cell-editor.tsx: mount effect runs before destroy+ * effect setup. With async editor creation (editorMountScheduler), destroy+ * captures null initially; with sync creation it captures the live editor.+ */+import { EditorState } from "@codemirror/state";+import { EditorView } from "@codemirror/view";+import { describe, expect, it } from "vitest";+import { Functions } from "@/utils/functions";++interface EffectRegistration {+ cleanup: () => void;+}++function createActivitySimulator() {+ const effects: EffectRegistration[] = [];++ return {+ /** Register effects in order — each setup runs synchronously, like React. */+ useEffect(setup: () => (() => void) | undefined) {+ const cleanup = setup() ?? Functions.NOOP;+ effects.push({ cleanup });+ },+ hide() {+ for (const effect of effects) {+ effect.cleanup();+ }+ },+ show() {+ effects.length = 0;+ },+ };+}++function createEditor(doc = "hello") {+ return new EditorView({+ state: EditorState.create({ doc }),+ });+}++interface RegisterCellEditorEffectsOptions {+ activity: ReturnType<typeof createActivitySimulator>;+ editorViewRef: { current: EditorView | null };+ destroyPattern: "old" | "pr";+ onDestroy?: () => void;+ /** When true, editor creation is deferred like editorMountScheduler.request */+ asyncMount?: boolean;+}++function registerCellEditorEffects({+ activity,+ editorViewRef,+ destroyPattern,+ onDestroy,+ asyncMount = false,+}: RegisterCellEditorEffectsOptions) {+ activity.useEffect(() => {+ if (editorViewRef.current !== null) {+ return;+ }+ let cancelled = false;+ const mount = () => {+ if (!cancelled && editorViewRef.current === null) {+ editorViewRef.current = createEditor();+ }+ };+ if (asyncMount) {+ const id = setTimeout(mount, 0);+ return () => {+ cancelled = true;+ clearTimeout(id);+ };+ }+ mount();+ return () => {+ cancelled = true;+ };+ });++ if (destroyPattern === "old") {+ activity.useEffect(() => {+ const ev = editorViewRef.current;+ return () => {+ if (ev) {+ ev.destroy();+ onDestroy?.();+ }+ };+ });+ } else {+ activity.useEffect(() => {+ return () => {+ if (editorViewRef.current) {+ editorViewRef.current.destroy();+ onDestroy?.();+ }+ editorViewRef.current = null;+ };+ });+ }+}++describe("CellEditor Activity lifecycle (simulated)", () => {+ it("old destroy pattern (sync mount): first hide/show leaves stale ref", () => {+ const editorViewRef = { current: null as EditorView | null };+ let destroyCount = 0;+ const activity = createActivitySimulator();++ registerCellEditorEffects({+ activity,+ editorViewRef,+ destroyPattern: "old",+ onDestroy: () => {+ destroyCount++;+ },+ });+ const liveEditor = editorViewRef.current;+ expect(liveEditor).not.toBeNull();++ activity.hide();+ expect(destroyCount).toBeGreaterThan(0);+ expect(editorViewRef.current).toBe(liveEditor);++ activity.show();+ registerCellEditorEffects({+ activity,+ editorViewRef,+ destroyPattern: "old",+ });+ expect(editorViewRef.current).toBe(liveEditor);+ });++ it("old destroy pattern (async mount): first hide/show preserves editor", async () => {+ const editorViewRef = { current: null as EditorView | null };+ let destroyCount = 0;+ const activity = createActivitySimulator();++ registerCellEditorEffects({+ activity,+ editorViewRef,+ destroyPattern: "old",+ onDestroy: () => {+ destroyCount++;+ },+ asyncMount: true,+ });+ await new Promise((r) => setTimeout(r, 0));+ const liveEditor = editorViewRef.current;+ expect(liveEditor).not.toBeNull();++ // Destroy effect captured null at setup (editor created async after effects)+ activity.hide();+ expect(destroyCount).toBe(0);+ expect(editorViewRef.current).toBe(liveEditor);++ activity.show();+ registerCellEditorEffects({+ activity,+ editorViewRef,+ destroyPattern: "old",+ asyncMount: true,+ });+ await new Promise((r) => setTimeout(r, 0));+ expect(editorViewRef.current).toBe(liveEditor);+ });++ it("PR destroy pattern (async mount): recreates on first hide/show", async () => {+ const editorViewRef = { current: null as EditorView | null };+ const activity = createActivitySimulator();++ registerCellEditorEffects({+ activity,+ editorViewRef,+ destroyPattern: "pr",+ asyncMount: true,+ });+ await new Promise((r) => setTimeout(r, 0));+ const firstEditor = editorViewRef.current;++ activity.hide();+ expect(editorViewRef.current).toBeNull();++ activity.show();+ registerCellEditorEffects({+ activity,+ editorViewRef,+ destroyPattern: "pr",+ asyncMount: true,+ });+ await new Promise((r) => setTimeout(r, 0));+ expect(editorViewRef.current).not.toBeNull();+ expect(editorViewRef.current).not.toBe(firstEditor);+ });++ it("PR destroy pattern: nulls ref on hide so mount recreates on show", () => {+ const editorViewRef = { current: null as EditorView | null };+ const activity = createActivitySimulator();++ registerCellEditorEffects({+ activity,+ editorViewRef,+ destroyPattern: "pr",+ });+ const firstEditor = editorViewRef.current;++ activity.hide();+ expect(editorViewRef.current).toBeNull();++ activity.show();+ registerCellEditorEffects({+ activity,+ editorViewRef,+ destroyPattern: "pr",+ });+ expect(editorViewRef.current).not.toBeNull();+ expect(editorViewRef.current).not.toBe(firstEditor);+ });++ it("PR destroy pattern: stable across repeated hide/show cycles", () => {+ const editorViewRef = { current: null as EditorView | null };+ const activity = createActivitySimulator();++ for (let i = 0; i < 3; i++) {+ registerCellEditorEffects({+ activity,+ editorViewRef,+ destroyPattern: "pr",+ });+ expect(editorViewRef.current).not.toBeNull();++ activity.hide();+ expect(editorViewRef.current).toBeNull();++ activity.show();+ }++ registerCellEditorEffects({+ activity,+ editorViewRef,+ destroyPattern: "pr",+ });+ expect(editorViewRef.current).not.toBeNull();+ });+});diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsxindex ac1206bb16..ff6187b641 100644--- a/frontend/src/components/editor/cell/code/cell-editor.tsx+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx@@ -39,7 +39,7 @@ import type { UserConfig } from "@/core/config/config-schema";import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";import { connectionAtom } from "@/core/network/connection";import { useRequestClient } from "@/core/network/requests";-import { isRtcEnabled } from "@/core/rtc/state";+import { canUseRtc, isRtcEnabled } from "@/core/rtc/state";import { useSaveNotebook } from "@/core/saving/save-component";import { isAppConnecting } from "@/core/websocket/connection-utils";import type { Theme } from "@/theme/useTheme";@@ -342,7 +342,7 @@ const CellEditorInternal = ({saveOrNameNotebook,]);- const rtcEnabled = isRtcEnabled();+ const rtcEnabled = isRtcEnabled() && canUseRtc(cellId);const handleInitializeEditor = useEvent(() => {// If rtc is enabled, use collaborative editingif (rtcEnabled) {@@ -451,6 +451,7 @@ const CellEditorInternal = ({setIsEditorMounted(true);return;}+ setIsEditorMounted(false);if (serializedEditorState !== null) {handleDeserializeEditor();setIsEditorMounted(true);@@ -479,11 +480,12 @@ const CellEditorInternal = ({handleReconfigureEditor();}, [handleReconfigureEditor, extensions, editorViewRef]);- // Destroy the editor when the component is unmounted+ // Destroy the editor when the component is unmounted. Read the ref in cleanup+ // (not setup) so Activity hide/show cycles don't leave a stale destroyed view.useEffect(() => {- const ev = editorViewRef.current;return () => {- ev?.destroy();+ editorViewRef.current?.destroy();+ editorViewRef.current = null;};}, [editorViewRef]);@@ -635,14 +637,18 @@ CellCodeMirrorEditor.displayName = "CellCodeMirrorEditor";// Wait until the websocket connection is open before rendering the editor// This is used for real-time collaboration since the backend needs the connection started// before connecting the rtc websockets-function WithWaitUntilConnected<T extends {}>(+function WithWaitUntilConnected<T extends Pick<CellEditorProps, "id">>(Component: React.ComponentType<T>,) {const WaitUntilConnectedComponent = (props: T) => {const connection = useAtomValue(connectionAtom);const [rtcDoc, setRtcDoc] = useAtom(connectedDocAtom);- if (isAppConnecting(connection.state) || rtcDoc === undefined) {+ if (+ isRtcEnabled() &&+ canUseRtc(props.id) &&+ (isAppConnecting(connection.state) || rtcDoc === undefined)+ ) {return (<div className="flex h-full w-full items-baseline p-4"><DelayMount milliseconds={1000} fallback={null}>diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex e2a82f5454..e5b6f2ce47 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -28,7 +28,7 @@ import { findCollapseRange, mergeOutlines } from "../dom/outline";import type { CellMessage } from "../kernel/messages";import { isErrorMime } from "../mime";import type { CellConfig } from "../network/types";-import { isRtcEnabled } from "../rtc/state";+import { canUseRtc, isRtcEnabled } from "../rtc/state";import { createDeepEqualAtom, store } from "../state/jotai";import { isWasm } from "../wasm/utils";import { prepareCellForExecution, transitionCell } from "./cell";@@ -1043,9 +1043,9 @@ const {};}- // Update codemirror if mounted- // If RTC is enabled, the editor view will already be updated, so we don't need to do this- if (!isRtcEnabled()) {+ // Update codemirror if mounted. RTC-backed cells sync via Loro; others+ // (e.g. scratchpad) still need an explicit editor update.+ if (!isRtcEnabled() || !canUseRtc(cellId)) {const cellHandle = nextState.cellHandles[cellId].current;if (cellHandle?.editorViewOrNull) {updateEditorCodeFromPython(cellHandle.editorViewOrNull, code);diff --git a/frontend/src/core/rtc/state.ts b/frontend/src/core/rtc/state.tsindex ad3a124be0..252bd19a5a 100644--- a/frontend/src/core/rtc/state.ts+++ b/frontend/src/core/rtc/state.ts@@ -1,5 +1,6 @@/* Copyright 2026 Marimo. All rights reserved. */import { atomWithStorage } from "jotai/utils";+import { SCRATCH_CELL_ID, type CellId } from "@/core/cells/ids";import { once } from "@/utils/once";import { jotaiJsonStorage } from "@/utils/storage/jotai";import { getFeatureFlag } from "../config/feature-flag";@@ -23,3 +24,11 @@ export const usernameAtom = atomWithStorage<string>(export const isRtcEnabled = once(() => {return getFeatureFlag("rtc_v2");});++/**+ * Whether this cell type can participate in real-time collaboration.+ * Scratchpad cells are local-only.+ */+export function canUseRtc(cellId: CellId): boolean {+ return cellId !== SCRATCH_CELL_ID;+}