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: recover file browser after cached output resets (#10862)
Myles Scolnick146cf3d82572
diff --git a/frontend/src/plugins/impl/FileBrowserPlugin.tsx b/frontend/src/plugins/impl/FileBrowserPlugin.tsxindex 5bc4b90038..32365eb95c 100644--- a/frontend/src/plugins/impl/FileBrowserPlugin.tsx+++ b/frontend/src/plugins/impl/FileBrowserPlugin.tsx@@ -218,7 +218,7 @@ export const FileBrowser = ({const { data, error, isPending } = useAsyncData(() => {return list_directory({ path: path });- }, [path, randomId]);+ }, [path, randomId, list_directory]);useEffect(() => {if (!isPending) {@@ -238,9 +238,15 @@ export const FileBrowser = ({// Reset the roving tabindex whenever the listing reloads (a new path or a// same-path refresh) so activeIndex never points past the current rows.const listingKey = `${path}::${randomId}`;- const [prevListingKey, setPrevListingKey] = useState(listingKey);- if (prevListingKey !== listingKey) {- setPrevListingKey(listingKey);+ const [prevListing, setPrevListing] = useState({+ listingKey,+ list_directory,+ });+ if (+ prevListing.listingKey !== listingKey ||+ prevListing.list_directory !== list_directory+ ) {+ setPrevListing({ listingKey, list_directory });setActiveIndex(0);}diff --git a/frontend/src/plugins/impl/__tests__/FileBrowserPlugin.test.tsx b/frontend/src/plugins/impl/__tests__/FileBrowserPlugin.test.tsxindex f16b2c21a4..9bfc7e3b0c 100644--- a/frontend/src/plugins/impl/__tests__/FileBrowserPlugin.test.tsx+++ b/frontend/src/plugins/impl/__tests__/FileBrowserPlugin.test.tsx@@ -5,8 +5,9 @@ import { beforeAll, describe, expect, it, vi } from "vitest";import { SetupMocks } from "@/__mocks__/common";import { initialModeAtom } from "@/core/mode";import { store } from "@/core/state/jotai";+import { CellNotInitializedError } from "@/utils/errors";import type { IPluginProps } from "../../types";-import { FileBrowserPlugin } from "../FileBrowserPlugin";+import { FileBrowser, FileBrowserPlugin } from "../FileBrowserPlugin";interface MockFile {id: string;@@ -80,6 +81,54 @@ beforeAll(() => {store.set(initialModeAtom, "edit");});+describe("FileBrowserPlugin session cache recovery", () => {+ it("retries a failed cached listing when the plugin resets", async () => {+ const host = document.createElement("marimo-file-browser");+ const wrapper = document.createElement("marimo-ui-element");+ wrapper.setAttribute("random-id", "cached-id");+ wrapper.append(host);++ const props = {+ initialPath: "/home/user",+ filetypes: [],+ selectionMode: "directory",+ multiple: false,+ label: "Pick folder",+ restrictNavigation: false,+ value: [],+ setValue: vi.fn(),+ host,+ };+ const error = new CellNotInitializedError();+ const cachedListDirectory = vi.fn().mockRejectedValue(error);+ const { rerender } = render(+ <FileBrowser {...props} list_directory={cachedListDirectory} />,+ );+ expect(await screen.findByText(error.message)).toBeInTheDocument();++ // PluginSlot recreates the RPC functions on reset, even when the path+ // and the host's attributes are unchanged.+ const liveListDirectory = mockListDirectory(FILES);+ rerender(<FileBrowser {...props} list_directory={liveListDirectory} />);++ expect(await screen.findByText("docs")).toBeInTheDocument();+ expect(screen.queryByText(error.message)).not.toBeInTheDocument();+ expect(liveListDirectory.mock.calls).toEqual([[{ path: "/home/user" }]]);++ fireEvent.click(screen.getByRole("checkbox", { name: "Select docs" }));+ expect(props.setValue).toHaveBeenCalledWith([+ { ...FILES[0], id: FILES[0].path },+ ]);++ fireEvent.keyDown(screen.getAllByRole("row")[0], { key: "End" });+ rerender(+ <FileBrowser {...props} list_directory={mockListDirectory([FILES[0]])} />,+ );+ await waitFor(() => expect(screen.getAllByRole("row")).toHaveLength(2));+ expect(screen.getAllByRole("row")[0]).toHaveAttribute("tabindex", "0");+ });+});+describe("FileBrowserPlugin keyboard accessibility", () => {it("renders a row per file plus the parent row", async () => {renderBrowser();diff --git a/marimo/_plugins/ui/_core/registry.py b/marimo/_plugins/ui/_core/registry.pyindex 298b23846b..4d726ea116 100644--- a/marimo/_plugins/ui/_core/registry.py+++ b/marimo/_plugins/ui/_core/registry.py@@ -37,7 +37,7 @@ class UIElementRegistry:# on cell re-run, a UI element may be (re)-registered before# its destructor was called, so manually delete the old element# here- self.delete(object_id, id(self._objects[object_id]))+ self.delete(object_id, id(self._objects[object_id]()))self._objects[object_id] = weakref.ref(ui_element)assert execution_context is not Noneself._constructing_cells[object_id] = execution_context.cell_iddiff --git a/tests/_plugins/ui/_core/test_registry.py b/tests/_plugins/ui/_core/test_registry.pyindex ee75937f8c..0452ea788d 100644--- a/tests/_plugins/ui/_core/test_registry.py+++ b/tests/_plugins/ui/_core/test_registry.py@@ -271,3 +271,40 @@ def test_owner_registry_delete_removes_function_namespace(assert ctx.function_registry.get_function(object_id, "function") is Nonewith pytest.raises(KeyError):ctx.ui_element_registry.get_object(object_id)+++def test_reregister_removes_old_functions(executing_kernel: Kernel) -> None:+ del executing_kernel+ ctx = get_context()+ registry = ctx.ui_element_registry+ old_element = ui.text()+ replacement = ui.text()+ object_id = old_element._id+ old_function = Function(+ name="old_function",+ arg_cls=EmptyArgs,+ function=lambda _args: None,+ )+ ctx.function_registry.register(namespace=object_id, function=old_function)++ # The old element is still alive when a new instance reuses its ID.+ registry.register(object_id, replacement)++ assert registry.get_object(object_id) is replacement+ assert (+ ctx.function_registry.get_function(object_id, "old_function") is None+ )++ new_function = Function(+ name="new_function",+ arg_cls=EmptyArgs,+ function=lambda _args: None,+ )+ ctx.function_registry.register(namespace=object_id, function=new_function)+ registry.delete(object_id, id(old_element))++ assert registry.get_object(object_id) is replacement+ assert (+ ctx.function_registry.get_function(object_id, "new_function")+ is new_function+ )