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: synchronize editor callbacks and release widget resources (#11376)
Myles Scolnicka7d7cbe33fd1
diff --git a/frontend/src/components/chat/__tests__/message-queue.test.tsx b/frontend/src/components/chat/__tests__/message-queue.test.tsxindex 5dfacd7c3f..971c26d8c9 100644--- a/frontend/src/components/chat/__tests__/message-queue.test.tsx+++ b/frontend/src/components/chat/__tests__/message-queue.test.tsx@@ -77,6 +77,23 @@ describe("useMessageQueue", () => {expect(result.current.messages).toEqual([]);});+ it("preserves multiple enqueues and flushes before React renders", () => {+ const { result } = renderHook(() => useMessageQueue());+ const send = vi.fn();++ act(() => {+ result.current.enqueue([textPart("first")]);+ result.current.enqueue([textPart("second")]);+ result.current.flushNext(send);+ result.current.flushNext(send);+ });++ expect(send).toHaveBeenNthCalledWith(1, [textPart("first")]);+ expect(send).toHaveBeenNthCalledWith(2, [textPart("second")]);+ expect(result.current.messages).toEqual([]);+ expect(result.current.hasQueuedRef.current).toBe(false);+ });+it("flushNext on an empty queue is a no-op", () => {const { result } = renderHook(() => useMessageQueue());const send = vi.fn();diff --git a/frontend/src/components/chat/chat-panel.tsx b/frontend/src/components/chat/chat-panel.tsxindex efbd1ac3d6..45b7ae2d1d 100644--- a/frontend/src/components/chat/chat-panel.tsx+++ b/frontend/src/components/chat/chat-panel.tsx@@ -716,14 +716,10 @@ const ChatPanelBody = () => {);const isLoading = status === "submitted" || status === "streaming";- // Read via a ref so the queue-vs-send decision stays correct even when it is- // made after an `await` (e.g. resolving @-context), by which point the render- // closure's `isLoading` may be stale.- const isLoadingRef = useRef(isLoading);- isLoadingRef.current = isLoading;-+ // useEvent reads the latest loading state, even when called after an await+ // (e.g. resolving @-context) that outlives the original render's closure.const submitOrQueue = useEvent((parts: ChatMessagePart[]) => {- if (isLoadingRef.current || hasQueuedRef.current) {+ if (isLoading || hasQueuedRef.current) {enqueueUserMessage(parts);} else {sendUserMessage(parts);diff --git a/frontend/src/components/chat/chat-utils.ts b/frontend/src/components/chat/chat-utils.tsindex 663b480476..405c1ed696 100644--- a/frontend/src/components/chat/chat-utils.ts+++ b/frontend/src/components/chat/chat-utils.ts@@ -294,16 +294,12 @@ export function useMessageQueue() {// invoked from a callback (e.g. `onFinish`) in the same tick as `enqueue`.const messagesRef = useRef<QueuedUserMessage[]>([]);const hasQueuedRef = useRef(false);- messagesRef.current = messages;- hasQueuedRef.current = messages.length > 0;const enqueue = useEvent((parts: ChatMessagePart[]) => {- setMessages((prev) => {- const next = [...prev, { id: generateUUID(), parts }];- messagesRef.current = next;- hasQueuedRef.current = true;- return next;- });+ const next = [...messagesRef.current, { id: generateUUID(), parts }];+ messagesRef.current = next;+ hasQueuedRef.current = true;+ setMessages(next);});const flushNext = useEvent((send: (parts: ChatMessagePart[]) => void) => {diff --git a/frontend/src/components/data-table/__tests__/context-menu-interaction.test.tsx b/frontend/src/components/data-table/__tests__/context-menu-interaction.test.tsxnew file mode 100644index 0000000000..b00c1c782f--- /dev/null+++ b/frontend/src/components/data-table/__tests__/context-menu-interaction.test.tsx@@ -0,0 +1,130 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { type Cell, createTable, getCoreRowModel } from "@tanstack/react-table";+import { fireEvent, render, screen } from "@testing-library/react";+import { useRef } from "react";+import { expect, it, vi } from "vitest";+import { SetupMocks } from "@/__mocks__/common";+import { DataTableContextMenu } from "../context-menu";++SetupMocks.resizeObserver();++const rows = [{ value: "first" }, { value: "second" }];+const columns = [+ { accessorKey: "value", meta: { filterType: "text" as const } },+];++function createCells() {+ const table = createTable({+ data: rows,+ columns,+ locale: "en-US",+ getCoreRowModel: getCoreRowModel(),+ onColumnFiltersChange: () => undefined,+ state: {},+ onStateChange: () => undefined,+ renderFallbackValue: null,+ });+ return table.getRowModel().rows.map((row) => row.getAllCells()[0]);+}++function Harness({ cells }: { cells: Cell<(typeof rows)[number], unknown>[] }) {+ const contextMenuRef = useRef<Cell<(typeof rows)[number], unknown> | null>(+ null,+ );+ const tableRef = useRef<HTMLTableSectionElement>(null);+ const tableBody = (+ <tbody ref={tableRef}>+ <tr>+ <td>empty</td>+ </tr>+ {cells.map((cell) => {+ return (+ <tr key={cell.id}>+ <td+ data-cell-id={cell.id}+ onContextMenu={() => {+ contextMenuRef.current = cell;+ }}+ >+ {String(cell.getValue())}+ </td>+ </tr>+ );+ })}+ </tbody>+ );+ return (+ <table>+ <DataTableContextMenu+ contextMenuRef={contextMenuRef}+ tableRef={tableRef}+ tableBody={tableBody}+ copyAllCells={() => undefined}+ />+ </table>+ );+}++it("filters the latest right-clicked cell when the menu is already open", () => {+ const onFilter = vi.fn();+ const table = createTable({+ data: rows,+ columns,+ locale: "en-US",+ getCoreRowModel: getCoreRowModel(),+ onColumnFiltersChange: onFilter,+ state: {},+ onStateChange: () => undefined,+ renderFallbackValue: null,+ });+ render(+ <Harness+ cells={table.getRowModel().rows.map((row) => row.getAllCells()[0])}+ />,+ );++ const firstCell = screen.getByText("first");+ const secondCell = screen.getByText("second");+ fireEvent.contextMenu(firstCell);+ expect(firstCell).toHaveClass("bg-(--green-4)");+ expect(+ screen.getByRole("menuitem", { name: "Filter by this value" }),+ ).toBeInTheDocument();+ fireEvent.contextMenu(secondCell);+ expect(firstCell).not.toHaveClass("bg-(--green-4)");+ expect(secondCell).toHaveClass("bg-(--green-4)");+ fireEvent.click(+ screen.getByRole("menuitem", { name: "Filter by this value" }),+ );+ expect(firstCell).not.toHaveClass("bg-(--green-4)");+ expect(secondCell).not.toHaveClass("bg-(--green-4)");++ const update = onFilter.mock.calls.at(-1)?.[0];+ expect(update([])).toEqual([+ {+ id: "value",+ value: { type: "text", operator: "equals", text: "second" },+ },+ ]);+});++it("does not reuse a previous cell after the menu closes", () => {+ render(<Harness cells={createCells()} />);++ const firstCell = screen.getByText("first");+ fireEvent.contextMenu(firstCell);+ expect(firstCell).toHaveClass("bg-(--green-4)");+ fireEvent.keyDown(document.activeElement ?? document.body, {+ key: "Escape",+ });+ expect(firstCell).not.toHaveClass("bg-(--green-4)");+ expect(screen.queryByRole("menu")).not.toBeInTheDocument();++ // Right-clicking outside any data cell must not resurrect the old one+ fireEvent.contextMenu(screen.getByText("empty"));+ expect(firstCell).not.toHaveClass("bg-(--green-4)");+ expect(+ screen.queryByRole("menuitem", { name: "Filter by this value" }),+ ).not.toBeInTheDocument();+});diff --git a/frontend/src/components/data-table/context-menu.tsx b/frontend/src/components/data-table/context-menu.tsxindex 70ab4c709d..5ac2ac02bd 100644--- a/frontend/src/components/data-table/context-menu.tsx+++ b/frontend/src/components/data-table/context-menu.tsx@@ -12,7 +12,7 @@ import { Logger } from "@/utils/Logger";import type { Cell } from "@tanstack/react-table";import { useAtomValue } from "jotai";import { CopyIcon, FilterIcon, SquareStack } from "lucide-react";-import type { RefObject } from "react";+import { type RefObject, useRef, useState } from "react";import useEvent from "react-use-event-hook";import {ContextMenu,@@ -123,8 +123,21 @@ export const DataTableContextMenu = <TData,>({tableRef: RefObject<HTMLTableSectionElement | null>;copyAllCells: () => void;}) => {+ const [activeCell, setActiveCell] = useState<Cell<TData, unknown> | null>(+ null,+ );+ const highlightedCell = useRef<Element | null>(null);const handleContextMenuChange = useEvent((open: boolean) => {+ highlightedCell.current?.classList.remove("bg-(--green-4)");+ highlightedCell.current = null;+ if (!open) {+ // Forget the cell so a later right-click outside any cell can't reuse it+ contextMenuRef.current = null;+ return;+ }+const cell = contextMenuRef.current;+ setActiveCell(cell);if (!cell) {return;}@@ -138,42 +151,45 @@ export const DataTableContextMenu = <TData,>({return;}- if (open) {- cellElement.classList.add("bg-(--green-4)");- } else {- cellElement.classList.remove("bg-(--green-4)");- }+ cellElement.classList.add("bg-(--green-4)");+ highlightedCell.current = cellElement;});return (- <ContextMenu onOpenChange={handleContextMenuChange}>- <ContextMenuTrigger asChild={true}>{tableBody}</ContextMenuTrigger>+ // Open via the trigger so a right-click while already open retargets the+ // menu; Radix only reports open changes, so use it for closing.+ <ContextMenu+ onOpenChange={(open) => {+ if (!open) {+ handleContextMenuChange(false);+ }+ }}+ >+ <ContextMenuTrigger+ asChild={true}+ onContextMenu={() => handleContextMenuChange(true)}+ >+ {tableBody}+ </ContextMenuTrigger><ContextMenuPortal>- <CellContextMenu- cellRef={contextMenuRef}- copySelectedCells={copyAllCells}- />+ {activeCell && (+ <CellContextMenu cell={activeCell} copySelectedCells={copyAllCells} />+ )}</ContextMenuPortal></ContextMenu>);};export const CellContextMenu = <TData,>({- cellRef,+ cell,copySelectedCells,}: {- cellRef: RefObject<Cell<TData, unknown> | null>;+ cell: Cell<TData, unknown>;copySelectedCells: () => void;}) => {const selectedCells = useAtomValue(selectedCellsAtom);const multipleSelectedCells = selectedCells.size > 1;- const cell = cellRef.current;- if (!cell) {- Logger.error("No cell found in context menu");- return;- }-const table = cell.getContext().table;const displayedValue = cell.getValue();const rawValue =diff --git a/frontend/src/components/editor/cell/CreateCellButton.tsx b/frontend/src/components/editor/cell/CreateCellButton.tsxindex a81145eaec..a351dca0c4 100644--- a/frontend/src/components/editor/cell/CreateCellButton.tsx+++ b/frontend/src/components/editor/cell/CreateCellButton.tsx@@ -1,6 +1,6 @@/* Copyright 2026 Marimo. All rights reserved. */import { DatabaseIcon, DiamondPlusIcon, PlusIcon } from "lucide-react";-import { useState } from "react";+import { useRef, useState } from "react";import { Button } from "@/components/editor/inputs/Inputs";import { MinimalHotkeys } from "@/components/shortcuts/renderShortcut";import {@@ -36,7 +36,8 @@ export const CreateCellButton = ({const { createNewCell, addSetupCellIfDoesntExist } = useCellActions();const shortcut = `${oneClickShortcut}-Click`;const [open, setOpen] = useState(false);- const [justOpened, setJustOpened] = useState(false);+ // Time the dropdown last opened, to ignore the click that opened it+ const openedAt = useRef(0);const baseTooltipContent =getConnectionTooltip(connectionState) || tooltipContent;@@ -83,9 +84,7 @@ export const CreateCellButton = ({const openDropdown = () => {setOpen(true);- setJustOpened(true);- // Allow interactions after a brief delay to prevent the dropdown items immediately being clicked- setTimeout(() => setJustOpened(false), 200);+ openedAt.current = Date.now();};// We use onPointerDownCapture (not onPointerDown) to intercept events in@@ -121,15 +120,14 @@ export const CreateCellButton = ({const handleOpenChange = (isOpen: boolean) => {setOpen(isOpen);if (isOpen) {- setJustOpened(true);- // Allow interactions after a brief delay- setTimeout(() => setJustOpened(false), 200);+ openedAt.current = Date.now();}};const handleFirstItemClick = (e: React.MouseEvent) => {- // Hack to prevent the first item from being clicked when the dropdown is opened- if (justOpened) {+ // Hack to prevent the first item from being clicked when the dropdown is+ // opened: allow interactions only after a brief delay+ if (Date.now() - openedAt.current < 200) {e.preventDefault();e.stopPropagation();return;diff --git a/frontend/src/components/editor/cell/code/__tests__/language-toggle.test.tsx b/frontend/src/components/editor/cell/code/__tests__/language-toggle.test.tsxnew file mode 100644index 0000000000..d6dcc94e7c--- /dev/null+++ b/frontend/src/components/editor/cell/code/__tests__/language-toggle.test.tsx@@ -0,0 +1,54 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { EditorState } from "@codemirror/state";+import { EditorView } from "@codemirror/view";+import { fireEvent, render, screen } from "@testing-library/react";+import { createRef } from "react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { TooltipProvider } from "@/components/ui/tooltip";+import { switchLanguage } from "@/core/codemirror/language/extension";+import { LanguageToggle } from "../language-toggle";++vi.mock("@/core/codemirror/language/extension", () => ({+ switchLanguage: vi.fn(),+}));++describe("LanguageToggle", () => {+ afterEach(() => {+ vi.mocked(switchLanguage).mockClear();+ });++ it("uses the editor mounted after the button rendered", () => {+ const editorViewRef = createRef<EditorView>();+ const onAfterToggle = vi.fn();+ render(+ <TooltipProvider>+ <LanguageToggle+ editorViewRef={editorViewRef}+ currentLanguageAdapter="python"+ canSwitchToLanguage={true}+ toType="markdown"+ displayName="Markdown"+ icon="Markdown"+ onAfterToggle={onAfterToggle}+ />+ </TooltipProvider>,+ );++ fireEvent.click(screen.getByRole("button", { name: "Markdown" }));+ expect(switchLanguage).not.toHaveBeenCalled();+ expect(onAfterToggle).not.toHaveBeenCalled();++ const view = new EditorView({ state: EditorState.create() });+ editorViewRef.current = view;+ try {+ fireEvent.click(screen.getByRole("button", { name: "Markdown" }));+ expect(switchLanguage).toHaveBeenCalledWith(view, {+ language: "markdown",+ });+ expect(onAfterToggle).toHaveBeenCalledOnce();+ } finally {+ view.destroy();+ }+ });+});diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsxindex b7c7676e76..41a81579bb 100644--- a/frontend/src/components/editor/cell/code/cell-editor.tsx+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx@@ -572,7 +572,7 @@ const CellEditorInternal = ({<div className="absolute top-1 right-5"><LanguageTogglescode={code}- editorView={editorViewRef.current}+ editorViewRef={editorViewRef}currentLanguageAdapter={languageAdapter}onAfterToggle={afterToggleMarkdown}/>diff --git a/frontend/src/components/editor/cell/code/language-toggle.tsx b/frontend/src/components/editor/cell/code/language-toggle.tsxindex dab65cd665..cc173deae8 100644--- a/frontend/src/components/editor/cell/code/language-toggle.tsx+++ b/frontend/src/components/editor/cell/code/language-toggle.tsx@@ -13,7 +13,7 @@ import { Functions } from "@/utils/functions";import { MarkdownIcon, PythonIcon } from "./icons";interface LanguageTogglesProps {- editorView: EditorView | null;+ editorViewRef: React.RefObject<EditorView | null>;code: string;currentLanguageAdapter: LanguageAdapter["type"] | undefined;onAfterToggle: () => void;@@ -25,7 +25,7 @@ interface LanguageTogglesProps {}export const LanguageToggles: React.FC<LanguageTogglesProps> = ({- editorView,+ editorViewRef,code,currentLanguageAdapter,onAfterToggle,@@ -43,7 +43,7 @@ export const LanguageToggles: React.FC<LanguageTogglesProps> = ({return (<div className={className}><LanguageToggle- editorView={editorView}+ editorViewRef={editorViewRef}currentLanguageAdapter={currentLanguageAdapter}canSwitchToLanguage={canUseSQL && currentLanguageAdapter === "python"}icon={@@ -58,7 +58,7 @@ export const LanguageToggles: React.FC<LanguageTogglesProps> = ({onAfterToggle={onAfterToggle}/><LanguageToggle- editorView={editorView}+ editorViewRef={editorViewRef}currentLanguageAdapter={currentLanguageAdapter}canSwitchToLanguage={canUseMarkdown && currentLanguageAdapter === "python"@@ -75,7 +75,7 @@ export const LanguageToggles: React.FC<LanguageTogglesProps> = ({onAfterToggle={onAfterToggle}/><LanguageToggle- editorView={editorView}+ editorViewRef={editorViewRef}currentLanguageAdapter={currentLanguageAdapter}canSwitchToLanguage={true}icon={@@ -95,7 +95,7 @@ export const LanguageToggles: React.FC<LanguageTogglesProps> = ({interface Props {className?: string;- editorView: EditorView | null;+ editorViewRef: React.RefObject<EditorView | null>;canSwitchToLanguage: boolean;currentLanguageAdapter: LanguageAdapter["type"] | undefined;toType: LanguageAdapter["type"];@@ -105,7 +105,7 @@ interface Props {}export const LanguageToggle: React.FC<Props> = ({- editorView,+ editorViewRef,currentLanguageAdapter,canSwitchToLanguage,icon,@@ -114,6 +114,7 @@ export const LanguageToggle: React.FC<Props> = ({onAfterToggle,}) => {const handleClick = () => {+ const editorView = editorViewRef.current;if (!editorView) {return;}diff --git a/frontend/src/components/editor/file-tree/file-viewer.tsx b/frontend/src/components/editor/file-tree/file-viewer.tsxindex eeb2eb1055..36f12a9afd 100644--- a/frontend/src/components/editor/file-tree/file-viewer.tsx+++ b/frontend/src/components/editor/file-tree/file-viewer.tsx@@ -9,7 +9,7 @@ import {SaveIcon,} from "lucide-react";import type React from "react";-import { useEffect, useRef, useState } from "react";+import { useEffect, useLayoutEffect, useRef, useState } from "react";import { renderShortcut } from "@/components/shortcuts/renderShortcut";import { Alert, AlertDescription } from "@/components/ui/alert";import { Button } from "@/components/ui/button";@@ -82,7 +82,9 @@ export const FileViewer: React.FC<Props> = ({ file, onOpenNotebook }) => {// carry no draft to preserve.// We use a ref for internalValue so we don't call this effect on each keystrokeconst internalValueRef = useRef<string>(internalValue);- internalValueRef.current = internalValue;+ useLayoutEffect(() => {+ internalValueRef.current = internalValue;+ }, [internalValue]);useEffect(() => {return () => {if (diff --git a/frontend/src/components/editor/output/console/ConsoleOutput.tsx b/frontend/src/components/editor/output/console/ConsoleOutput.tsxindex 198a0b837f..2ded6720f9 100644--- a/frontend/src/components/editor/output/console/ConsoleOutput.tsx+++ b/frontend/src/components/editor/output/console/ConsoleOutput.tsx@@ -6,7 +6,7 @@ import {ChevronsUpDownIcon,WrapTextIcon,} from "lucide-react";-import React, { useEffect, useLayoutEffect, useRef, useState } from "react";+import React, { useEffect, useLayoutEffect, useState } from "react";import { ToggleButton } from "react-aria-components";import { DebuggerControls } from "@/components/debugger/debugger-code";import { CopyClipboardIcon } from "@/components/icons/copy-icon";@@ -49,31 +49,21 @@ export const CONSOLE_CLEAR_DEBOUNCE_MS = 200;*/function useDebouncedConsoleOutputs<T>(outputs: T[]): T[] {const [debouncedOutputs, setDebouncedOutputs] = useState(outputs);- const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);- // Non-empty outputs: apply immediately and cancel any pending clear+ // Non-empty outputs: apply immediately. Effect cleanup cancels pending clears.if (outputs.length > 0 && debouncedOutputs !== outputs) {- if (timerRef.current !== null) {- clearTimeout(timerRef.current);- timerRef.current = null;- }setDebouncedOutputs(outputs);}// Empty outputs: delay the clear so new outputs can arrive firstuseEffect(() => {- if (outputs.length === 0 && timerRef.current === null) {- timerRef.current = setTimeout(() => {- timerRef.current = null;- setDebouncedOutputs([]);- }, CONSOLE_CLEAR_DEBOUNCE_MS);+ if (outputs.length > 0) {+ return;}- return () => {- if (timerRef.current !== null) {- clearTimeout(timerRef.current);- timerRef.current = null;- }- };+ const timer = setTimeout(() => {+ setDebouncedOutputs([]);+ }, CONSOLE_CLEAR_DEBOUNCE_MS);+ return () => clearTimeout(timer);}, [outputs]);return debouncedOutputs;diff --git a/frontend/src/components/slides/slide-cell-view.tsx b/frontend/src/components/slides/slide-cell-view.tsxindex 966546d3ba..e9ed2dc801 100644--- a/frontend/src/components/slides/slide-cell-view.tsx+++ b/frontend/src/components/slides/slide-cell-view.tsx@@ -117,7 +117,7 @@ export const SlideCellView = ({ cell }: { cell: RuntimeCell }) => {/><LanguageTogglescode={cell.code}- editorView={editorViewRef.current}+ editorViewRef={editorViewRef}currentLanguageAdapter={languageAdapter}onAfterToggle={afterToggleLanguage}className="flex items-center gap-1"diff --git a/frontend/src/core/static/files.ts b/frontend/src/core/static/files.tsindex 39dc14275f..e55ec570f0 100644--- a/frontend/src/core/static/files.ts+++ b/frontend/src/core/static/files.ts@@ -125,6 +125,8 @@ function withoutLeadingDot(path: string): string {/*** Resolve a URL to a blob URL if it's a virtual file, for use with dynamic import().* Unlike fetch, import() can't be patched, so we need to convert data URLs to blob URLs.+ * The caller owns a returned URL that differs from the input and must revoke it+ * once no module consumers or their cleanup callbacks need it.** @returns The original URL if not a virtual file, or a blob URL if it is*/diff --git a/frontend/src/hooks/useInputHistory.ts b/frontend/src/hooks/useInputHistory.tsindex 1bffb27d39..3373608b63 100644--- a/frontend/src/hooks/useInputHistory.ts+++ b/frontend/src/hooks/useInputHistory.ts@@ -37,12 +37,9 @@ export function useInputHistory({const historyIndexRef = React.useRef<number>(-1);// Store the current input when navigating historyconst pendingInputRef = React.useRef<string>("");- // Keep a ref to history for use in callbacks without causing re-renders- const historyRef = React.useRef(history);- historyRef.current = history;const navigateUp = React.useCallback(() => {- const currentHistory = historyRef.current;+ const currentHistory = history;if (currentHistory.length === 0) {return;}@@ -59,10 +56,10 @@ export function useInputHistory({historyIndexRef.current = newIndex;setValue(currentHistory[currentHistory.length - 1 - newIndex]);}- }, [value, setValue]);+ }, [history, value, setValue]);const navigateDown = React.useCallback(() => {- const currentHistory = historyRef.current;+ const currentHistory = history;if (currentHistory.length === 0) {return;}@@ -79,7 +76,7 @@ export function useInputHistory({historyIndexRef.current = -1;setValue(pendingInputRef.current);}- }, [setValue]);+ }, [history, setValue]);const addToHistory = React.useCallback((command: string) => {setHistory((prev) => {diff --git a/frontend/src/hooks/useResizeObserver.ts b/frontend/src/hooks/useResizeObserver.tsindex c0367f7c3b..d437cc2322 100644--- a/frontend/src/hooks/useResizeObserver.ts+++ b/frontend/src/hooks/useResizeObserver.ts@@ -6,6 +6,7 @@import type { RefObject } from "react";import { useEffect, useRef } from "react";+import useEvent from "react-use-event-hook";interface Size {width: number | undefined;@@ -30,9 +31,7 @@ export function useResizeObserver<T extends HTMLElement = HTMLElement>(const { ref, box = "content-box", skip } = options;// oxlint-disable-next-line react/hook-use-stateconst previousSize = useRef<Size>({ ...initialSize });- const onResize = useRef<((size: Size) => void) | undefined>(undefined);- // oxlint-disable-next-line react-hooks/react-compiler- onResize.current = options.onResize;+ const onResize = useEvent((size: Size) => options.onResize?.(size));useEffect(() => {if (!ref.current || skip) {@@ -63,9 +62,7 @@ export function useResizeObserver<T extends HTMLElement = HTMLElement>(previousSize.current.width = newWidth;previousSize.current.height = newHeight;- if (onResize.current) {- onResize.current(newSize);- }+ onResize(newSize);}});@@ -74,7 +71,7 @@ export function useResizeObserver<T extends HTMLElement = HTMLElement>(return () => {observer.disconnect();};- }, [box, ref, skip]);+ }, [box, ref, skip, onResize]);}type BoxSizesKey = keyof Pick<diff --git a/frontend/src/plugins/impl/anywidget/__tests__/registry.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/registry.test.tsindex f9047d7ea2..e405a345b0 100644--- a/frontend/src/plugins/impl/anywidget/__tests__/registry.test.ts+++ b/frontend/src/plugins/impl/anywidget/__tests__/registry.test.ts@@ -238,6 +238,7 @@ describe("WidgetRegistry.getWidget", () => {jsUrl: SPEC.url,jsHash: SPEC.hash,kernelAuthored: true,+ lifetime: expect.any(AbortSignal),});expect(widgetDef.initialize).toHaveBeenCalledTimes(1);expect(widget.exports).toBe(exports);@@ -263,6 +264,7 @@ describe("WidgetRegistry.getWidget", () => {jsUrl: SPEC.url,jsHash: SPEC.hash,kernelAuthored: true,+ lifetime: expect.any(AbortSignal),});});diff --git a/frontend/src/plugins/impl/anywidget/__tests__/widget-binding.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/widget-binding.test.tsindex 186e05256e..c2b3226b0f 100644--- a/frontend/src/plugins/impl/anywidget/__tests__/widget-binding.test.ts+++ b/frontend/src/plugins/impl/anywidget/__tests__/widget-binding.test.ts@@ -7,9 +7,12 @@ import { userConfigAtom } from "@/core/config/config";import { parseUserConfig } from "@/core/config/config-schema";import { initialModeAtom } from "@/core/mode";import { store } from "@/core/state/jotai";+import type { DataURLString } from "@/utils/json/base64";import { Model } from "../model";import type { Host } from "../host";-import type { ModelState } from "../types";+import type { ModelState, WidgetModelId } from "../types";+import { WidgetRuntime } from "../runtime";+import { Deferred } from "@/utils/Deferred";import { visibleForTesting } from "../widget-binding";const { WidgetDefRegistry, WidgetBinding } = visibleForTesting;@@ -30,13 +33,14 @@ const createTestHost = (): Host => ({function createBinding<T extends ModelState>(widgetDef: AnyWidget<T>,model: Model<T>,- options: { controller?: AbortController } = {},+ options: { controller?: AbortController; onDestroy?: () => void } = {},) {return WidgetBinding.create({widgetDef,model,createHost: createTestHost,controller: options.controller,+ onDestroy: options.onDestroy,});}@@ -123,6 +127,25 @@ describe("WidgetDefRegistry", () => {promise2.catch(() => undefined);});+ it("does not evict a replacement when an invalidated import fails", async () => {+ const oldImport = getModule(+ registry,+ "http://localhost/old.js",+ "replaced",+ );+ registry.invalidate("replaced");+ const newImport = registry.getModule({+ jsUrl: "data:text/javascript,export default {}",+ jsHash: "replaced",+ kernelAuthored: true,+ });+ await expect(oldImport).rejects.toThrow(/untrusted/i);+ await newImport;+ expect(getModule(registry, "http://localhost/new.js", "replaced")).toBe(+ newImport,+ );+ });+describe("URL validation", () => {it.each([// Attack vector: raw <marimo-anywidget data-js-url=...> in markdown@@ -148,9 +171,225 @@ describe("WidgetDefRegistry", () => {).rejects.not.toThrow(/untrusted/i);});});++ describe("static module URLs", () => {+ afterEach(() => {+ delete window.__MARIMO_STATIC__;+ vi.restoreAllMocks();+ });++ it("releases the generated URL when a static module fails to import", async () => {+ window.__MARIMO_STATIC__ = {+ files: {+ "/@file/widget.js":+ "data:text/javascript;base64,ZXhwb3J0IHt9" as DataURLString,+ },+ };+ const create = vi+ .spyOn(URL, "createObjectURL")+ .mockReturnValue("blob:widget-module");+ const revoke = vi+ .spyOn(URL, "revokeObjectURL")+ .mockImplementation(() => undefined);++ await expect(+ getModule(registry, "./@file/widget.js", "static-module"),+ ).rejects.toThrow(/blob:/);++ expect(create).toHaveBeenCalledOnce();+ expect(revoke).toHaveBeenCalledExactlyOnceWith("blob:widget-module");+ });++ it("does not revoke active modules when their cache entry is invalidated", async () => {+ window.__MARIMO_STATIC__ = {+ files: {+ "/@file/widget.js":+ "data:text/javascript;base64,ZXhwb3J0IHt9" as DataURLString,+ },+ };+ const oldUrl = "data:text/javascript,export const version = 1";+ const newUrl = "data:text/javascript,export const version = 2";+ vi.spyOn(URL, "createObjectURL")+ .mockReturnValueOnce(oldUrl)+ .mockReturnValueOnce(newUrl);+ const revoke = vi+ .spyOn(URL, "revokeObjectURL")+ .mockImplementation(() => undefined);+ const oldLifetime = new AbortController();+ const newLifetime = new AbortController();+ const options = { jsUrl: "./@file/widget.js", jsHash: "invalidated" };+ const oldImport = registry.getModule({+ ...options,+ lifetime: oldLifetime.signal,+ });+ registry.invalidate(options.jsHash);+ const newImport = registry.getModule({+ ...options,+ lifetime: newLifetime.signal,+ });+ await Promise.all([oldImport, newImport]);+ expect(revoke).not.toHaveBeenCalled();+ oldLifetime.abort();+ await vi.waitFor(() =>+ expect(revoke).toHaveBeenCalledExactlyOnceWith(oldUrl),+ );+ const siblingLifetime = new AbortController();+ expect(+ registry.getModule({ ...options, lifetime: siblingLifetime.signal }),+ ).toBe(newImport);+ newLifetime.abort();+ siblingLifetime.abort();+ await vi.waitFor(() => expect(revoke).toHaveBeenLastCalledWith(newUrl));+ });++ it("waits for a canceled import to settle before revoking its URL", async () => {+ window.__MARIMO_STATIC__ = {+ files: {+ "/@file/widget.js":+ "data:text/javascript;base64,ZXhwb3J0IHt9" as DataURLString,+ },+ };+ const moduleUrl = "data:text/javascript,export const pending = true";+ vi.spyOn(URL, "createObjectURL").mockReturnValue(moduleUrl);+ const revoke = vi+ .spyOn(URL, "revokeObjectURL")+ .mockImplementation(() => undefined);+ const lifetime = new AbortController();+ const pending = registry.getModule({+ jsUrl: "./@file/widget.js",+ jsHash: "pending",+ lifetime: lifetime.signal,+ });+ lifetime.abort();+ expect(revoke).not.toHaveBeenCalled();+ await pending;+ expect(revoke).toHaveBeenCalledExactlyOnceWith(moduleUrl);+ });++ it("does not revoke an unchanged URL for a missing static file", async () => {+ window.__MARIMO_STATIC__ = { files: {} };+ const revoke = vi+ .spyOn(URL, "revokeObjectURL")+ .mockImplementation(() => undefined);++ await expect(+ getModule(registry, "./@file/missing.js", "missing-module"),+ ).rejects.toThrow(/http:/);++ expect(revoke).not.toHaveBeenCalled();+ });++ it("keeps a shared module URL until the last widget generation is destroyed", async () => {+ window.__MARIMO_STATIC__ = {+ files: {+ "/@file/widget.js":+ "data:text/javascript;base64,ZXhwb3J0IHt9" as DataURLString,+ },+ };+ // Node cannot import blob URLs; a data URL exercises successful loading.+ const moduleUrl = `data:text/javascript,${encodeURIComponent(+ "export default { initialize: () => ({ moduleUrl: import.meta.url }) }",+ )}`;+ vi.spyOn(URL, "createObjectURL").mockReturnValue(moduleUrl);+ const revoke = vi+ .spyOn(URL, "revokeObjectURL")+ .mockImplementation(() => undefined);++ const createRuntime = (id: string) => {+ const runtime = new WidgetRuntime(id as WidgetModelId, {+ timeout: 50,+ isEditMode: () => true,+ createHost: createTestHost,+ onModelTimeout: vi.fn(),+ });+ runtime.setModel(new Model({}, createMockComm()));+ runtime.setSpec({ url: "./@file/widget.js", hash: "static-success" });+ return runtime;+ };+ const first = createRuntime("first");+ const second = createRuntime("second");+ const widgets = await Promise.all([+ first.getWidget(),+ second.getWidget(),+ ]);+ expect(widgets.map((widget) => widget.exports)).toEqual([+ { moduleUrl },+ { moduleUrl },+ ]);+ expect(URL.createObjectURL).toHaveBeenCalledOnce();+ expect(revoke).not.toHaveBeenCalled();++ first.dispose();+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(revoke).not.toHaveBeenCalled();++ second.dispose();+ await vi.waitFor(() => {+ expect(revoke).toHaveBeenCalledExactlyOnceWith(moduleUrl);+ });++ // A later generation reuses the evaluated module rather than+ // re-running its top-level side effects, and does not revoke again.+ const third = createRuntime("third");+ const widget = await third.getWidget();+ expect(widget.exports).toEqual({ moduleUrl });+ expect(URL.createObjectURL).toHaveBeenCalledOnce();+ third.dispose();+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(revoke).toHaveBeenCalledOnce();+ });+ });});describe("WidgetBinding", () => {+ it("releases module resources after asynchronous generation cleanup", async () => {+ const cleanup = new Deferred<void>();+ const onDestroy = vi.fn();+ const binding = await createBinding(+ { initialize: () => () => cleanup.promise },+ new Model({}, createMockComm()),+ { onDestroy },+ );+ const destroying = binding.destroy();+ expect(onDestroy).not.toHaveBeenCalled();+ cleanup.resolve();+ await destroying;+ await binding.destroy();+ expect(onDestroy).toHaveBeenCalledOnce();+ });++ it("retains module resources until canceled initialization and late cleanup settle", async () => {+ const initialize = new Deferred<() => Promise<void>>();+ const cleanup = new Deferred<void>();+ const controller = new AbortController();+ const onDestroy = vi.fn();+ const pending = createBinding(+ { initialize: () => initialize.promise },+ new Model({}, createMockComm()),+ { controller, onDestroy },+ );+ controller.abort();+ await expect(pending).rejects.toThrow(/binding destroyed/);+ expect(onDestroy).not.toHaveBeenCalled();+ initialize.resolve(() => cleanup.promise);+ await Promise.resolve();+ expect(onDestroy).not.toHaveBeenCalled();+ cleanup.resolve();+ await vi.waitFor(() => expect(onDestroy).toHaveBeenCalledOnce());+ });++ it("releases module resources when initialization fails", async () => {+ const onDestroy = vi.fn();+ await expect(+ createBinding(+ { initialize: () => Promise.reject(new Error("initialize failed")) },+ new Model({}, createMockComm()),+ { onDestroy },+ ),+ ).rejects.toThrow("initialize failed");+ await vi.waitFor(() => expect(onDestroy).toHaveBeenCalledOnce());+ });+it("should run initialize exactly once and expose exports", async () => {const model = new Model<ModelState>({ count: 0 }, createMockComm());const exports = { setValue: vi.fn() };diff --git a/frontend/src/plugins/impl/anywidget/runtime.ts b/frontend/src/plugins/impl/anywidget/runtime.tsindex 636201c550..cc617e9537 100644--- a/frontend/src/plugins/impl/anywidget/runtime.ts+++ b/frontend/src/plugins/impl/anywidget/runtime.ts@@ -206,21 +206,33 @@ export class WidgetRuntime {controller: AbortController;}): Promise<WidgetBinding<ModelState>> {const { spec, model, controller } = options;- const mod = await WIDGET_DEF_REGISTRY.getModule({- jsUrl: spec.url,- jsHash: spec.hash,- kernelAuthored: true,- });- const widget = resolveAnyWidget(mod, spec.url);- if (!widget) {- WIDGET_DEF_REGISTRY.invalidate(spec.hash);- throw getInvalidAnyWidgetModuleError(mod, spec.url);+ const moduleLifetime = new AbortController();+ let widget: NonNullable<ReturnType<typeof resolveAnyWidget>>;+ try {+ const mod = await WIDGET_DEF_REGISTRY.getModule({+ jsUrl: spec.url,+ jsHash: spec.hash,+ kernelAuthored: true,+ lifetime: moduleLifetime.signal,+ });+ const resolved = resolveAnyWidget(mod, spec.url);+ if (!resolved) {+ WIDGET_DEF_REGISTRY.invalidate(spec.hash);+ throw getInvalidAnyWidgetModuleError(mod, spec.url);+ }+ widget = resolved;+ } catch (error) {+ moduleLifetime.abort();+ throw error;}+ // From here WidgetBinding owns release, including late cleanup when the+ // generation is destroyed during initialize.return WidgetBinding.create({widgetDef: widget,model,createHost: this.#createHost,controller,+ onDestroy: () => moduleLifetime.abort(),});}diff --git a/frontend/src/plugins/impl/anywidget/widget-binding.ts b/frontend/src/plugins/impl/anywidget/widget-binding.tsindex da9e35b8a7..4dfcc8da63 100644--- a/frontend/src/plugins/impl/anywidget/widget-binding.ts+++ b/frontend/src/plugins/impl/anywidget/widget-binding.ts@@ -46,38 +46,80 @@ function abortSignalAny(signals: AbortSignal[]): AbortSignal {return controller.signal;}+interface ModuleEntry {+ promise: Promise<unknown>;+ references: number;+ dispose: () => void;+}+/*** Deduplicates ESM imports by jsHash.* A single import is shared across all widget instances using the same module.*/class WidgetDefRegistry {- #cache = new Map<string, Promise<unknown>>();+ #cache = new Map<string, ModuleEntry>();/*** Get (or start) the ESM import for a widget module, cached by* jsHash so multiple instances share one import. Pass* `kernelAuthored: true` only for URLs from an `EsmSpec`; it widens- * the import gate to remote and data URLs.+ * the import gate to remote and data URLs. A lifetime retains the module's+ * temporary URL until that signal aborts; omit it to retain the URL for+ * the notebook's lifetime. The evaluated module itself stays cached.*/public getModule(options: {jsUrl: string;jsHash: string;kernelAuthored?: boolean;+ lifetime?: AbortSignal;}): Promise<unknown> {- const { jsUrl, jsHash, kernelAuthored = false } = options;- const cached = this.#cache.get(jsHash);- if (cached) {- return cached;+ const { jsUrl, jsHash, kernelAuthored = false, lifetime } = options;+ let entry = this.#cache.get(jsHash);+ if (!entry) {+ const imported = this.#doImport(jsUrl, { kernelAuthored });+ const created: ModuleEntry = {+ references: 0,+ dispose: () => undefined,+ promise: imported.then(+ ({ module, dispose }) => {+ created.dispose = dispose;+ return module;+ },+ (error) => {+ // An invalidated import must not evict its replacement.+ if (this.#cache.get(jsHash) === created) {+ this.#cache.delete(jsHash);+ }+ throw error;+ },+ ),+ };+ this.#cache.set(jsHash, created);+ entry = created;}-- const promise = this.#doImport(jsUrl, { kernelAuthored }).catch((error) => {- // On failure, remove from cache so a retry with a new URL can work- this.#cache.delete(jsHash);- throw error;- });-- this.#cache.set(jsHash, promise);- return promise;+ const retained = entry;+ retained.references += 1;+ const release = () => {+ retained.references -= 1;+ if (retained.references === 0) {+ // Keep the evaluated module cached: re-importing would re-run its+ // top-level side effects (e.g. `customElements.define`). Only the+ // temporary URL is released.+ void retained.promise.then(+ () => {+ retained.dispose();+ retained.dispose = () => undefined;+ },+ () => undefined,+ );+ }+ };+ if (lifetime?.aborted) {+ release();+ } else {+ lifetime?.addEventListener("abort", release, { once: true });+ }+ return retained.promise;}public invalidate(jsHash: string): void {@@ -87,7 +129,7 @@ class WidgetDefRegistry {async #doImport(jsUrl: string,opts: { kernelAuthored?: boolean } = {},- ): Promise<unknown> {+ ): Promise<{ module: unknown; dispose: () => void }> {// By default, only trust marimo virtual file paths: arbitrary URLs// would let markdown-injected elements import attacker-controlled// JavaScript. Kernel-authored URLs (from an `EsmSpec`) are exempt —@@ -103,11 +145,23 @@ class WidgetDefRegistry {)}`,);}- let url = asRemoteURL(jsUrl).toString();- if (isStaticNotebook()) {- url = resolveVirtualFileURL(url);+ const remoteUrl = asRemoteURL(jsUrl).toString();+ const url = isStaticNotebook()+ ? resolveVirtualFileURL(remoteUrl)+ : remoteUrl;+ const dispose = () => {+ // Only the static-file resolver's newly created URL belongs to us.+ if (url !== remoteUrl) {+ URL.revokeObjectURL(url);+ }+ };+ try {+ const module = await import(/* @vite-ignore */ url);+ return { module, dispose };+ } catch (error) {+ dispose();+ throw error;}- return import(/* @vite-ignore */ url);}}@@ -132,6 +186,7 @@ interface CreateWidgetBindingOptions<T extends ModelState> {model: Model<T>;createHost: HostFactory;controller?: AbortController;+ onDestroy?: () => void;}async function safelyRunCleanup(cleanup: Cleanup, reason: string) {@@ -159,6 +214,7 @@ export class WidgetBinding<T extends ModelState = ModelState> {#createHost: HostFactory;#cleanupTasks = new Set<Promise<void>>();#viewTasks = new Set<Promise<void>>();+ #onDestroy?: () => void;private constructor(options: {widget: ResolvedWidget<T>;@@ -166,12 +222,14 @@ export class WidgetBinding<T extends ModelState = ModelState> {exports: unknown;controller: AbortController;createHost: HostFactory;+ onDestroy?: () => void;}) {this.#widget = options.widget;this.#model = options.model;this.#exports = options.exports;this.#controller = options.controller;this.#createHost = options.createHost;+ this.#onDestroy = options.onDestroy;}/**@@ -185,76 +243,94 @@ export class WidgetBinding<T extends ModelState = ModelState> {model,createHost,controller = new AbortController(),+ onDestroy,}: CreateWidgetBindingOptions<T>): Promise<WidgetBinding<T>> {const signal = controller.signal;- const widget: ResolvedWidget<T> =- typeof widgetDef === "function" ? await widgetDef() : widgetDef;+ let lateCleanup: Promise<void> | undefined;+ try {+ const widget: ResolvedWidget<T> =+ typeof widgetDef === "function" ? await widgetDef() : widgetDef;- const initPromise = Promise.resolve(- widget.initialize?.({- model: modelProxy(model, signal),- experimental,- signal,- }),- );- // If destroyed mid-initialize, still run a late-arriving legacy- // cleanup callback: the widget acquired resources.- initPromise- .then(async (settled) => {- if (signal.aborted && isCleanup(settled)) {- await safelyRunCleanup(settled, "late initialize");- }- })- .catch(() => undefined);+ if (signal.aborted) {+ throw new Error("[anywidget] binding destroyed");+ }+ const initPromise = Promise.resolve(+ widget.initialize?.({+ model: modelProxy(model, signal),+ experimental,+ signal,+ }),+ );+ // If destroyed mid-initialize, still run a late-arriving legacy+ // cleanup callback: the widget acquired resources.+ lateCleanup = initPromise+ .then(async (settled) => {+ if (signal.aborted && isCleanup(settled)) {+ await safelyRunCleanup(settled, "late initialize");+ }+ })+ .catch(() => undefined);- // Race against destruction so a hung `initialize` can't strand- // callers whose model already closed.- const result = await Promise.race([- initPromise,- new Promise<never>((_, reject) => {- const abort = () => reject(new Error("[anywidget] binding destroyed"));- if (signal.aborted) {- abort();- return;- }- signal.addEventListener("abort", abort, { once: true });- }),- ]);+ // Race against destruction so a hung `initialize` can't strand+ // callers whose model already closed.+ const result = await Promise.race([+ initPromise,+ new Promise<never>((_, reject) => {+ const abort = () =>+ reject(new Error("[anywidget] binding destroyed"));+ if (signal.aborted) {+ abort();+ return;+ }+ signal.addEventListener("abort", abort, { once: true });+ }),+ ]);- if (signal.aborted) {- throw new Error("[anywidget] binding destroyed");- }+ if (signal.aborted) {+ throw new Error("[anywidget] binding destroyed");+ }- // Distinguish anywidget's three return shapes:- // function → legacy cleanup callback (run on destroy)- // object → widget exports (anywidget>=0.11)- // void → nothing- let exports: unknown;- let initializeCleanup: Cleanup | undefined;- if (isCleanup(result)) {- initializeCleanup = result;- exports = undefined;- } else if (typeof result === "object" && result !== null) {- exports = result;- } else {- exports = undefined;- }+ // Distinguish anywidget's three return shapes:+ // function → legacy cleanup callback (run on destroy)+ // object → widget exports (anywidget>=0.11)+ // void → nothing+ let exports: unknown;+ let initializeCleanup: Cleanup | undefined;+ if (isCleanup(result)) {+ initializeCleanup = result;+ exports = undefined;+ } else if (typeof result === "object" && result !== null) {+ exports = result;+ } else {+ exports = undefined;+ }- const binding = new WidgetBinding({- widget,- model,- exports,- controller,- createHost,- });- if (initializeCleanup) {- signal.addEventListener(- "abort",- () => void binding.#trackCleanup(initializeCleanup, "initialize"),- { once: true },- );+ const binding = new WidgetBinding({+ widget,+ model,+ exports,+ controller,+ createHost,+ onDestroy,+ });+ if (initializeCleanup) {+ signal.addEventListener(+ "abort",+ () => void binding.#trackCleanup(initializeCleanup, "initialize"),+ { once: true },+ );+ }+ return binding;+ } catch (error) {+ // A canceled initialize may still be using import.meta.url in its+ // late cleanup. Keep the module alive until that work settles.+ if (lateCleanup) {+ void lateCleanup.then(() => onDestroy?.());+ } else {+ onDestroy?.();+ }+ throw error;}- return binding;}/**@@ -353,6 +429,8 @@ export class WidgetBinding<T extends ModelState = ModelState> {while (this.#cleanupTasks.size > 0) {await Promise.all(this.#cleanupTasks);}+ this.#onDestroy?.();+ this.#onDestroy = undefined;}}diff --git a/frontend/src/plugins/impl/mpl-interactive/MplInteractivePlugin.tsx b/frontend/src/plugins/impl/mpl-interactive/MplInteractivePlugin.tsxindex b82da725f9..c6c8edb62e 100644--- a/frontend/src/plugins/impl/mpl-interactive/MplInteractivePlugin.tsx+++ b/frontend/src/plugins/impl/mpl-interactive/MplInteractivePlugin.tsx@@ -1,7 +1,7 @@/* Copyright 2026 Marimo. All rights reserved. *//* oxlint-disable typescript/no-explicit-any */-import { useCallback, useEffect, useRef } from "react";+import { useCallback, useEffect, useLayoutEffect, useRef } from "react";import { z } from "zod";import { useEventListener } from "@/hooks/useEventListener";import { createPlugin } from "@/plugins/core/builder";@@ -186,12 +186,14 @@ const MplInteractiveSlot = (props: IPluginProps<ModelIdRef, Data>) => {// the figure is built once, and switching to a new model is the rebind// effect's job, not a reason to tear the canvas down.const modelIdRef = useRef(modelId);- modelIdRef.current = modelId;// The data attributes are re-parsed into fresh objects on every rerun, so// `toolbarImages` changes identity even when its contents do not. Read it// from a ref so it can't retrigger the mount effect and rebuild the canvas.const toolbarImagesRef = useRef(toolbarImages);- toolbarImagesRef.current = toolbarImages;+ useLayoutEffect(() => {+ modelIdRef.current = modelId;+ toolbarImagesRef.current = toolbarImages;+ }, [modelId, toolbarImages]);// Bind the already-rendered figure/socket to a backend model, leaving the// DOM, figure, and socket in place so they survive across reruns. Disposesdiff --git a/frontend/src/plugins/impl/panel/PanelPlugin.tsx b/frontend/src/plugins/impl/panel/PanelPlugin.tsxindex f8b984e32c..98d87c9368 100644--- a/frontend/src/plugins/impl/panel/PanelPlugin.tsx+++ b/frontend/src/plugins/impl/panel/PanelPlugin.tsx@@ -1,7 +1,8 @@/* Copyright 2026 Marimo. All rights reserved. *//* oxlint-disable typescript/no-explicit-any */-import { useCallback, useEffect, useRef, useState } from "react";+import { useEffect, useRef, useState } from "react";+import useEvent from "react-use-event-hook";import { z } from "zod";import { MarimoIncomingMessageEvent } from "@/core/dom/events";import {@@ -146,17 +147,10 @@ const PanelSlot = (props: Props) => {> | null>(null);const [loaded, setLoaded] = useState<boolean>(false);const [rendered, setRendered] = useState<string | null>(null);+ const eventBufferRef = useRef<EventBuffer<unknown> | null>(null);- // Store functions in a ref so the callback captured by EventBuffer stays current- const functionsRef = useRef(functions);- functionsRef.current = functions;-- const processEvents = useCallback(() => {- if (!eventBufferRef.current) {- return;- }-- const events = eventBufferRef.current.getAndClear();+ const processEvents = useEvent(() => {+ const events = eventBufferRef.current?.getAndClear() ?? [];if (events.length === 0) {return;}@@ -182,14 +176,19 @@ const PanelSlot = (props: Props) => {);const buffers: ArrayBuffer[] = [];message.content = extractBuffers(message.content, buffers);- functionsRef.current.send_to_widget({ message, buffers }).catch((error) => {+ functions.send_to_widget({ message, buffers }).catch((error) => {Logger.warn("Failed to send Panel event to backend", error);});- }, []);+ });- const eventBufferRef = useRef<EventBuffer<unknown> | null>(- new EventBuffer(processEvents),- );+ useEffect(() => {+ const buffer = new EventBuffer(processEvents);+ eventBufferRef.current = buffer;+ return () => {+ buffer.dispose();+ eventBufferRef.current = null;+ };+ }, [processEvents]);// Load the bokeh extensionuseEffect(() => {diff --git a/frontend/src/plugins/impl/panel/__tests__/utils.test.ts b/frontend/src/plugins/impl/panel/__tests__/utils.test.tsindex ebaf6a15d4..c9c1316d1c 100644--- a/frontend/src/plugins/impl/panel/__tests__/utils.test.ts+++ b/frontend/src/plugins/impl/panel/__tests__/utils.test.ts@@ -1,5 +1,5 @@/* Copyright 2026 Marimo. All rights reserved. */-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { EventBuffer, extractBuffers, MessageSchema } from "../utils";describe("MessageSchema", () => {@@ -73,6 +73,44 @@ describe("EventBuffer", () => {eventBuffer = new EventBuffer(processEvents, 50);});+ afterEach(() => {+ eventBuffer.dispose();+ vi.useRealTimers();+ });++ it("flushes queued events and cancels the pending timer on dispose", () => {+ eventBuffer.add("event1");+ eventBuffer.add("event2");+ expect(vi.getTimerCount()).toBe(1);+ expect(processEvents).toHaveBeenCalledOnce();++ eventBuffer.dispose();+ expect(processEvents).toHaveBeenCalledTimes(2);+ eventBuffer.dispose();++ expect(eventBuffer.size()).toBe(0);+ expect(vi.getTimerCount()).toBe(0);+ vi.advanceTimersByTime(100);+ expect(processEvents).toHaveBeenCalledTimes(2);+ });++ it("does not process an empty buffer on dispose", () => {+ eventBuffer.dispose();+ expect(processEvents).not.toHaveBeenCalled();+ });++ it("resets the blocked state when disposed", () => {+ eventBuffer.add("event1");+ // Emulate a real processEvents, which drains the buffer+ eventBuffer.getAndClear();+ eventBuffer.dispose();+ eventBuffer.add("event2");++ expect(processEvents).toHaveBeenCalledTimes(2);+ expect(eventBuffer.getAndClear()).toEqual(["event2"]);+ expect(vi.getTimerCount()).toBe(1);+ });+it("should add events to buffer", () => {eventBuffer.add("event1");eventBuffer.add("event2");diff --git a/frontend/src/plugins/impl/panel/utils.ts b/frontend/src/plugins/impl/panel/utils.tsindex 0fc821cca6..4be2c4fc17 100644--- a/frontend/src/plugins/impl/panel/utils.ts+++ b/frontend/src/plugins/impl/panel/utils.ts@@ -83,6 +83,7 @@ export class EventBuffer<T> {clearTimeout(this.timeout);}this.timeout = window.setTimeout(() => {+ this.timeout = null;this.isBlocked = false;if (this.buffer.length > 0) {this.flush();@@ -98,6 +99,22 @@ export class EventBuffer<T> {this.buffer = [];}+ /**+ * Cancel the pending timer, flushing any events still held by the block+ * window so the last user interaction is not lost.+ */+ public dispose() {+ if (this.timeout !== null) {+ clearTimeout(this.timeout);+ this.timeout = null;+ }+ this.isBlocked = false;+ if (this.buffer.length > 0) {+ this.processEvents();+ }+ this.clear();+ }+public getAndClear() {const events = this.buffer;this.buffer = [];diff --git a/frontend/src/stories/__tests__/editor-story.test.tsx b/frontend/src/stories/__tests__/editor-story.test.tsxnew file mode 100644index 0000000000..76d87276db--- /dev/null+++ b/frontend/src/stories/__tests__/editor-story.test.tsx@@ -0,0 +1,33 @@+/* Copyright 2026 Marimo. All rights reserved. */+import { EditorView } from "@codemirror/view";+import { composeStories } from "@storybook/react-vite";+import { act, render } from "@testing-library/react";+import { expect, it, vi } from "vitest";+import * as stories from "../editor.stories";++vi.mock("@/core/codemirror/cm", () => ({+ basicBundle: () => [],+}));++const { Primary } = composeStories(stories);++it("preserves editor changes when the story rerenders with the same theme", () => {+ const { container, rerender } = render(<Primary />);+ const editor = container.querySelector<HTMLElement>(".cm-editor");+ expect(editor).not.toBeNull();+ const view = editor && EditorView.findFromDOM(editor);+ expect(view).toBeDefined();+ if (!view) {+ throw new Error("Editor view was not mounted");+ }++ act(() => {+ view.dispatch({+ changes: { from: 0, to: view.state.doc.length, insert: "user edit" },+ });+ });+ rerender(<Primary />);++ expect(container.querySelector(".cm-editor")).toBe(editor);+ expect(view.state.doc.toString()).toBe("user edit");+});diff --git a/frontend/src/stories/editor.stories.tsx b/frontend/src/stories/editor.stories.tsxindex de0a150dc9..9d3e067e95 100644--- a/frontend/src/stories/editor.stories.tsx+++ b/frontend/src/stories/editor.stories.tsx@@ -5,7 +5,7 @@ import { EditorState, type Extension } from "@codemirror/state";import { EditorView } from "@codemirror/view";import type { Meta, StoryObj } from "@storybook/react-vite";import CodeMirror from "@uiw/react-codemirror";-import { useEffect, useRef } from "react";+import { useEffect, useMemo, useRef } from "react";import { CopilotConfig } from "@/core/codemirror/copilot/copilot-config";import { copilotBundle } from "@/core/codemirror/copilot/extension";import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";@@ -52,28 +52,35 @@ const Editor = (opts: { extensions?: Extension[] }): React.ReactNode => {});return () => view.destroy();- // oxlint-disable-next-line react-hooks/exhaustive-deps- }, [ref.current]);+ }, [opts.extensions]);return <div className="cm" ref={ref} />;};-export const Primary: Story = {- render: (_args, ctx) => (+const PrimaryEditor = ({ theme }: Pick<CodeMirrorSetupOpts, "theme">) => {+ const extensions = useMemo(+ () =>+ basicBundle({+ completionConfig: {+ activate_on_typing: false,+ copilot: false,+ signature_hint_on_typing: false,+ },+ theme,+ hotkeys: new OverridingHotkeyProvider({}),+ } as unknown as CodeMirrorSetupOpts),+ [theme],+ );++ return (<div className="Cell m-20 w-[60%] overflow-hidden">- <Editor- extensions={basicBundle({- completionConfig: {- activate_on_typing: false,- copilot: false,- signature_hint_on_typing: false,- },- theme: ctx.globals.theme,- hotkeys: new OverridingHotkeyProvider({}),- } as unknown as CodeMirrorSetupOpts)}- />+ <Editor extensions={extensions} /></div>- ),+ );+};++export const Primary: Story = {+ render: (_args, ctx) => <PrimaryEditor theme={ctx.globals.theme} />,};export const DefaultPython: Story = {