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.

feat: make the file browser faster and easier to navigate (#10773)

Shahmir Varqha7203417502a1
diff --git a/frontend/src/components/editor/file-tree/__tests__/file-explorer-navigation.test.tsx b/frontend/src/components/editor/file-tree/__tests__/file-explorer-navigation.test.tsx
new file mode 100644
index 0000000000..9b404d2b1c
--- /dev/null
+++ b/frontend/src/components/editor/file-tree/__tests__/file-explorer-navigation.test.tsx
@@ -0,0 +1,832 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import {
+ act,
+ fireEvent,
+ render,
+ renderHook,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { Provider, createStore } from "jotai";
+import type { ReactNode } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { MockRequestClient } from "@/__mocks__/requests";
+import { ModalProvider } from "@/components/modal/ImperativeModal";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { requestClientAtom } from "@/core/network/requests";
+import type { FileInfo, FileSearchResponse } from "@/core/network/types";
+import { Deferred } from "@/utils/Deferred";
+import type { FilePath } from "@/utils/paths";
+import { TreeDndProvider } from "../dnd-wrapper";
+import { FileExplorer } from "../file-explorer";
+import { openStateAtom } from "../state";
+import { fileTreeNodeId, RequestingTree } from "../requesting-tree";
+import { useFileSearch } from "../use-file-search";
+import { HOVER_EXPAND_DELAY } from "../use-hover-expand";
+
+vi.mock("../file-viewer", () => ({
+ FileViewer: ({ file }: { file: FileInfo }) => <div>Preview: {file.name}</div>,
+}));
+
+function file(name: string, isDirectory = false): FileInfo {
+ return {
+ id: name,
+ name: name.split("/").at(-1) ?? name,
+ path: `/workspace/${name}`,
+ isDirectory,
+ isMarimoFile: false,
+ };
+}
+
+function createDragEvents(clientY = 115) {
+ const dataTransfer = {
+ setData: vi.fn(),
+ getData: vi.fn(),
+ setDragImage: vi.fn(),
+ types: [],
+ dropEffect: "move",
+ effectAllowed: "all",
+ };
+ return (target: Element, type: string) => {
+ // jsdom has no DragEvent; MouseEvent preserves the pointer coordinates.
+ const event = new MouseEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ clientX: 100,
+ clientY,
+ });
+ Object.defineProperty(event, "dataTransfer", { value: dataTransfer });
+ fireEvent(target, event);
+ };
+}
+
+let store = createStore();
+let client: ReturnType<typeof MockRequestClient.create>;
+const wrapper = ({ children }: { children: ReactNode }) => (
+ <Provider store={store}>
+ <TooltipProvider>
+ <ModalProvider>
+ <TreeDndProvider>{children}</TreeDndProvider>
+ </ModalProvider>
+ </TooltipProvider>
+ </Provider>
+);
+
+beforeEach(() => {
+ localStorage.clear();
+ store = createStore();
+ client = MockRequestClient.create({
+ getFileRoots: vi.fn().mockResolvedValue({
+ roots: [{ path: "/workspace", name: "workspace", isPrimary: true }],
+ }),
+ sendListFiles: vi.fn().mockImplementation(async ({ path }) => ({
+ files:
+ path === "/workspace"
+ ? [file("data", true), file("notes.txt")]
+ : [file("data/report.csv")],
+ })),
+ });
+ store.set(requestClientAtom, client);
+});
+
+describe("file browser navigation", () => {
+ it("debounces the first character, subsequent edits, and searches after clearing", async () => {
+ render(<FileExplorer height={300} />, { wrapper });
+ const input = await screen.findByRole("textbox", {
+ name: "Search files and folders",
+ });
+ vi.useFakeTimers();
+ try {
+ fireEvent.change(input, { target: { value: "n" } });
+ await act(() => vi.advanceTimersByTimeAsync(100));
+ expect(client.sendSearchFiles).not.toHaveBeenCalled();
+ fireEvent.change(input, { target: { value: "no" } });
+ await act(() => vi.advanceTimersByTimeAsync(299));
+ expect(client.sendSearchFiles).not.toHaveBeenCalled();
+ await act(() => vi.advanceTimersByTimeAsync(1));
+ expect(client.sendSearchFiles).toHaveBeenCalledOnce();
+ expect(client.sendSearchFiles).toHaveBeenLastCalledWith(
+ expect.objectContaining({ query: "no" }),
+ );
+
+ fireEvent.change(input, { target: { value: "" } });
+ fireEvent.change(input, { target: { value: "f" } });
+ await act(() => vi.advanceTimersByTimeAsync(299));
+ expect(client.sendSearchFiles).toHaveBeenCalledOnce();
+ await act(() => vi.advanceTimersByTimeAsync(1));
+ expect(client.sendSearchFiles).toHaveBeenCalledTimes(2);
+ expect(client.sendSearchFiles).toHaveBeenLastCalledWith(
+ expect.objectContaining({ query: "f" }),
+ );
+
+ fireEvent.change(input, { target: { value: "" } });
+ await act(() => vi.advanceTimersByTimeAsync(300));
+ expect(client.sendSearchFiles).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("navigates with arrows, opens with Enter, and restores the tree after preview", async () => {
+ render(<FileExplorer height={300} />, { wrapper });
+ const tree = await screen.findByRole("tree");
+ act(() => tree.focus());
+ expect(document.activeElement).toHaveTextContent("data");
+ fireEvent.keyDown(document.activeElement!, { key: "ArrowRight" });
+ expect(client.sendListFiles).toHaveBeenCalledWith({
+ path: "/workspace/data",
+ });
+ expect(await screen.findByText("report.csv")).toBeVisible();
+ fireEvent.keyDown(document.activeElement!, { key: "ArrowDown" });
+ expect(screen.queryByText("Preview: report.csv")).not.toBeInTheDocument();
+ expect(document.activeElement).toHaveTextContent("report.csv");
+ fireEvent.keyDown(document.activeElement!, { key: "Enter" });
+ expect(await screen.findByText("Preview: report.csv")).toBeVisible();
+ fireEvent.click(screen.getByRole("button", { name: "Back to files" }));
+ expect(await screen.findByText("report.csv")).toBeVisible();
+ expect(screen.getByRole("tree")).toBe(tree);
+ await waitFor(() =>
+ expect(document.activeElement).toHaveTextContent("report.csv"),
+ );
+ });
+
+ it("bounds mounted rows for a directory with 10,000 files and supports End navigation", async () => {
+ client.sendListFiles.mockResolvedValue({
+ root: "/workspace",
+ files: Array.from({ length: 10_000 }, (_, index) =>
+ file(`file-${index}.txt`),
+ ),
+ });
+ render(<FileExplorer height={300} />, { wrapper });
+ const tree = await screen.findByRole("tree");
+ expect(screen.getAllByRole("treeitem").length).toBeLessThan(40);
+ act(() => tree.focus());
+ fireEvent.keyDown(document.activeElement!, { key: "End" });
+ expect(await screen.findByText("file-9999.txt")).toBeVisible();
+ expect(screen.getAllByRole("treeitem").length).toBeLessThan(40);
+ });
+
+ it("renames with F2 and keeps leaf files distinct from expandable folders", async () => {
+ render(<FileExplorer height={300} />, { wrapper });
+ const row = await screen.findByRole("treeitem", { name: "notes.txt" });
+ expect(row).not.toHaveAttribute("aria-expanded");
+ expect(screen.getByRole("treeitem", { name: "data" })).toHaveAttribute(
+ "aria-expanded",
+ "false",
+ );
+ fireEvent.click(screen.getByText("notes.txt"));
+ fireEvent.keyDown(row, { key: "F2" });
+ expect(await screen.findByDisplayValue("notes.txt")).toHaveFocus();
+ fireEvent.keyDown(document.activeElement!, { key: "Escape" });
+ expect(client.sendRenameFileOrFolder).not.toHaveBeenCalled();
+ });
+
+ it("reveals and expands folders found by search", async () => {
+ client.sendSearchFiles.mockResolvedValue({
+ files: [file("data", true)],
+ query: "data",
+ totalFound: 1,
+ });
+ render(<FileExplorer height={300} />, { wrapper });
+ const input = await screen.findByRole("textbox", {
+ name: "Search files and folders",
+ });
+ fireEvent.change(input, { target: { value: "data" } });
+ await screen.findByText("1 match");
+ fireEvent.keyDown(input, { key: "Enter" });
+ expect(await screen.findByText("report.csv")).toBeVisible();
+ expect(input).toHaveValue("");
+ expect(screen.getByRole("treeitem", { name: "data" })).toHaveAttribute(
+ "aria-expanded",
+ "true",
+ );
+ });
+
+ it("finds unopened descendants and supports keyboard activation from the search field", async () => {
+ client.sendSearchFiles.mockResolvedValue({
+ files: [file("data/report.csv")],
+ query: "report",
+ totalFound: 1,
+ });
+ render(<FileExplorer height={300} />, { wrapper });
+ const input = await screen.findByRole("textbox", {
+ name: "Search files and folders",
+ });
+ fireEvent.change(input, { target: { value: "report" } });
+ expect(await screen.findByText("report.csv")).toBeVisible();
+ expect(client.sendSearchFiles).toHaveBeenCalledWith(
+ expect.objectContaining({ query: "report", path: "/workspace" }),
+ );
+ fireEvent.keyDown(input, { key: "ArrowDown" });
+ await waitFor(() =>
+ expect(document.activeElement).toHaveTextContent("report.csv"),
+ );
+ fireEvent.keyDown(document.activeElement!, { key: "Enter" });
+ expect(await screen.findByText("Preview: report.csv")).toBeVisible();
+ fireEvent.click(screen.getByRole("button", { name: "Back to files" }));
+ expect(input).toHaveValue("report");
+ fireEvent.keyDown(input, { key: "Escape" });
+ expect(input).toHaveValue("");
+ });
+
+ it("previews search files without loading their ancestors", async () => {
+ client.sendSearchFiles.mockResolvedValue({
+ files: [file("new/nested/report.csv")],
+ query: "report",
+ totalFound: 1,
+ });
+ render(<FileExplorer height={300} />, { wrapper });
+ const input = await screen.findByRole("textbox", {
+ name: "Search files and folders",
+ });
+ client.sendListFiles.mockClear();
+ fireEvent.change(input, { target: { value: "report" } });
+ await screen.findByText("1 match");
+ fireEvent.keyDown(input, { key: "Enter" });
+ expect(await screen.findByText("Preview: report.csv")).toBeVisible();
+ expect(client.sendListFiles).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { offset: 1, sourceName: "notes.txt", canMove: true },
+ { offset: 15, sourceName: "notes.txt", canMove: true },
+ { offset: 29, sourceName: "notes.txt", canMove: true },
+ { offset: 15, sourceName: "data", canMove: false },
+ ])(
+ "drops $sourceName at folder offset $offset with canMove=$canMove",
+ async ({ offset, sourceName, canMove }) => {
+ render(<FileExplorer height={300} />, { wrapper });
+ const folder = await screen.findByRole("treeitem", { name: "data" });
+ const source = screen.getByRole("treeitem", {
+ name: sourceName,
+ }).firstElementChild;
+ if (!source) {
+ throw new Error("Missing drag source");
+ }
+ vi.spyOn(folder, "getBoundingClientRect").mockReturnValue(
+ new DOMRect(0, 100, 300, 30),
+ );
+ const dragEvent = createDragEvents(100 + offset);
+ dragEvent(source, "dragstart");
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+ dragEvent(folder, "dragenter");
+ dragEvent(folder, "dragover");
+ await act(async () => {
+ await new Promise(requestAnimationFrame);
+ });
+ dragEvent(folder, "drop");
+ if (canMove) {
+ await waitFor(() =>
+ expect(client.sendRenameFileOrFolder).toHaveBeenCalledExactlyOnceWith(
+ {
+ path: "/workspace/notes.txt",
+ newPath: "/workspace/data/notes.txt",
+ },
+ ),
+ );
+ } else {
+ expect(client.sendRenameFileOrFolder).not.toHaveBeenCalled();
+ }
+ dragEvent(source, "dragend");
+ },
+ );
+
+ it("expands hovered folders after a delay and supports nested drops", async () => {
+ client.sendListFiles.mockImplementation(async ({ path }) => {
+ if (path === "/workspace") {
+ return {
+ root: "/workspace",
+ files: [file("data", true), file("notes.txt")],
+ };
+ }
+ if (path === "/workspace/data") {
+ return { root: "/workspace", files: [file("data/nested", true)] };
+ }
+ return { root: "/workspace", files: [] };
+ });
+ render(<FileExplorer height={300} />, { wrapper });
+ const folder = await screen.findByRole("treeitem", { name: "data" });
+ const source = screen.getByRole("treeitem", {
+ name: "notes.txt",
+ }).firstElementChild;
+ if (!source) {
+ throw new Error("Missing drag source");
+ }
+ const dragEvent = createDragEvents();
+ vi.useFakeTimers();
+ try {
+ dragEvent(source, "dragstart");
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ dragEvent(folder, "dragenter");
+ dragEvent(folder, "dragover");
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(HOVER_EXPAND_DELAY - 1);
+ });
+ expect(folder).toHaveAttribute("aria-expanded", "false");
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+ expect(folder).toHaveAttribute("aria-expanded", "true");
+ expect(client.sendListFiles).toHaveBeenCalledWith({
+ path: "/workspace/data",
+ });
+ const nested = screen.getByRole("treeitem", { name: "nested" });
+ dragEvent(nested, "dragenter");
+ dragEvent(nested, "dragover");
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(16);
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(HOVER_EXPAND_DELAY);
+ });
+ expect(nested).toHaveAttribute("aria-expanded", "true");
+ expect(client.sendListFiles).toHaveBeenCalledWith({
+ path: "/workspace/data/nested",
+ });
+ await act(async () => {
+ dragEvent(nested, "drop");
+ });
+ expect(client.sendRenameFileOrFolder).toHaveBeenCalledExactlyOnceWith({
+ path: "/workspace/notes.txt",
+ newPath: "/workspace/data/nested/notes.txt",
+ });
+ dragEvent(source, "dragend");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it.each(["leave", "end", "invalid"])(
+ "does not expand a folder when the drag is %s",
+ async (reason) => {
+ render(<FileExplorer height={300} />, { wrapper });
+ const folder = await screen.findByRole("treeitem", { name: "data" });
+ const sourceRow =
+ reason === "invalid"
+ ? folder
+ : screen.getByRole("treeitem", { name: "notes.txt" });
+ const source = sourceRow.firstElementChild;
+ if (!source) {
+ throw new Error("Missing drag source");
+ }
+ const dragEvent = createDragEvents();
+ vi.useFakeTimers();
+ try {
+ dragEvent(source, "dragstart");
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ dragEvent(folder, "dragenter");
+ dragEvent(folder, "dragover");
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(400);
+ });
+ if (reason === "leave") {
+ dragEvent(sourceRow, "dragenter");
+ dragEvent(sourceRow, "dragover");
+ } else if (reason === "end") {
+ dragEvent(source, "dragend");
+ }
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1000);
+ });
+ expect(folder).toHaveAttribute("aria-expanded", "false");
+ expect(client.sendListFiles).not.toHaveBeenCalledWith({
+ path: "/workspace/data",
+ });
+ dragEvent(source, "dragend");
+ } finally {
+ vi.useRealTimers();
+ }
+ },
+ );
+
+ it("expands nested external upload destinations and cancels when the drag leaves", async () => {
+ client.sendListFiles.mockImplementation(async ({ path }) => {
+ if (path === "/workspace") {
+ return { root: "/workspace", files: [file("data", true)] };
+ }
+ if (path === "/workspace/data") {
+ return { root: "/workspace", files: [file("data/nested", true)] };
+ }
+ return { root: "/workspace", files: [] };
+ });
+ const { rerender } = render(<FileExplorer height={300} />, { wrapper });
+ const folder = await screen.findByRole("treeitem", { name: "data" });
+ vi.useFakeTimers();
+ try {
+ rerender(
+ <FileExplorer
+ height={300}
+ externalDropDestinationPath={"/workspace/data" as FilePath}
+ />,
+ );
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(300);
+ });
+ rerender(
+ <FileExplorer height={300} externalDropDestinationPath={null} />,
+ );
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(HOVER_EXPAND_DELAY);
+ });
+ expect(folder).toHaveAttribute("aria-expanded", "false");
+ rerender(
+ <FileExplorer
+ height={300}
+ externalDropDestinationPath={"/workspace/data" as FilePath}
+ />,
+ );
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(HOVER_EXPAND_DELAY - 1);
+ });
+ expect(folder).toHaveAttribute("aria-expanded", "false");
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1);
+ });
+ expect(folder).toHaveAttribute("aria-expanded", "true");
+ const nested = screen.getByRole("treeitem", { name: "nested" });
+ rerender(
+ <FileExplorer
+ height={300}
+ externalDropDestinationPath={"/workspace/data/nested" as FilePath}
+ />,
+ );
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(HOVER_EXPAND_DELAY);
+ });
+ expect(nested).toHaveAttribute("aria-expanded", "true");
+ expect(client.sendListFiles).toHaveBeenCalledWith({
+ path: "/workspace/data/nested",
+ });
+ expect(client.sendRenameFileOrFolder).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("ranks matches across roots before applying the global result limit", async () => {
+ client.getFileRoots.mockResolvedValue({
+ roots: [
+ { path: "/workspace", name: "workspace", isPrimary: true },
+ { path: "/shared", name: "shared", isPrimary: false },
+ ],
+ });
+ client.sendSearchFiles.mockImplementation(async ({ path, query }) => {
+ const files =
+ path === "/workspace"
+ ? Array.from({ length: 200 }, (_, index) =>
+ file(`report-${index}.txt`),
+ )
+ : [{ ...file("report"), path: "/shared/report" }];
+ return { files, query, totalFound: files.length };
+ });
+ render(<FileExplorer height={300} />, { wrapper });
+ const input = await screen.findByRole("textbox", {
+ name: "Search files and folders",
+ });
+ fireEvent.change(input, { target: { value: "report" } });
+ await screen.findByText(/200 matches/);
+ const results = screen.getAllByRole("treeitem");
+ expect(results[0]).toHaveAccessibleName("/shared/report");
+ expect(
+ client.sendSearchFiles.mock.calls.map(([request]) => request.path),
+ ).toEqual(["/workspace", "/shared"]);
+ });
+
+ it.each([false, true])(
+ "deduplicates overlapping roots before limiting (primary first: %s)",
+ async (primaryFirst) => {
+ const roots = [
+ { path: "/workspace", name: "workspace", isPrimary: true },
+ { path: "/workspace/data", name: "data", isPrimary: false },
+ ];
+ client.getFileRoots.mockResolvedValue({
+ roots: primaryFirst ? roots : roots.toReversed(),
+ });
+ const sharedFiles = Array.from({ length: 150 }, (_, index) =>
+ file(`data/report-${index}.txt`),
+ );
+ client.sendSearchFiles.mockImplementation(async ({ path, query }) => {
+ const files =
+ path === "/workspace"
+ ? [...sharedFiles, file("report-unique.txt")]
+ : sharedFiles;
+ return { files, query, totalFound: files.length };
+ });
+ const tree = new RequestingTree({
+ getRoots: client.getFileRoots,
+ listFiles: client.sendListFiles,
+ createFileOrFolder: client.sendCreateFileOrFolder,
+ deleteFileOrFolder: client.sendDeleteFileOrFolder,
+ copyFileOrFolder: client.sendCopyFileOrFolder,
+ renameFileOrFolder: client.sendRenameFileOrFolder,
+ });
+ await tree.initialize(vi.fn());
+ const { result } = renderHook(
+ () => useFileSearch({ query: "report", tree, showHiddenFiles: false }),
+ { wrapper },
+ );
+ await waitFor(() => expect(result.current.state.status).toBe("success"));
+ const state = result.current.state;
+ if (state.status !== "success") {
+ throw new Error("Expected search results");
+ }
+ expect(state.files).toHaveLength(151);
+ expect(new Set(state.files.map((file) => file.path)).size).toBe(151);
+ expect(
+ state.files.every(
+ (file) => file.rootPath === "/workspace" && file.isPrimaryRoot,
+ ),
+ ).toBe(true);
+ expect(
+ state.files.some(
+ (file) => file.path === "/workspace/report-unique.txt",
+ ),
+ ).toBe(true);
+ expect(state.hasMore).toBe(false);
+ },
+ );
+
+ it("distinguishes same-named search results by their accessible paths", async () => {
+ client.sendSearchFiles.mockResolvedValue({
+ query: "report",
+ files: [file("data/report.csv"), file("archive/report.csv")],
+ totalFound: 2,
+ });
+ render(<FileExplorer height={300} />, { wrapper });
+ fireEvent.change(
+ await screen.findByRole("textbox", { name: "Search files and folders" }),
+ { target: { value: "report" } },
+ );
+ expect(
+ await screen.findByRole("treeitem", {
+ name: "/workspace/data/report.csv",
+ }),
+ ).toBeVisible();
+ expect(
+ screen.getByRole("treeitem", { name: "/workspace/archive/report.csv" }),
+ ).toBeVisible();
+ });
+
+ it("shows an error when every search root fails", async () => {
+ client.sendSearchFiles.mockRejectedValue(new Error("Unavailable"));
+ render(<FileExplorer height={300} />, { wrapper });
+ const input = await screen.findByRole("textbox", {
+ name: "Search files and folders",
+ });
+ fireEvent.change(input, { target: { value: "report" } });
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Could not search files",
+ );
+ expect(screen.getByRole("button", { name: "Retry" })).toBeInTheDocument();
+ });
+
+ it("retries failed hover expansion only after leaving and reentering", async () => {
+ const { rerender } = render(<FileExplorer height={300} />, { wrapper });
+ const folder = await screen.findByRole("treeitem", { name: "data" });
+ client.sendListFiles.mockRejectedValue(new Error("Unavailable"));
+ client.sendListFiles.mockClear();
+ vi.useFakeTimers();
+ try {
+ rerender(
+ <FileExplorer
+ height={300}
+ externalDropDestinationPath={"/workspace/data" as FilePath}
+ />,
+ );
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(HOVER_EXPAND_DELAY);
+ });
+ expect(folder).toHaveAttribute("aria-expanded", "false");
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(HOVER_EXPAND_DELAY * 5);
+ });
+ expect(client.sendListFiles).toHaveBeenCalledTimes(1);
+ rerender(
+ <FileExplorer height={300} externalDropDestinationPath={null} />,
+ );
+ client.sendListFiles.mockResolvedValue({
+ root: "/workspace",
+ files: [file("data/report.csv")],
+ });
+ rerender(
+ <FileExplorer
+ height={300}
+ externalDropDestinationPath={"/workspace/data" as FilePath}
+ />,
+ );
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(HOVER_EXPAND_DELAY);
+ });
+ expect(client.sendListFiles).toHaveBeenCalledTimes(2);
+ expect(folder).toHaveAttribute("aria-expanded", "true");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("keeps partial results when a root fails, and retries all roots", async () => {
+ client.getFileRoots.mockResolvedValue({
+ roots: [
+ { path: "/workspace", name: "workspace", isPrimary: true },
+ { path: "/shared", name: "shared", isPrimary: false },
+ ],
+ });
+ let sharedUnavailable = true;
+ client.sendSearchFiles.mockImplementation(async ({ path, query }) => {
+ if (path === "/shared" && sharedUnavailable) {
+ throw new Error("Storage unavailable");
+ }
+ return {
+ files: [{ ...file("report.txt"), path: `${path}/report.txt` }],
+ query,
+ totalFound: 1,
+ };
+ });
+ render(<FileExplorer height={300} />, { wrapper });
+ const input = await screen.findByRole("textbox", {
+ name: "Search files and folders",
+ });
+ fireEvent.change(input, { target: { value: "report" } });
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Some locations could not be searched",
+ );
+ expect(
+ screen.getByRole("treeitem", { name: "/workspace/report.txt" }),
+ ).toBeInTheDocument();
+ fireEvent.click(
+ screen.getByRole("treeitem", { name: "/workspace/report.txt" }),
+ );
+ const retry = screen.getByRole("button", { name: "Retry" });
+ retry.focus();
+ sharedUnavailable = false;
+ expect(fireEvent.keyDown(retry, { key: "Enter" })).toBe(true);
+ // jsdom does not synthesize a button click from Enter.
+ fireEvent.click(retry);
+ await screen.findByText("2 matches");
+ expect(screen.queryByText("Preview: report.txt")).not.toBeInTheDocument();
+ expect(
+ client.sendSearchFiles.mock.calls.map(([request]) => request.path),
+ ).toEqual(["/workspace", "/shared", "/workspace", "/shared"]);
+ });
+
+ it.each([
+ { counts: [100, 100], truncated: false },
+ { counts: [200, 0], truncated: true },
+ { counts: [150, 100], truncated: true },
+ ])(
+ "reports search truncation correctly for $counts",
+ async ({ counts, truncated }) => {
+ client.getFileRoots.mockResolvedValue({
+ roots: [
+ { path: "/workspace", name: "workspace", isPrimary: true },
+ { path: "/shared", name: "shared", isPrimary: false },
+ ],
+ });
+ client.sendSearchFiles.mockImplementation(async ({ path, query }) => {
+ const count = counts[path === "/workspace" ? 0 : 1];
+ const files = Array.from({ length: count }, (_, index) => ({
+ ...file(`report-${index}`),
+ path: `${path}/report-${index}`,
+ }));
+ return { files, query, totalFound: files.length };
+ });
+ render(<FileExplorer height={300} />, { wrapper });
+ const input = await screen.findByRole("textbox", {
+ name: "Search files and folders",
+ });
+ fireEvent.change(input, { target: { value: "report" } });
+ const status = await screen.findByText(/200 matches/);
+ expect(status.textContent?.includes("Refine your search")).toBe(
+ truncated,
+ );
+ },
+ );
+
+ it("keeps keyboard navigation aligned with a clicked row", async () => {
+ client.sendListFiles.mockResolvedValue({
+ root: "/workspace",
+ files: [file("a.txt"), file("b.txt"), file("c.txt")],
+ });
+ render(<FileExplorer height={300} />, { wrapper });
+ const middle = await screen.findByRole("treeitem", { name: "b.txt" });
+ fireEvent.click(screen.getByText("b.txt"));
+ expect(middle).toHaveFocus();
+ fireEvent.keyDown(middle, { key: "ArrowDown" });
+ expect(screen.getByRole("treeitem", { name: "c.txt" })).toHaveFocus();
+ });
+
+ it("closes failed expansions without persisting them and allows retry", async () => {
+ render(<FileExplorer height={300} />, { wrapper });
+ const folder = await screen.findByRole("treeitem", { name: "data" });
+ client.sendListFiles.mockRejectedValueOnce(new Error("Offline"));
+ fireEvent.click(folder);
+ fireEvent.keyDown(folder, { key: "ArrowRight" });
+ await waitFor(() =>
+ expect(folder).toHaveAttribute("aria-expanded", "false"),
+ );
+ expect(
+ store.get(openStateAtom)[fileTreeNodeId("/workspace", "/workspace/data")],
+ ).toBe(false);
+ fireEvent.keyDown(folder, { key: "ArrowRight" });
+ expect(
+ await screen.findByRole("treeitem", { name: "report.csv" }),
+ ).toBeVisible();
+ });
+
+ it("focuses a clicked search result so Enter opens that result", async () => {
+ client.sendSearchFiles.mockResolvedValue({
+ files: [file("report-first.txt"), file("report-second.txt")],
+ query: "report",
+ totalFound: 2,
+ });
+ render(<FileExplorer height={300} />, { wrapper });
+ const input = await screen.findByRole("textbox", {
+ name: "Search files and folders",
+ });
+ input.focus();
+ fireEvent.change(input, { target: { value: "report" } });
+ await screen.findByText("2 matches");
+ fireEvent.click(screen.getByText("report-second.txt"));
+ const second = screen.getByRole("treeitem", {
+ name: "/workspace/report-second.txt",
+ });
+ expect(second).toHaveFocus();
+ fireEvent.keyDown(second, { key: "Enter" });
+ expect(await screen.findByText("Preview: report-second.txt")).toBeVisible();
+ });
+
+ it("passes hidden-file visibility to search and refetches when it changes", async () => {
+ client.sendSearchFiles.mockResolvedValue({
+ files: [],
+ query: "note",
+ totalFound: 0,
+ });
+ render(<FileExplorer height={300} />, { wrapper });
+ const input = await screen.findByRole("textbox", {
+ name: "Search files and folders",
+ });
+ fireEvent.change(input, { target: { value: "note" } });
+ await screen.findByText("No matching files or folders.");
+ expect(client.sendSearchFiles).toHaveBeenLastCalledWith(
+ expect.objectContaining({ includeHidden: true }),
+ );
+ fireEvent.click(screen.getByTestId("file-explorer-hidden-files-button"));
+ await waitFor(() =>
+ expect(client.sendSearchFiles).toHaveBeenLastCalledWith(
+ expect.objectContaining({ includeHidden: false }),
+ ),
+ );
+ });
+
+ it("coalesces superseded searches without overlapping server scans", async () => {
+ const slow = new Deferred<FileSearchResponse>();
+ client.sendSearchFiles
+ .mockReturnValueOnce(slow.promise)
+ .mockResolvedValueOnce({
+ files: [file("notes.txt")],
+ query: "notes",
+ totalFound: 1,
+ });
+ render(<FileExplorer height={300} />, { wrapper });
+ const input = await screen.findByRole("textbox", {
+ name: "Search files and folders",
+ });
+ fireEvent.change(input, { target: { value: "report" } });
+ await waitFor(() => expect(client.sendSearchFiles).toHaveBeenCalledOnce());
+ fireEvent.change(input, { target: { value: "notes" } });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 350));
+ });
+ expect(client.sendSearchFiles).toHaveBeenCalledOnce();
+ fireEvent.change(input, { target: { value: "note" } });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 350));
+ });
+ expect(client.sendSearchFiles).toHaveBeenCalledOnce();
+ await act(async () => {
+ slow.resolve({
+ files: [file("data/report.csv")],
+ query: "report",
+ totalFound: 1,
+ });
+ });
+ await screen.findByText("1 match");
+ expect(client.sendSearchFiles).toHaveBeenCalledTimes(2);
+ expect(client.sendSearchFiles).toHaveBeenLastCalledWith(
+ expect.objectContaining({ query: "note" }),
+ );
+ expect(
+ screen.getByRole("treeitem", { name: "/workspace/notes.txt" }),
+ ).toBeVisible();
+ expect(
+ screen.queryByRole("treeitem", { name: "/workspace/data/report.csv" }),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/components/editor/file-tree/__tests__/file-viewer.test.tsx b/frontend/src/components/editor/file-tree/__tests__/file-viewer.test.tsx
index 42d8a795c6..6bea2c016c 100644
--- a/frontend/src/components/editor/file-tree/__tests__/file-viewer.test.tsx
+++ b/frontend/src/components/editor/file-tree/__tests__/file-viewer.test.tsx
@@ -64,6 +64,33 @@ describe("FileViewer bounded previews", () => {
store.set(requestClientAtom, null);
});
+ it("uses fetched metadata to offer opening a notebook from a search result", async () => {
+ const notebook = {
+ ...file,
+ id: "/workspace/app.py",
+ path: "/workspace/app.py",
+ name: "app.py",
+ };
+ const onOpenNotebook = vi.fn();
+ const client = MockRequestClient.create({
+ sendFileDetails: vi.fn().mockResolvedValue({
+ file: { ...notebook, isMarimoFile: true },
+ contents: "import marimo",
+ mimeType: "text/plain",
+ isBase64: false,
+ isTooLarge: false,
+ }),
+ });
+ store.set(requestClientAtom, client);
+ render(<FileViewer file={notebook} onOpenNotebook={onOpenNotebook} />, {
+ wrapper,
+ });
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Open notebook" }),
+ );
+ expect(onOpenNotebook).toHaveBeenCalledOnce();
+ });
+
it("requests a bounded preview and shows oversized metadata", async () => {
const client = renderViewer({
file,
diff --git a/frontend/src/components/editor/file-tree/__tests__/requesting-tree.test.ts b/frontend/src/components/editor/file-tree/__tests__/requesting-tree.test.ts
index a478861e6d..611574d7a5 100644
--- a/frontend/src/components/editor/file-tree/__tests__/requesting-tree.test.ts
+++ b/frontend/src/components/editor/file-tree/__tests__/requesting-tree.test.ts
@@ -307,6 +307,109 @@ describe("RequestingTree", () => {
expect(sendListFiles).toHaveBeenCalledWith({ path: "/external" });
});
+ test("caches empty directories and shares concurrent expansion requests", async () => {
+ let finish!: (value: { files: never[] }) => void;
+ sendListFiles.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const first = tree.expand(EXTERNAL_ROOT_ID);
+ const second = tree.expand(EXTERNAL_ROOT_ID);
+ expect(sendListFiles).toHaveBeenCalledOnce();
+ finish({ files: [] });
+ expect(await Promise.all([first, second])).toEqual([true, true]);
+ await tree.expand(EXTERNAL_ROOT_ID);
+ expect(sendListFiles).toHaveBeenCalledOnce();
+ });
+
+ test("refreshes a cached ancestor when revealing a newly created folder", async () => {
+ await tree.expand(PRIMARY_ROOT_ID);
+ const newFolder = {
+ ...PRIMARY_FILES[1],
+ id: "/root/new",
+ path: "/root/new",
+ name: "new",
+ };
+ const nested = {
+ ...newFolder,
+ id: "/root/new/nested",
+ path: "/root/new/nested",
+ name: "nested",
+ };
+ sendListFiles.mockImplementation(async ({ path }: { path: string }) => {
+ if (path === "/root") {
+ return { files: [...PRIMARY_FILES, newFolder] };
+ }
+ if (path === "/root/new") {
+ return { files: [nested] };
+ }
+ return { files: [] };
+ });
+ sendListFiles.mockClear();
+ expect(
+ await tree.reveal({
+ ...nested,
+ id: fileTreeNodeId("/root", nested.path),
+ rootPath: "/root",
+ isRoot: false,
+ isPrimaryRoot: true,
+ }),
+ ).toBe(true);
+ expect(sendListFiles.mock.calls).toEqual([
+ [{ path: "/root" }],
+ [{ path: "/root/new" }],
+ [{ path: "/root/new/nested" }],
+ ]);
+ });
+
+ test("reports a search folder that no longer exists after refreshing its parent", async () => {
+ await tree.expand(PRIMARY_ROOT_ID);
+ expect(
+ await tree.reveal({
+ ...PRIMARY_FILES[1],
+ id: fileTreeNodeId("/root", "/root/missing"),
+ path: "/root/missing",
+ rootPath: "/root",
+ isRoot: false,
+ isPrimaryRoot: true,
+ }),
+ ).toBe(false);
+ expect(toast).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Could not reveal folder" }),
+ );
+ });
+
+ test("retries a failed expansion", async () => {
+ sendListFiles.mockRejectedValueOnce(new Error("Offline"));
+ expect(await tree.expand(EXTERNAL_ROOT_ID)).toBe(false);
+ expect(await tree.expand(EXTERNAL_ROOT_ID)).toBe(true);
+ expect(sendListFiles).toHaveBeenCalledTimes(2);
+ });
+
+ test("preserves loaded descendants when refreshing their parent", async () => {
+ await tree.expand(PRIMARY_ROOT_ID);
+ const folderId = fileTreeNodeId("/root", "/root/folder1");
+ await tree.expand(folderId);
+ await tree.refreshPath("/root" as FilePath);
+ sendListFiles.mockClear();
+ await tree.expand(folderId);
+ expect(sendListFiles).not.toHaveBeenCalled();
+ });
+
+ test("reloads a collapsed cached folder after refreshing", async () => {
+ await tree.expand(PRIMARY_ROOT_ID);
+ const folderId = fileTreeNodeId("/root", "/root/folder1");
+ await tree.expand(folderId);
+ await tree.refreshAll([]);
+ sendListFiles.mockClear();
+ await tree.expand(folderId);
+ expect(sendListFiles).toHaveBeenCalledExactlyOnceWith({
+ path: "/root/folder1",
+ });
+ });
+
test("refreshes supplied open folders in addition to configured roots", async () => {
await tree.expand(PRIMARY_ROOT_ID);
sendListFiles.mockClear();
@@ -318,6 +421,33 @@ describe("RequestingTree", () => {
expect(sendListFiles).toHaveBeenCalledWith({ path: "/root/folder1" });
});
+ test("invalidates collapsed copies independently for overlapping roots", async () => {
+ getRoots.mockResolvedValue({
+ roots: [
+ { path: "/root", name: "workspace", isPrimary: true },
+ { path: "/root/folder1", name: "nested root", isPrimary: false },
+ ],
+ });
+ const overlapping = new RequestingTree({
+ getRoots,
+ listFiles: sendListFiles,
+ createFileOrFolder: sendCreateFileOrFolder,
+ deleteFileOrFolder: sendDeleteFileOrFolder,
+ copyFileOrFolder: sendCopyFileOrFolder,
+ renameFileOrFolder: sendRenameFileOrFolder,
+ });
+ await overlapping.initialize(onChange);
+ await overlapping.expand(PRIMARY_ROOT_ID);
+ const collapsedCopy = fileTreeNodeId("/root", "/root/folder1");
+ await overlapping.expand(collapsedCopy);
+ await overlapping.refreshAll([]);
+ sendListFiles.mockClear();
+ await overlapping.expand(collapsedCopy);
+ expect(sendListFiles).toHaveBeenCalledExactlyOnceWith({
+ path: "/root/folder1",
+ });
+ });
+
test("keeps existing children when a refresh fails", async () => {
await tree.expand(PRIMARY_ROOT_ID);
const beforeRefresh = onChange.mock.calls.at(-1)?.[0];
diff --git a/frontend/src/components/editor/file-tree/file-browser-row.tsx b/frontend/src/components/editor/file-tree/file-browser-row.tsx
new file mode 100644
index 0000000000..c24b62c858
--- /dev/null
+++ b/frontend/src/components/editor/file-tree/file-browser-row.tsx
@@ -0,0 +1,82 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { useEffect, useRef } from "react";
+import type { RowRendererProps } from "react-arborist";
+import { useDrop } from "react-dnd";
+import { FileTreeRow } from "./file-tree-row";
+import { useHoverExpand } from "./use-hover-expand";
+import type { FileTreeNode } from "./requesting-tree";
+
+export function FileBrowserRow(props: RowRendererProps<FileTreeNode>) {
+ return props.node.data.isDirectory ? (
+ <FolderDropRow {...props} />
+ ) : (
+ <FileTreeRow {...props} />
+ );
+}
+
+function FolderDropRow(props: RowRendererProps<FileTreeNode>) {
+ const { node } = props;
+ const tree = node.tree;
+ const rowRef = useRef<HTMLDivElement | null>(null);
+ const [{ isHovering }, dropRef] = useDrop(
+ () => ({
+ // Arborist's drag source uses NODE. Keep its validation and move handler,
+ // but treat the entire folder row as a destination, without reorder zones.
+ accept: "NODE",
+ canDrop: () => tree.canDrop(),
+ collect: (monitor) => ({
+ isHovering: monitor.isOver({ shallow: true }) && monitor.canDrop(),
+ }),
+ hover: () => {
+ if (
+ tree.state.dnd.parentId !== node.id ||
+ tree.state.dnd.index !== null
+ ) {
+ tree.dispatch({
+ type: "DND_HOVERING",
+ parentId: node.id,
+ index: null,
+ });
+ }
+ if (!tree.canDrop()) {
+ tree.hideCursor();
+ }
+ },
+ drop: () => {
+ if (!tree.canDrop()) {
+ return;
+ }
+ void tree.props.onMove?.({
+ dragIds: tree.state.dnd.dragIds,
+ dragNodes: tree.dragNodes,
+ parentId: node.id,
+ parentNode: node,
+ index: 0,
+ });
+ tree.open(node.id);
+ },
+ }),
+ [tree, node.id],
+ );
+
+ useHoverExpand(node, isHovering);
+
+ // Replacing innerRef avoids attaching Arborist's positional drop target.
+ // Retain its focus behavior for keyboard navigation and rename completion.
+ useEffect(() => {
+ if (node.isFocused && !node.isEditing) {
+ rowRef.current?.focus({ preventScroll: true });
+ }
+ }, [node.isFocused, node.isEditing]);
+
+ return (
+ <FileTreeRow
+ {...props}
+ innerRef={(element) => {
+ rowRef.current = element;
+ dropRef(element);
+ }}
+ />
+ );
+}
diff --git a/frontend/src/components/editor/file-tree/file-explorer.tsx b/frontend/src/components/editor/file-tree/file-explorer.tsx
index 92dcbb8cb1..123132ca9b 100644
--- a/frontend/src/components/editor/file-tree/file-explorer.tsx
+++ b/frontend/src/components/editor/file-tree/file-explorer.tsx
@@ -16,14 +16,17 @@ import {
PlaySquareIcon,
UploadIcon,
ViewIcon,
+ XIcon,
} from "lucide-react";
import React, { Suspense, use, useRef, useState } from "react";
import {
+ type DragPreviewProps,
type NodeApi,
type NodeRendererProps,
Tree,
type TreeApi,
} from "react-arborist";
+import { createPortal } from "react-dom";
import useEvent from "react-use-event-hook";
import {
FILE_ICON,
@@ -54,6 +57,7 @@ import {
DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { Tooltip } from "@/components/ui/tooltip";
+import { SearchInput } from "@/components/ui/input";
import { toast } from "@/components/ui/use-toast";
import { useCellActions } from "@/core/cells/cells";
import { useLastFocusedCellId } from "@/core/cells/focus";
@@ -61,6 +65,8 @@ import { disableFileDownloadsAtom } from "@/core/config/config";
import { useRequestClient } from "@/core/network/requests";
import { isWasm } from "@/core/wasm/utils";
import { useAsyncData } from "@/hooks/useAsyncData";
+import { useFileSearch } from "./use-file-search";
+import { useHoverExpand } from "./use-hover-expand";
import { ErrorBanner } from "@/plugins/impl/common/error-banner";
import { cn } from "@/utils/cn";
import { copyToClipboard } from "@/utils/copy";
@@ -71,6 +77,8 @@ import { jotaiJsonStorage } from "@/utils/storage/jotai";
import { useTreeDndManager } from "./dnd-wrapper";
import { downloadFile } from "./download";
import { FileViewer } from "./file-viewer";
+import { FileSearchResults } from "./file-search-results";
+import { FileBrowserRow } from "./file-browser-row";
import type { FileTreeNode, RequestingTree } from "./requesting-tree";
import { openStateAtom, treeAtom } from "./state";
import { PYTHON_CODE_FOR_FILE_TYPE } from "./types";
@@ -102,6 +110,10 @@ export const FileExplorer: React.FC<{
externalDropDestinationPath?: FilePath | null;
}> = ({ height, externalDropDestinationPath = null }) => {
const treeRef = useRef<TreeApi<FileTreeNode>>(null);
+ const searchTreeRef = useRef<TreeApi<FileTreeNode>>(null);
+ const searchRef = useRef<HTMLInputElement>(null);
+ const [query, setQuery] = useState("");
+ const [revealId, setRevealId] = useState<string | null>(null);
const dndManager = useTreeDndManager();
const [tree] = useAtom(treeAtom);
const [data, setData] = useState<FileTreeNode[]>([]);
@@ -112,6 +124,7 @@ export const FileExplorer: React.FC<{
} | null>(null);
const [showHiddenFiles, setShowHiddenFiles] =
useAtom<boolean>(hiddenFilesState);
+ const search = useFileSearch({ query: query.trim(), tree, showHiddenFiles });
// Keep external state to remember which folders are open when this
// component is unmounted.
const [openState, setOpenState] = useAtom(openStateAtom);
@@ -135,14 +148,12 @@ export const FileExplorer: React.FC<{
openUploadPicker();
});
- const { openPrompt } = useImperativeModal();
+ const { openPrompt, openConfirm } = useImperativeModal();
const { isPending, error } = useAsyncData(() => tree.initialize(setData), []);
- const handleRefresh = useEvent(() => {
- // Return the promise so callers can await refresh completion
- return tree.refreshAll(
- Object.keys(openState).filter((id) => openState[id]),
- );
+ const handleRefresh = useEvent(async () => {
+ await tree.refreshAll(Object.keys(openState).filter((id) => openState[id]));
+ search.refetch();
});
const handleHiddenFilesToggle = useEvent(() => {
@@ -204,6 +215,77 @@ export const FileExplorer: React.FC<{
[tree, handleUploadFiles, externalDropDestinationPath],
);
+ React.useEffect(() => {
+ if (revealId && !openFile) {
+ const activeTree = query.trim() ? searchTreeRef.current : treeRef.current;
+ activeTree?.openParents(revealId);
+ activeTree?.select(revealId);
+ const node = activeTree?.get(revealId);
+ if (node?.data.isDirectory) {
+ node.open();
+ }
+ setRevealId(null);
+ }
+ }, [revealId, query, openFile, data]);
+
+ const handleReveal = async (node: FileTreeNode) => {
+ if (!node.isDirectory) {
+ setOpenFile(node);
+ return;
+ }
+ if (await tree.reveal(node)) {
+ setQuery("");
+ setRevealId(node.id);
+ }
+ };
+
+ const handleTreeKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
+ if ((event.ctrlKey || event.metaKey) && event.key === "f") {
+ event.preventDefault();
+ event.stopPropagation();
+ searchRef.current?.focus();
+ searchRef.current?.select();
+ return;
+ }
+ if (event.key === "Escape" && query) {
+ event.preventDefault();
+ event.stopPropagation();
+ setQuery("");
+ searchRef.current?.focus();
+ return;
+ }
+ const role =
+ event.target instanceof Element
+ ? event.target.getAttribute("role")
+ : null;
+ if (query.trim() || (role !== "treeitem" && role !== "tree")) {
+ return;
+ }
+ const node = treeRef.current?.focusedNode;
+ if (!node || treeRef.current?.isEditing) {
+ return;
+ }
+ if (event.key === "Enter") {
+ event.preventDefault();
+ event.stopPropagation();
+ if (node.data.isDirectory) {
+ node.toggle();
+ } else {
+ node.activate();
+ }
+ } else if (event.key === "F2" && !node.data.isRoot) {
+ event.preventDefault();
+ event.stopPropagation();
+ node.edit();
+ } else if (event.key === "Delete" || event.key === "Backspace") {
+ event.preventDefault();
+ event.stopPropagation();
+ if (!node.data.isRoot) {
+ void node.tree.delete(node.id);
+ }
+ }
+ };
+
if (isPending) {
return <Spinner size="medium" centered={true} />;
}
@@ -212,128 +294,230 @@ export const FileExplorer: React.FC<{
return <ErrorBanner error={error} />;
}
- if (openFile) {
- return (
- <>
- <div className="flex items-center pl-1 pr-3 shrink-0 border-b justify-between">
- <Button
- onClick={() => setOpenFile(null)}
- data-testid="file-explorer-back-button"
- variant="text"
- size="xs"
- className="mb-0"
- >
- <ArrowLeftIcon size={16} />
- </Button>
- <span className="font-bold">{openFile.name}</span>
- </div>
- <Suspense>
- <FileViewer
- onOpenNotebook={
- tree.isPrimaryNode(openFile)
- ? (evt) => {
- const path = tree.getPrimaryRelativePath(
- openFile.path as FilePath,
- );
- if (path !== null) {
- openMarimoNotebook(evt, path);
- }
+ const preview = openFile ? (
+ <>
+ <div className="flex items-center pl-1 pr-3 shrink-0 border-b justify-between">
+ <Button
+ autoFocus={true}
+ aria-label="Back to files"
+ onClick={() => {
+ setRevealId(openFile.id);
+ setOpenFile(null);
+ }}
+ data-testid="file-explorer-back-button"
+ variant="text"
+ size="xs"
+ className="mb-0"
+ >
+ <ArrowLeftIcon size={16} />
+ </Button>
+ <span className="font-bold">{openFile.name}</span>
+ </div>
+ <Suspense>
+ <FileViewer
+ onOpenNotebook={
+ tree.isPrimaryNode(openFile)
+ ? (evt) => {
+ const path = tree.getPrimaryRelativePath(
+ openFile.path as FilePath,
+ );
+ if (path !== null) {
+ openMarimoNotebook(evt, path);
}
- : undefined
- }
- file={openFile}
- />
- </Suspense>
- </>
- );
- }
+ }
+ : undefined
+ }
+ file={openFile}
+ />
+ </Suspense>
+ </>
+ ) : null;
return (
<>
- <input
- data-testid="file-explorer-upload-input"
- {...getUploadInputProps()}
- />
- <Toolbar
- onRefresh={handleRefresh}
- onHidden={handleHiddenFilesToggle}
- showHiddenFiles={showHiddenFiles}
- onCreateFile={handleCreateFile}
- onCreateNotebook={handleCreateNotebook}
- onCreateFolder={handleCreateFolder}
- onCollapseAll={handleCollapseAll}
- uploadDestinationPath={
- selectedFolder?.path ?? tree.getPrimaryRootPath()
- }
- uploadDestinationLabel={getUploadDestinationLabel(
- tree,
- selectedFolder?.path ?? tree.getPrimaryRootPath(),
- )}
- onUpload={handleUploadFiles}
- />
- <RequestingTreeContext value={contextValue}>
- <Tree<FileTreeNode>
- width="100%"
- ref={treeRef}
- height={height - 33}
- className="h-full"
- data={visibleData}
- initialOpenState={openState}
- openByDefault={false}
- // Use shared DnD manager to prevent "Cannot have two HTML5 backends" error
- dndManager={dndManager}
- // Hide the drop cursor
- renderCursor={() => null}
- // Disable dropping files into files
- disableDrag={(node) => node.isRoot}
- disableDrop={({ parentNode, dragNodes }) =>
- dragNodes.some((node) => node.data.isRoot) ||
- (parentNode ? !parentNode.data.isDirectory : false)
- }
- onDelete={async ({ ids }) => {
- for (const id of ids) {
- await tree.delete(id);
+ {preview}
+ <div hidden={!!openFile} onKeyDownCapture={handleTreeKeyDown}>
+ <input
+ data-testid="file-explorer-upload-input"
+ {...getUploadInputProps()}
+ />
+ <div>
+ <Toolbar
+ onRefresh={handleRefresh}
+ onHidden={handleHiddenFilesToggle}
+ showHiddenFiles={showHiddenFiles}
+ onCreateFile={handleCreateFile}
+ onCreateNotebook={handleCreateNotebook}
+ onCreateFolder={handleCreateFolder}
+ onCollapseAll={handleCollapseAll}
+ uploadDestinationPath={
+ selectedFolder?.path ?? tree.getPrimaryRootPath()
}
- }}
- onRename={async ({ id, name }) => {
- await tree.rename(id, name);
- }}
- onMove={async ({ dragIds, parentId }) => {
- await tree.move(dragIds, parentId);
- }}
- onSelect={(nodes) => {
- const first = nodes[0];
- if (!first) {
- setSelectedFolder(null);
- return;
- }
- if (first.data.isDirectory) {
- setSelectedFolder({
- id: first.id,
- path: first.data.path as FilePath,
- });
- return;
- }
- setSelectedFolder(null);
- setOpenFile(first.data);
- }}
- onToggle={async (id) => {
- const result = await tree.expand(id);
- if (result) {
- const prevOpen = openState[id] ?? false;
- setOpenState({ ...openState, [id]: !prevOpen });
- }
- }}
- padding={15}
- rowHeight={30}
- indent={INDENT_STEP}
- overscanCount={1000}
- // Disable multi-selection
- disableMultiSelection={true}
- >
- {Node}
- </Tree>
- </RequestingTreeContext>
+ uploadDestinationLabel={getUploadDestinationLabel(
+ tree,
+ selectedFolder?.path ?? tree.getPrimaryRootPath(),
+ )}
+ onUpload={handleUploadFiles}
+ />
+ <div className="relative -mt-1">
+ <SearchInput
+ ref={searchRef}
+ className="rounded-none pr-6 focus-visible:outline-1 focus-visible:outline-ring/50"
+ clearable={false}
+ aria-label="Search files and folders"
+ placeholder="Search"
+ title="Search names in all configured roots, up to 20 folders deep. Generated directories such as node_modules and .git are excluded."
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ onKeyDown={(event) => {
+ const activeTree = query.trim()
+ ? searchTreeRef.current
+ : treeRef.current;
+ if (event.key === "ArrowDown") {
+ event.preventDefault();
+ activeTree?.focus(activeTree.firstNode);
+ } else if (event.key === "Enter" && query.trim()) {
+ event.preventDefault();
+ activeTree?.firstNode?.activate();
+ }
+ }}
+ />
+ {query && (
+ <Button
+ variant="text"
+ size="icon"
+ className="absolute right-3 top-1/2 h-5 w-5 -translate-y-1/2"
+ aria-label="Clear search"
+ onClick={() => {
+ setQuery("");
+ searchRef.current?.focus();
+ }}
+ >
+ <XIcon className="h-3 w-3" />
+ </Button>
+ )}
+ </div>
+ </div>
+ <div hidden={!query.trim()}>
+ <FileSearchResults
+ treeRef={searchTreeRef}
+ search={search}
+ height={Math.max(0, height - 63)}
+ onReveal={handleReveal}
+ />
+ </div>
+ <div hidden={!!query.trim()} className="relative">
+ <RequestingTreeContext value={contextValue}>
+ <Tree<FileTreeNode>
+ width="100%"
+ ref={treeRef}
+ height={Math.max(0, height - 63)}
+ className="h-full"
+ data={visibleData}
+ childrenAccessor={(node) =>
+ node.isDirectory ? node.children : null
+ }
+ selectionFollowsFocus={true}
+ rowClassName="outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring"
+ renderRow={FileBrowserRow}
+ renderDragPreview={(props) => (
+ <FileDragPreview {...props} tree={treeRef.current} />
+ )}
+ disableEdit={(node) => node.isRoot}
+ initialOpenState={openState}
+ openByDefault={false}
+ // Use shared DnD manager to prevent "Cannot have two HTML5 backends" error
+ dndManager={dndManager}
+ // Hide the drop cursor
+ renderCursor={() => null}
+ // Disable dropping files into files
+ disableDrag={(node) => node.isRoot}
+ disableDrop={({ parentNode, dragNodes }) =>
+ dragNodes.some((node) => node.data.isRoot) ||
+ (parentNode ? !parentNode.data.isDirectory : false)
+ }
+ onDelete={async ({ ids }) => {
+ openConfirm({
+ title: "Delete file",
+ description:
+ "Are you sure you want to delete the selected file or folder?",
+ confirmAction: (
+ <AlertDialogDestructiveAction
+ onClick={async () => {
+ for (const id of ids) {
+ await tree.delete(id);
+ }
+ }}
+ >
+ Delete
+ </AlertDialogDestructiveAction>
+ ),
+ });
+ }}
+ onRename={async ({ id, name }) => {
+ await tree.rename(id, name);
+ }}
+ onMove={async ({ dragIds, parentId }) => {
+ await tree.move(dragIds, parentId);
+ }}
+ onSelect={(nodes) => {
+ const first = nodes[0];
+ if (!first) {
+ setSelectedFolder(null);
+ return;
+ }
+ if (first.data.isDirectory) {
+ setSelectedFolder({
+ id: first.id,
+ path: first.data.path as FilePath,
+ });
+ return;
+ }
+ setSelectedFolder(null);
+ }}
+ onActivate={(node) => {
+ if (!node.data.isDirectory) {
+ setOpenFile(node.data);
+ }
+ }}
+ onToggle={async (id) => {
+ const isOpen =
+ treeRef.current?.isOpen(id) ?? !(openState[id] ?? false);
+ if (!isOpen) {
+ setOpenState((previous) => ({ ...previous, [id]: false }));
+ return;
+ }
+ const loaded = await tree.expand(id);
+ if (!loaded) {
+ treeRef.current?.close(id);
+ }
+ const remainsOpen =
+ loaded && (treeRef.current?.isOpen(id) ?? false);
+ setOpenState((previous) => ({
+ ...previous,
+ [id]: remainsOpen,
+ }));
+ }}
+ padding={15}
+ rowHeight={30}
+ indent={INDENT_STEP}
+ overscanCount={8}
+ // Disable multi-selection
+ disableMultiSelection={true}
+ >
+ {Node}
+ </Tree>
+ </RequestingTreeContext>
+ {!visibleData.length && (
+ <p
+ role="status"
+ className="absolute top-2 left-3 text-sm text-muted-foreground"
+ >
+ No visible files.
+ </p>
+ )}
+ </div>
+ </div>
</>
);
};
@@ -368,7 +552,7 @@ const Toolbar = ({
const uploadLabel = `Upload files to ${uploadDestinationLabel}`;
return (
- <div className="flex items-center justify-end px-2 shrink-0 border-b">
+ <div className="flex items-center justify-end px-2 shrink-0">
<Tooltip content="Add notebook">
<Button
data-testid="file-explorer-add-notebook-button"
@@ -445,16 +629,7 @@ const Show = ({
) => void;
}) => {
const label = (
- <span
- className="flex-1 overflow-hidden text-ellipsis"
- onClick={(e) => {
- if (node.data.isDirectory) {
- return;
- }
- e.stopPropagation();
- node.select();
- }}
- >
+ <span className="flex-1 overflow-hidden text-ellipsis">
{node.data.name}
{node.data.isMarimoFile && node.data.isPrimaryRoot && !isWasm() && (
<span
@@ -484,7 +659,7 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileTreeNode>) => {
: guessFileIconType(node.data.name);
const Icon = FILE_ICON[fileType];
- const { openConfirm, openPrompt } = useImperativeModal();
+ const { openPrompt } = useImperativeModal();
const { createNewCell } = useCellActions();
const lastFocusedCellId = useLastFocusedCellId();
@@ -501,6 +676,7 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileTreeNode>) => {
const isExternalDropTarget =
node.data.isDirectory &&
fileExplorer?.externalDropDestinationPath === node.data.path;
+ useHoverExpand(node, isExternalDropTarget);
const handleOpenMarimoFile = async (
evt: Pick<Event, "stopPropagation" | "preventDefault">,
@@ -514,20 +690,7 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileTreeNode>) => {
const handleDeleteFile = async (evt: Event) => {
evt.stopPropagation();
evt.preventDefault();
- openConfirm({
- title: "Delete file",
- description: `Are you sure you want to delete ${node.data.name}?`,
- confirmAction: (
- <AlertDialogDestructiveAction
- onClick={async () => {
- await node.tree.delete(node.id);
- }}
- aria-label="Confirm"
- >
- Delete
- </AlertDialogDestructiveAction>
- ),
- });
+ await node.tree.delete(node.id);
};
const handleCreateFolder = useEvent(async () => {
@@ -576,40 +739,53 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileTreeNode>) => {
? { [FILE_EXPLORER_DIRECTORY_PATH_ATTRIBUTE]: node.data.path }
: {})}
className={cn(
- "flex items-center cursor-pointer ml-1 text-muted-foreground whitespace-nowrap group",
+ "relative flex h-full items-center cursor-pointer ml-1 text-muted-foreground whitespace-nowrap group",
)}
draggable={!node.data.isRoot}
- onClick={(evt) => {
- evt.stopPropagation();
+ onClick={() => {
if (node.data.isDirectory) {
- node.select();
node.toggle();
}
}}
+ onDoubleClick={(event) => {
+ event.stopPropagation();
+ if (!node.data.isDirectory) {
+ node.activate();
+ }
+ }}
>
+ {Array.from({ length: node.level }, (_, level) => (
+ <span
+ key={level}
+ aria-hidden="true"
+ className="pointer-events-none absolute inset-y-0 border-l border-border"
+ style={{ left: level * INDENT_STEP + 8 }}
+ />
+ ))}
<FolderArrow node={node} />
<span
className={cn(
"flex items-center pl-1 py-1 cursor-pointer hover:bg-accent/50 hover:text-accent-foreground rounded-l flex-1 overflow-hidden group",
node.willReceiveDrop &&
+ node.tree.canDrop() &&
node.data.isDirectory &&
- "bg-accent/80 hover:bg-accent/80 text-accent-foreground",
+ "bg-primary/15 hover:bg-primary/15 text-accent-foreground",
node.isSelected &&
"bg-accent/60 hover:bg-accent/60 text-accent-foreground",
isExternalDropTarget &&
- "bg-primary/15 hover:bg-primary/15 text-accent-foreground ring-1 ring-inset ring-primary",
+ "bg-primary/15 hover:bg-primary/15 text-accent-foreground",
)}
>
{node.data.isRoot ? (
<FolderRootIcon
- className="w-5 h-5 shrink-0 mr-2 text-primary"
+ className="w-4 h-4 shrink-0 mr-2 text-primary"
strokeWidth={1.5}
/>
) : node.data.isMarimoFile ? (
- <MarimoIcon className="w-5 h-5 shrink-0 mr-2" strokeWidth={1.5} />
+ <MarimoIcon className="w-4 h-4 shrink-0 mr-2" strokeWidth={1.5} />
) : (
<Icon
- className={cn("w-5 h-5 shrink-0 mr-2", FILE_ICON_COLOR[fileType])}
+ className={cn("w-4 h-4 shrink-0 mr-2", FILE_ICON_COLOR[fileType])}
strokeWidth={1.5}
/>
)}
@@ -624,7 +800,7 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileTreeNode>) => {
>
{!node.data.isDirectory && (
<DropdownMenuItem
- onSelect={() => node.select()}
+ onSelect={() => node.activate()}
data-testid="file-explorer-open-file-menu-item"
>
<ViewIcon className={MENU_ITEM_ICON_CLASS} />
@@ -794,6 +970,18 @@ const FolderArrow = ({ node }: { node: NodeApi<FileTreeNode> }) => {
return <span className="w-4 h-4 shrink-0" />;
}
+ if (node.data.loadState === "loading") {
+ return (
+ <span
+ role="status"
+ aria-label={`Loading ${node.data.name}`}
+ className="w-4 h-4 shrink-0"
+ >
+ <Spinner size="small" />
+ </span>
+ );
+ }
+
return <TreeChevron isExpanded={node.isOpen} className="w-4 h-4" />;
};
@@ -852,3 +1040,33 @@ function treeContainsId(list: FileTreeNode[], id: string): boolean {
(item.children ? treeContainsId(item.children, id) : false),
);
}
+
+function FileDragPreview({
+ mouse,
+ id,
+ isDragging,
+ tree,
+}: DragPreviewProps & { tree: TreeApi<FileTreeNode> | null }) {
+ const node = tree?.get(id);
+ if (!isDragging || !mouse || !node) {
+ return null;
+ }
+ const fileType = node.data.isDirectory
+ ? "directory"
+ : guessFileIconType(node.data.name);
+ const Icon = FILE_ICON[fileType];
+ return createPortal(
+ <div
+ className="pointer-events-none fixed left-0 top-0 z-[1000] opacity-[0.85]"
+ style={{
+ transform: `translate3d(${mouse.x + 12}px, ${mouse.y + 12}px, 0)`,
+ }}
+ >
+ <div className="flex max-w-72 items-center gap-2 rounded-md border border-border bg-popover px-3 py-2 text-sm text-popover-foreground shadow-md">
+ <Icon className={cn("h-4 w-4 shrink-0", FILE_ICON_COLOR[fileType])} />
+ <span className="truncate">{node.data.name}</span>
+ </div>
+ </div>,
+ document.body,
+ );
+}
diff --git a/frontend/src/components/editor/file-tree/file-operations.tsx b/frontend/src/components/editor/file-tree/file-operations.tsx
index ab9292aa8f..4667c73c5a 100644
--- a/frontend/src/components/editor/file-tree/file-operations.tsx
+++ b/frontend/src/components/editor/file-tree/file-operations.tsx
@@ -206,7 +206,7 @@ export const FileActionsDropdown = ({
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
- className={contentClassName ?? "print:hidden w-[220px]"}
+ className={contentClassName ?? "print:hidden w-[240px]"}
onClick={(e) => e.stopPropagation()}
onCloseAutoFocus={(e) => e.preventDefault()}
>
diff --git a/frontend/src/components/editor/file-tree/file-search-results.tsx b/frontend/src/components/editor/file-tree/file-search-results.tsx
new file mode 100644
index 0000000000..dc317a1013
--- /dev/null
+++ b/frontend/src/components/editor/file-tree/file-search-results.tsx
@@ -0,0 +1,142 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { FileIcon, FolderIcon } from "lucide-react";
+import type { RefObject } from "react";
+import {
+ Tree,
+ type NodeRendererProps,
+ type RowRendererProps,
+ type TreeApi,
+} from "react-arborist";
+import { Spinner } from "@/components/icons/spinner";
+import { cn } from "@/utils/cn";
+import { useTreeDndManager } from "./dnd-wrapper";
+import { FileTreeRow } from "./file-tree-row";
+import type { FileTreeNode } from "./requesting-tree";
+import type { useFileSearch } from "./use-file-search";
+
+export function FileSearchResults({
+ treeRef,
+ search,
+ height,
+ onReveal,
+}: {
+ treeRef: RefObject<TreeApi<FileTreeNode> | null>;
+ search: ReturnType<typeof useFileSearch>;
+ height: number;
+ onReveal: (node: FileTreeNode) => Promise<void>;
+}) {
+ const dndManager = useTreeDndManager();
+ const { state, refetch } = search;
+ if (state.status === "idle") {
+ return null;
+ }
+
+ if (state.status === "error") {
+ return (
+ <div role="alert" className="px-3 py-2 text-sm">
+ Could not search files.{" "}
+ <button type="button" className="underline" onClick={refetch}>
+ Retry
+ </button>
+ </div>
+ );
+ }
+ if (state.status === "loading") {
+ return (
+ <div
+ role="status"
+ className="flex items-center gap-2 px-3 py-2 text-sm text-muted-foreground"
+ >
+ <Spinner size="small" />
+ Searching files…
+ </div>
+ );
+ }
+ const { files, hasMore, isPartial } = state;
+ const count = files.length;
+ return (
+ <div
+ onKeyDownCapture={(event) => {
+ if (
+ event.key === "Enter" &&
+ event.target instanceof HTMLElement &&
+ event.target.closest('[role="tree"]')
+ ) {
+ event.preventDefault();
+ event.stopPropagation();
+ treeRef.current?.focusedNode?.activate();
+ }
+ }}
+ >
+ {isPartial && (
+ <div role="alert" className="px-3 py-2 text-xs text-muted-foreground">
+ Some locations could not be searched.{" "}
+ <button type="button" className="underline" onClick={refetch}>
+ Retry
+ </button>
+ </div>
+ )}
+ <p role="status" className="px-3 py-2 text-xs text-muted-foreground">
+ {files.length
+ ? `${count} ${count === 1 ? "match" : "matches"}`
+ : "No matching files or folders."}
+ {hasMore && " · Refine your search for more results."}
+ </p>
+ <Tree<FileTreeNode>
+ ref={treeRef}
+ data={files}
+ childrenAccessor={() => null}
+ width="100%"
+ height={Math.max(0, height - 48 - (isPartial ? 48 : 0))}
+ rowHeight={48}
+ overscanCount={8}
+ dndManager={dndManager}
+ disableDrag={true}
+ disableDrop={true}
+ disableEdit={true}
+ disableMultiSelection={true}
+ selectionFollowsFocus={true}
+ rowClassName="outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring"
+ renderRow={SearchResultRow}
+ onActivate={(node) => {
+ void onReveal(node.data);
+ }}
+ >
+ {SearchResult}
+ </Tree>
+ <p className="px-3 text-xs text-muted-foreground">
+ Enter or double-click to open · Esc to clear
+ </p>
+ </div>
+ );
+}
+
+function SearchResultRow(props: RowRendererProps<FileTreeNode>) {
+ return <FileTreeRow {...props} ariaLabel={props.node.data.path} />;
+}
+
+function SearchResult({ node }: NodeRendererProps<FileTreeNode>) {
+ const Icon = node.data.isDirectory ? FolderIcon : FileIcon;
+ return (
+ <div
+ className={cn(
+ "flex h-full items-start gap-2.5 px-3 py-1 cursor-pointer hover:bg-accent/50",
+ node.isSelected && "bg-accent/60",
+ )}
+ onDoubleClick={(event) => {
+ event.stopPropagation();
+ node.activate();
+ }}
+ title={node.data.path}
+ >
+ <Icon className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <div className="truncate text-sm leading-5">{node.data.name}</div>
+ <div className="truncate text-xs leading-4 text-muted-foreground">
+ {node.data.path}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/components/editor/file-tree/file-tree-row.tsx b/frontend/src/components/editor/file-tree/file-tree-row.tsx
new file mode 100644
index 0000000000..b43c654a4f
--- /dev/null
+++ b/frontend/src/components/editor/file-tree/file-tree-row.tsx
@@ -0,0 +1,40 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type { RowRendererProps } from "react-arborist";
+import type { FileTreeNode } from "./requesting-tree";
+
+export function FileTreeRow({
+ node,
+ attrs,
+ innerRef,
+ children,
+ ariaLabel = node.data.name,
+}: RowRendererProps<FileTreeNode> & { ariaLabel?: string }) {
+ return (
+ <div
+ {...attrs}
+ ref={innerRef}
+ aria-label={ariaLabel}
+ aria-expanded={node.isInternal ? node.isOpen : undefined}
+ onFocus={(event) => {
+ event.stopPropagation();
+ attrs.onFocus?.(event);
+ if (event.target === event.currentTarget && !node.isFocused) {
+ node.focus();
+ }
+ }}
+ onClick={(event) => {
+ if (attrs.onClick) {
+ attrs.onClick(event);
+ } else {
+ node.select();
+ }
+ if (!event.defaultPrevented) {
+ event.currentTarget.focus({ preventScroll: true });
+ }
+ }}
+ >
+ {children}
+ </div>
+ );
+}
diff --git a/frontend/src/components/editor/file-tree/file-viewer.tsx b/frontend/src/components/editor/file-tree/file-viewer.tsx
index 40e72e8028..eeb2eb1055 100644
--- a/frontend/src/components/editor/file-tree/file-viewer.tsx
+++ b/frontend/src/components/editor/file-tree/file-viewer.tsx
@@ -156,11 +156,12 @@ export const FileViewer: React.FC<Props> = ({ file, onOpenNotebook }) => {
onDownload={disableFileDownloads ? undefined : handleDownload}
actions={
<>
- {file.isMarimoFile && onOpenNotebook && !isWasm() && (
+ {data.file.isMarimoFile && onOpenNotebook && !isWasm() && (
<Tooltip content="Open notebook">
<Button
variant="text"
size="xs"
+ aria-label="Open notebook"
onClick={(evt) => onOpenNotebook(evt)}
>
<ExternalLinkIcon className="h-3.5 w-3.5" />
diff --git a/frontend/src/components/editor/file-tree/requesting-tree.tsx b/frontend/src/components/editor/file-tree/requesting-tree.tsx
index 6e75e89169..3d53062ebb 100644
--- a/frontend/src/components/editor/file-tree/requesting-tree.tsx
+++ b/frontend/src/components/editor/file-tree/requesting-tree.tsx
@@ -22,6 +22,7 @@ export type FileTreeNode = Omit<FileInfo, "children"> & {
isRoot: boolean;
rootPath: string;
isPrimaryRoot: boolean;
+ loadState?: "unloaded" | "loading" | "loaded" | "error";
};
/**
@@ -66,6 +67,7 @@ export class RequestingTree {
}
private roots: FileRoot[] = [];
+ private pendingExpansions = new Map<string, Promise<boolean>>();
private onChange: (data: FileTreeNode[]) => void = Functions.NOOP;
private path = new PathBuilder("/");
@@ -87,12 +89,7 @@ export class RequestingTree {
const data = await this.callbacks.listFiles({
path: primaryRoot.path,
});
- this.delegate.update({
- id: this.getPrimaryRootId(),
- changes: {
- children: annotateFiles(data.files, primaryRoot),
- },
- });
+ this.updateDirectory(this.getPrimaryRootId(), data.files);
}
} catch (error) {
toast({
@@ -105,24 +102,91 @@ export class RequestingTree {
this.emitChange();
};
- async expand(id: string): Promise<boolean> {
+ expand(id: string): Promise<boolean> {
+ return this.requestDirectory(id);
+ }
+
+ private requestDirectory(id: string, force = false): Promise<boolean> {
+ const pending = this.pendingExpansions.get(id);
+ if (pending) {
+ return pending;
+ }
const node = this.delegate.find(id);
if (!node?.data.isDirectory) {
- return false;
+ return Promise.resolve(false);
}
- if (node.children && node.children.length > 0) {
- return true;
+ if (!force && node.data.loadState === "loaded") {
+ return Promise.resolve(true);
}
- const data = await this.callbacks.listFiles({ path: node.data.path });
- this.delegate.update({
- id,
- changes: {
- children: annotateFiles(data.files, this.getRootForNode(node.data)),
- },
+ const request = this.loadDirectory(id, node.data).finally(() => {
+ this.pendingExpansions.delete(id);
});
+ this.pendingExpansions.set(id, request);
+ return request;
+ }
+
+ private async loadDirectory(
+ id: string,
+ node: FileTreeNode,
+ ): Promise<boolean> {
+ this.delegate.update({ id, changes: { loadState: "loading" } });
this.emitChange();
+ try {
+ const data = await this.callbacks.listFiles({ path: node.path });
+ this.updateDirectory(id, data.files);
+ return true;
+ } catch (error) {
+ this.delegate.update({ id, changes: { loadState: "error" } });
+ toast({
+ title: `Could not load ${node.name}`,
+ description: prettyError(error),
+ });
+ return false;
+ } finally {
+ this.emitChange();
+ }
+ }
+
+ getRoots(): readonly FileRoot[] {
+ return this.roots;
+ }
+
+ async reveal(node: FileTreeNode): Promise<boolean> {
+ const relative = relativePath(node.path as FilePath, node.rootPath);
+ if (relative === null) {
+ return false;
+ }
+ let path = node.rootPath as FilePath;
+ const parts = relative.split(pathDelimiter(node.rootPath)).filter(Boolean);
+ if (!node.isDirectory) {
+ parts.pop();
+ }
+ for (const part of [null, ...parts]) {
+ if (part !== null) {
+ const parentId = fileTreeNodeId(node.rootPath, path);
+ path = joinPath(path, part);
+ // Search sees the live filesystem; a cached parent may not contain
+ // a directory that was created since its last listing.
+ if (!this.delegate.find(fileTreeNodeId(node.rootPath, path))) {
+ if (!(await this.requestDirectory(parentId, true))) {
+ return false;
+ }
+ }
+ }
+ const id = fileTreeNodeId(node.rootPath, path);
+ if (!this.delegate.find(id)) {
+ toast({
+ title: "Could not reveal folder",
+ description: `The folder may have moved or been deleted: ${path}`,
+ });
+ return false;
+ }
+ if (!(await this.expand(id))) {
+ return false;
+ }
+ }
return true;
}
@@ -252,7 +316,13 @@ export class RequestingTree {
.map((id) => this.delegate.find(id)?.data.path)
.filter((path): path is string => Boolean(path)),
];
- await this.refreshPaths(paths);
+ await this.refreshPaths(
+ paths,
+ new Set([
+ ...this.roots.map((root) => fileTreeNodeId(root.path, root.path)),
+ ...ids,
+ ]),
+ );
};
refreshPath = async (path: FilePath): Promise<void> => {
@@ -344,8 +414,13 @@ export class RequestingTree {
return node;
}
- private refreshPaths = async (paths: string[]): Promise<void> => {
- const uniquePaths = [...new Set(paths)];
+ private refreshPaths = async (
+ paths: string[],
+ retainedIds?: ReadonlySet<string>,
+ ): Promise<void> => {
+ const uniquePaths = [...new Set(paths)].toSorted(
+ (left, right) => left.length - right.length,
+ );
if (uniquePaths.length === 0) {
return;
}
@@ -360,31 +435,84 @@ export class RequestingTree {
if (!result) {
continue;
}
- // The same absolute path may appear below multiple overlapping roots.
- // Refresh every occurrence, while keeping each occurrence in its own ID
- // namespace and preserving its root metadata.
+ // Fetch overlapping paths once, but retain loaded folders independently
+ // for each root-qualified occurrence.
for (const root of this.roots) {
- const node = this.delegate.find(fileTreeNodeId(root.path, path));
- if (!node?.data.isDirectory) {
- continue;
+ const id = fileTreeNodeId(root.path, path);
+ if (!retainedIds || retainedIds.has(id)) {
+ this.updateDirectory(id, result.files, retainedIds);
}
- this.delegate.update({
- id: node.id,
- changes: {
- children: annotateFiles(result.files, root),
- },
- });
}
}
this.emitChange();
};
+ private updateDirectory(
+ id: string,
+ files: FileInfo[],
+ retainedIds?: ReadonlySet<string>,
+ ): void {
+ const node = this.delegate.find(id)?.data;
+ if (!node?.isDirectory) {
+ return;
+ }
+ const children = mergeDirectoryChildren(
+ annotateFiles(files, this.getRootForNode(node)),
+ node.children,
+ );
+ this.delegate.update({
+ id,
+ changes: {
+ children: retainedIds
+ ? invalidateClosedDirectories(children, retainedIds)
+ : children,
+ loadState: "loaded",
+ },
+ });
+ }
+
private emitChange(): void {
const data = this.delegate.data;
- this.onChange(this.roots.length === 1 ? (data[0]?.children ?? []) : data);
+ // SimpleTree mutates child arrays in place. Publish a new array so React
+ // observes completed directory loads even when the root is flattened.
+ this.onChange(
+ this.roots.length === 1 ? [...(data[0]?.children ?? [])] : data,
+ );
}
}
+function mergeDirectoryChildren(
+ files: FileTreeNode[],
+ previous: FileTreeNode[],
+): FileTreeNode[] {
+ const byId = new Map(previous.map((node) => [node.id, node]));
+ return files.map((file) => {
+ const old = byId.get(file.id);
+ if (!file.isDirectory || !old?.isDirectory) {
+ return file;
+ }
+ return { ...file, children: old.children, loadState: old.loadState };
+ });
+}
+
+function invalidateClosedDirectories(
+ files: FileTreeNode[],
+ openIds: ReadonlySet<string>,
+): FileTreeNode[] {
+ return files.map((file) => {
+ if (!file.isDirectory) {
+ return file;
+ }
+ if (!openIds.has(file.id)) {
+ return { ...file, children: [], loadState: "unloaded" };
+ }
+ return {
+ ...file,
+ children: invalidateClosedDirectories(file.children, openIds),
+ };
+ });
+}
+
function toRootNode(root: FileRoot): FileTreeNode {
return {
id: fileTreeNodeId(root.path, root.path),
@@ -396,6 +524,7 @@ function toRootNode(root: FileRoot): FileTreeNode {
isRoot: true,
rootPath: root.path,
isPrimaryRoot: root.isPrimary,
+ loadState: "unloaded",
};
}
@@ -404,6 +533,7 @@ function annotateFiles(files: FileInfo[], root: FileRoot): FileTreeNode[] {
...file,
id: fileTreeNodeId(root.path, file.path),
children: annotateFiles(file.children ?? [], root),
+ loadState: file.children?.length ? "loaded" : "unloaded",
isRoot: false,
rootPath: root.path,
isPrimaryRoot: root.isPrimary,
diff --git a/frontend/src/components/editor/file-tree/use-file-search.ts b/frontend/src/components/editor/file-tree/use-file-search.ts
new file mode 100644
index 0000000000..2b8954640a
--- /dev/null
+++ b/frontend/src/components/editor/file-tree/use-file-search.ts
@@ -0,0 +1,142 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useRequestClient } from "@/core/network/requests";
+import { useDebounce } from "@/hooks/useDebounce";
+import {
+ fileTreeNodeId,
+ type FileTreeNode,
+ type RequestingTree,
+} from "./requesting-tree";
+
+const RESULT_LIMIT = 200;
+
+export type FileSearchState =
+ | { status: "idle" }
+ | { status: "loading"; query: string }
+ | { status: "error"; query: string; error: unknown }
+ | {
+ status: "success";
+ query: string;
+ files: FileTreeNode[];
+ hasMore: boolean;
+ isPartial: boolean;
+ };
+
+export function useFileSearch({
+ query,
+ tree,
+ showHiddenFiles,
+}: {
+ query: string;
+ tree: RequestingTree;
+ showHiddenFiles: boolean;
+}): { state: FileSearchState; refetch: () => void } {
+ const { sendSearchFiles } = useRequestClient();
+ const debouncedQuery = useDebounce(query, 300);
+ const pending = useRef<Promise<void>>(Promise.resolve());
+ const [revision, setRevision] = useState(0);
+ const refetch = useCallback(() => setRevision((value) => value + 1), []);
+ const [result, setResult] = useState<FileSearchState>({ status: "idle" });
+
+ useEffect(() => {
+ let cancelled = false;
+ if (!query || query !== debouncedQuery) {
+ return;
+ }
+ setResult({ status: "loading", query });
+ // Let the in-flight server scan finish before starting another. Superseded
+ // queued queries and remaining roots are skipped, keeping scan work bounded.
+ const request = pending.current.then(async () => {
+ const filesByPath = new Map<string, FileTreeNode>();
+ let rootLimitReached = false;
+ let failedRootCount = 0;
+ const roots = tree.getRoots();
+ for (const root of roots) {
+ if (cancelled) {
+ return;
+ }
+ try {
+ const response = await sendSearchFiles({
+ query,
+ path: root.path,
+ includeFiles: true,
+ includeDirectories: true,
+ includeHidden: showHiddenFiles,
+ depth: 20,
+ limit: RESULT_LIMIT,
+ });
+ rootLimitReached ||= response.files.length >= RESULT_LIMIT;
+ for (const file of response.files) {
+ const existing = filesByPath.get(file.path);
+ if (existing && (!root.isPrimary || existing.isPrimaryRoot)) {
+ continue;
+ }
+ filesByPath.set(file.path, {
+ ...file,
+ id: fileTreeNodeId(root.path, file.path),
+ children: [],
+ isRoot: false,
+ rootPath: root.path,
+ isPrimaryRoot: root.isPrimary,
+ });
+ }
+ } catch {
+ failedRootCount += 1;
+ }
+ }
+ if (!cancelled) {
+ if (roots.length > 0 && failedRootCount === roots.length) {
+ setResult({
+ status: "error",
+ query,
+ error: new Error("Could not search any root"),
+ });
+ return;
+ }
+ const rank = (file: FileTreeNode) => {
+ const name = file.name.toLowerCase();
+ const needle = query.toLowerCase();
+ if (name === needle) {
+ return 0;
+ }
+ if (name.startsWith(needle)) {
+ return 1;
+ }
+ return 2;
+ };
+ const sortedFiles = [...filesByPath.values()].toSorted(
+ (left, right) =>
+ rank(left) - rank(right) || left.name.localeCompare(right.name),
+ );
+ setResult({
+ status: "success",
+ isPartial: failedRootCount > 0,
+ query,
+ files: sortedFiles.slice(0, RESULT_LIMIT),
+ hasMore: rootLimitReached || sortedFiles.length > RESULT_LIMIT,
+ });
+ }
+ });
+ pending.current = request.catch((error: unknown) => {
+ if (!cancelled) {
+ setResult({ status: "error", query, error });
+ }
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [query, debouncedQuery, tree, showHiddenFiles, revision, sendSearchFiles]);
+
+ if (!query) {
+ return { state: { status: "idle" }, refetch };
+ }
+ if (
+ query !== debouncedQuery ||
+ result.status === "idle" ||
+ result.query !== query
+ ) {
+ return { state: { status: "loading", query }, refetch };
+ }
+ return { state: result, refetch };
+}
diff --git a/frontend/src/components/editor/file-tree/use-hover-expand.ts b/frontend/src/components/editor/file-tree/use-hover-expand.ts
new file mode 100644
index 0000000000..4da01b91d2
--- /dev/null
+++ b/frontend/src/components/editor/file-tree/use-hover-expand.ts
@@ -0,0 +1,34 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { useEffect, useRef } from "react";
+import type { NodeApi } from "react-arborist";
+import type { FileTreeNode } from "./requesting-tree";
+
+export const HOVER_EXPAND_DELAY = 600;
+
+export function useHoverExpand(
+ node: NodeApi<FileTreeNode>,
+ isHovering: boolean,
+) {
+ const tree = node.tree;
+ const attemptedNode = useRef<string | null>(null);
+ useEffect(() => {
+ if (!isHovering) {
+ attemptedNode.current = null;
+ return;
+ }
+ if (
+ !node.data.isDirectory ||
+ node.isOpen ||
+ attemptedNode.current === node.id
+ ) {
+ return;
+ }
+ const timeout = window.setTimeout(() => {
+ // A failed load closes the folder. Retry only after leaving and reentering.
+ attemptedNode.current = node.id;
+ tree.open(node.id);
+ }, HOVER_EXPAND_DELAY);
+ return () => window.clearTimeout(timeout);
+ }, [isHovering, node.data.isDirectory, node.isOpen, node.id, tree]);
+}
diff --git a/frontend/src/core/network/__tests__/requests-toasting.test.tsx b/frontend/src/core/network/__tests__/requests-toasting.test.tsx
index 8bb7581188..b0a2478e66 100644
--- a/frontend/src/core/network/__tests__/requests-toasting.test.tsx
+++ b/frontend/src/core/network/__tests__/requests-toasting.test.tsx
@@ -1,6 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { MockRequestClient } from "@/__mocks__/requests";
import { HTTPError } from "@/utils/errors";
const toastMock = vi.fn();
@@ -44,6 +45,19 @@ describe("createErrorToastingRequests", () => {
);
});
+ it("leaves search errors to callers without a toast per failed root", async () => {
+ const client = MockRequestClient.create();
+ const error = new Error("Storage unavailable");
+ vi.mocked(client.sendSearchFiles).mockRejectedValue(error);
+ const requests = createErrorToastingRequests(client);
+ for (const path of ["/workspace", "/shared"]) {
+ await expect(
+ requests.sendSearchFiles({ query: "report", path }),
+ ).rejects.toBe(error);
+ }
+ expect(toastMock).not.toHaveBeenCalled();
+ });
+
it("leaves file-root errors for the requesting tree to surface", async () => {
const error = new Error("Failed to load roots");
const requests = createErrorToastingRequests({
diff --git a/frontend/src/core/network/requests-toasting.tsx b/frontend/src/core/network/requests-toasting.tsx
index 5527423319..c9397269cf 100644
--- a/frontend/src/core/network/requests-toasting.tsx
+++ b/frontend/src/core/network/requests-toasting.tsx
@@ -50,7 +50,7 @@ export function createErrorToastingRequests(
getEnvironmentInfo: "", // No toast
getFileRoots: "", // RequestingTree surfaces this error
sendListFiles: "Failed to list files",
- sendSearchFiles: "Failed to search files",
+ sendSearchFiles: "", // Search callers handle errors
sendPdb: "Failed to start debug session",
sendSetBreakpoints: "", // No toast
sendCreateFileOrFolder: "Failed to create file or folder",
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index dbbbddc7ce..813735bad4 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -322,6 +322,7 @@ class PyodideBridge:
depth=body.depth,
include_directories=body.include_directories,
include_files=body.include_files,
+ include_hidden=body.include_hidden,
limit=body.limit,
)
response = FileSearchResponse(
diff --git a/marimo/_server/api/endpoints/file_explorer.py b/marimo/_server/api/endpoints/file_explorer.py
index b94a7411a6..87894fe693 100644
--- a/marimo/_server/api/endpoints/file_explorer.py
+++ b/marimo/_server/api/endpoints/file_explorer.py
@@ -1,6 +1,7 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import asyncio
from pathlib import Path
from typing import TYPE_CHECKING
@@ -127,7 +128,7 @@ async def list_files(
# for the browser.
directory = app_state.session_manager.workspace.directory
root = body.path or directory or file_system.get_root()
- files = file_system.list_files(root)
+ files = await asyncio.to_thread(file_system.list_files, root)
return FileListResponse(files=files, root=root)
@@ -446,11 +447,13 @@ async def search_files(
$ref: "#/components/schemas/FileSearchResponse"
"""
body = await parse_request(request, cls=FileSearchRequest)
- files = file_system.search(
+ files = await asyncio.to_thread(
+ file_system.search,
query=body.query,
path=body.path,
include_directories=body.include_directories,
include_files=body.include_files,
+ include_hidden=body.include_hidden,
depth=body.depth,
limit=body.limit,
)
diff --git a/marimo/_server/files/file_system.py b/marimo/_server/files/file_system.py
index e861caedd1..22405173f8 100644
--- a/marimo/_server/files/file_system.py
+++ b/marimo/_server/files/file_system.py
@@ -80,6 +80,7 @@ class FileSystem(ABC):
path: str | None = None,
include_directories: bool = True,
include_files: bool = True,
+ include_hidden: bool = True,
depth: int = 3,
limit: int = 100,
) -> list[FileInfo]:
@@ -88,6 +89,7 @@ class FileSystem(ABC):
Args:
query: Search query string (matches file/directory names)
path: Root path to search from (defaults to root)
+ include_hidden: Include hidden files and traverse hidden directories
include_directories: Include directories
include_files: Include files
depth: Maximum depth to search (default: 3)
diff --git a/marimo/_server/files/os_file_system.py b/marimo/_server/files/os_file_system.py
index a3d9a70b7b..0184cea0e7 100644
--- a/marimo/_server/files/os_file_system.py
+++ b/marimo/_server/files/os_file_system.py
@@ -2,15 +2,17 @@
from __future__ import annotations
import base64
+import heapq
import os
import platform
-import re
import shutil
import subprocess
import tempfile
+import time
from collections import deque
+from functools import lru_cache
from pathlib import Path
-from typing import Literal, Protocol
+from typing import TYPE_CHECKING, Literal, Protocol
from marimo import _loggers
from marimo._server.files.file_system import FileSystem
@@ -19,6 +21,9 @@ from marimo._session.notebook.file_manager import AppFileManager
from marimo._utils.files import natural_sort
from marimo._utils.mime import guess_mime_type
+if TYPE_CHECKING:
+ from collections.abc import Iterator
+
LOGGER = _loggers.marimo_logger()
LIST_IGNORE_LIST = [
@@ -91,7 +96,7 @@ class OSFileSystem(FileSystem):
name=entry.name,
is_directory=is_directory,
is_marimo_file=not is_directory
- and self._is_marimo_file(entry.path),
+ and self._is_marimo_file(entry.path, entry_stat),
last_modified=entry_stat.st_mtime,
size=None if is_directory else entry_stat.st_size,
)
@@ -114,7 +119,8 @@ class OSFileSystem(FileSystem):
path=path,
name=os.path.basename(path),
is_directory=is_directory,
- is_marimo_file=not is_directory and self._is_marimo_file(path),
+ is_marimo_file=not is_directory
+ and self._is_marimo_file(path, stat),
last_modified=stat.st_mtime,
size=None if is_directory else stat.st_size,
)
@@ -174,14 +180,24 @@ class OSFileSystem(FileSystem):
is_too_large=is_too_large,
)
- def _is_marimo_file(self, path: str) -> bool:
+ def _is_marimo_file(
+ self, path: str, stat: os.stat_result | None = None
+ ) -> bool:
file_path = Path(path)
if file_path.suffix not in (".py", ".md", ".qmd"):
return False
- from marimo._server.files.directory_scanner import is_marimo_app
-
- return is_marimo_app(path)
+ try:
+ stat = stat or os.stat(path)
+ except OSError:
+ return False
+ return _is_marimo_file_cached(
+ path,
+ stat.st_mtime_ns,
+ stat.st_ctime_ns,
+ stat.st_size,
+ int(time.monotonic() // 5),
+ )
def open_file(self, path: str, encoding: str | None = None) -> str | bytes:
file_path = Path(path)
@@ -332,11 +348,12 @@ class OSFileSystem(FileSystem):
path: str | None = None,
include_directories: bool = True,
include_files: bool = True,
+ include_hidden: bool = True,
depth: int = 3,
limit: int = 100,
) -> list[FileInfo]:
"""Search for files and directories matching a query with high performance."""
- if not query.strip():
+ if not query.strip() or limit <= 0:
return []
search_path = path if path is not None else self.get_root()
@@ -345,118 +362,77 @@ class OSFileSystem(FileSystem):
query_lower = query.lower()
- # Compile regex pattern for case-insensitive search
- try:
- pattern = re.compile(re.escape(query_lower))
- except re.error:
- # If regex compilation fails, fall back to simple string matching
- pattern = None
-
- results: list[FileInfo] = []
- seen_paths: set[str] = set()
-
- # Use BFS with deque for better performance than recursive DFS
- queue = deque([(search_path, 0)]) # (path, current_depth)
-
- while queue and len(results) < limit:
- current_path, current_depth = queue.popleft()
-
- # Skip if we've exceeded depth limit
- if current_depth > depth:
- continue
-
- # Skip if we've already processed this path (avoid symlink loops)
- if current_path in seen_paths:
- continue
- seen_paths.add(current_path)
-
- try:
- # Use os.scandir for better performance than os.listdir
- with os.scandir(current_path) as entries:
- for entry in entries:
- if len(results) >= limit:
- break
-
- # Skip ignored files/directories
- if entry.name in SEARCH_IGNORE_LIST:
- continue
-
- # Check if name matches query
- name_lower = entry.name.lower()
-
- matches = False
- if pattern:
- matches = pattern.search(name_lower) is not None
- else:
- matches = query_lower in name_lower
-
- if not matches:
- # If this is a directory and we haven't hit depth limit, add to queue
- if current_depth < depth:
- try:
- if entry.is_dir():
- queue.append(
- (entry.path, current_depth + 1)
- )
- except OSError:
- # Skip entries that can't be accessed
- continue
- continue
-
- try:
- is_directory = entry.is_dir()
- entry_stat = entry.stat()
-
- # Apply directory/file filtering
- if not include_directories and is_directory:
- # Skip directories if directory=False
+ def candidates() -> Iterator[os.DirEntry[str]]:
+ seen_paths: set[str] = set()
+ queue = deque([(search_path, 0)])
+ while queue:
+ current_path, current_depth = queue.popleft()
+ if current_depth > depth:
+ continue
+ real_path = os.path.realpath(current_path)
+ if real_path in seen_paths:
+ continue
+ seen_paths.add(real_path)
+ try:
+ with os.scandir(current_path) as entries:
+ for entry in entries:
+ if entry.name in SEARCH_IGNORE_LIST or (
+ not include_hidden
+ and entry.name.startswith(".")
+ ):
continue
- if not include_files and not is_directory:
- # Skip files if file=False
+ try:
+ is_directory = entry.is_dir()
+ if is_directory and current_depth < depth:
+ queue.append(
+ (entry.path, current_depth + 1)
+ )
+ if query_lower not in entry.name.lower():
+ continue
+ if is_directory and not include_directories:
+ continue
+ if not is_directory and not include_files:
+ continue
+ yield entry
+ except OSError:
continue
+ except OSError:
+ continue
- file_info = FileInfo(
- id=entry.path,
- path=entry.path,
- name=entry.name,
- is_directory=is_directory,
- # This can be expensive, so we don't do it on search
- is_marimo_file=False,
- last_modified=entry_stat.st_mtime,
- size=None
- if is_directory
- else entry_stat.st_size,
- )
- results.append(file_info)
-
- # If this is a matching directory and we haven't hit depth limit, add to queue
- if is_directory and current_depth < depth:
- queue.append((entry.path, current_depth + 1))
-
- except OSError:
- # Skip files/directories that can't be accessed
- continue
-
- except OSError:
- # Skip directories that can't be accessed
- continue
-
- # Sort results by relevance (exact matches first, then by name)
- def sort_key(file_info: FileInfo) -> tuple[int, str]:
- name_lower = file_info.name.lower()
-
- # Exact match gets highest priority
+ def sort_key(entry: os.DirEntry[str]) -> tuple[int, str, str]:
+ name_lower = entry.name.lower()
if name_lower == query_lower:
- return (0, file_info.name)
- # Starts with query gets second priority
+ rank = 0
elif name_lower.startswith(query_lower):
- return (1, file_info.name)
- # Contains query gets lowest priority
+ rank = 1
else:
- return (2, file_info.name)
+ rank = 2
+ return (rank, entry.name, entry.path)
- results.sort(key=sort_key)
- return results[:limit]
+ # Rank all names before fetching metadata, which can be expensive on
+ # network mounts. Only the best matches are retained in memory.
+ matches = heapq.nsmallest(limit, candidates(), key=sort_key)
+ files: list[FileInfo] = []
+ for entry in matches:
+ try:
+ entry_stat = entry.stat()
+ is_directory = entry.is_dir()
+ except OSError:
+ # A match may disappear or become unreadable during traversal.
+ continue
+ files.append(
+ FileInfo(
+ id=entry.path,
+ path=entry.path,
+ name=entry.name,
+ is_directory=is_directory,
+ # Notebook detection is deferred to preview.
+ is_marimo_file=False,
+ last_modified=entry_stat.st_mtime,
+ size=None if is_directory else entry_stat.st_size,
+ )
+ )
+ return files
def open_in_editor(self, path: str, line_number: int | None) -> bool:
try:
@@ -496,6 +472,19 @@ class OSFileSystem(FileSystem):
return False
+# Keep a small working set for repeated listings of recently viewed folders.
+@lru_cache(maxsize=512)
+def _is_marimo_file_cached(
+ path: str, _mtime_ns: int, _ctime_ns: int, _size: int, _time_bucket: int
+) -> bool:
+ # Metadata invalidates cached detection when a file changes; repeated
+ # directory listings need not scan unchanged file contents. A five-second
+ # bucket also bounds stale detection on filesystems that preserve metadata.
+ from marimo._server.files.directory_scanner import is_marimo_app
+
+ return is_marimo_app(path)
+
+
def editor_open_file_in_line_args(
editor: str, path: str, line_number: int
) -> list[str]:
diff --git a/marimo/_server/models/files.py b/marimo/_server/models/files.py
index ac1ede9289..f4de1f80c3 100644
--- a/marimo/_server/models/files.py
+++ b/marimo/_server/models/files.py
@@ -101,6 +101,8 @@ class FileSearchRequest(msgspec.Struct, rename="camel"):
include_directories: bool = True
# Include files
include_files: bool = True
+ # Include hidden files and traverse hidden directories
+ include_hidden: bool = True
# Maximum depth to search (default: 3)
depth: int = 3
# Maximum number of results to return (default: 100)
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index c7c35d0616..826d163ed6 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -2363,6 +2363,9 @@ components:
includeFiles:
default: true
type: boolean
+ includeHidden:
+ default: true
+ type: boolean
limit:
default: 100
type: integer
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 64d681a6cb..93ba350aa6 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -5108,6 +5108,8 @@ export interface components {
includeDirectories?: boolean;
/** @default true */
includeFiles?: boolean;
+ /** @default true */
+ includeHidden?: boolean;
/** @default 100 */
limit?: number;
/** @default null */
diff --git a/scripts/benchmarks/file_browser.py b/scripts/benchmarks/file_browser.py
new file mode 100644
index 0000000000..8308b9107b
--- /dev/null
+++ b/scripts/benchmarks/file_browser.py
@@ -0,0 +1,68 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""Compare uncached, cold-cache, and warm-cache directory listings.
+
+Run: uv run python scripts/benchmarks/file_browser.py
+Cold refers to the detector cache, not the operating system's filesystem cache.
+The clock is fixed to measure repeated listings within one cache expiry window.
+The larger cases intentionally exceed the 512-entry detector cache;
+its repeated scans measure eviction pressure, not a fully resident warm cache.
+"""
+
+from __future__ import annotations
+
+import statistics
+import tempfile
+import time
+from pathlib import Path
+from unittest.mock import patch
+
+from marimo._server.files.os_file_system import (
+ OSFileSystem,
+ _is_marimo_file_cached,
+)
+
+
+def measure(
+ fs: OSFileSystem, directory: Path, *, clear: bool = False
+) -> float:
+ samples = []
+ for _ in range(5):
+ if clear:
+ _is_marimo_file_cached.cache_clear()
+ start = time.perf_counter()
+ fs.list_files(str(directory))
+ samples.append(time.perf_counter() - start)
+ return statistics.median(samples) * 1000
+
+
+def main() -> None:
+ print("files Python% uncached_ms cold_ms repeat_ms cache_fit")
+ for count, python_every in [(100, 4), (1000, 4), (1000, 1), (10000, 4)]:
+ with tempfile.TemporaryDirectory() as temporary:
+ directory = Path(temporary)
+ for index in range(count):
+ suffix = ".py" if index % python_every == 0 else ".txt"
+ content = "print('hello')\n"
+ if index % (python_every * 2) == 0:
+ content = "import marimo\napp = marimo.App()\n"
+ (directory / f"file_{index:05d}{suffix}").write_text(content)
+ fs = OSFileSystem()
+ with patch(
+ "marimo._server.files.os_file_system.time.monotonic",
+ return_value=0,
+ ):
+ with patch(
+ "marimo._server.files.os_file_system._is_marimo_file_cached",
+ _is_marimo_file_cached.__wrapped__,
+ ):
+ uncached = measure(fs, directory)
+ cold = measure(fs, directory, clear=True)
+ warm = measure(fs, directory)
+ print(
+ f"{count:5d} {100 // python_every:7d} {uncached:11.2f} {cold:7.2f} {warm:9.2f} {count // python_every <= 512}"
+ )
+ _is_marimo_file_cached.cache_clear()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/_server/api/endpoints/test_file_explorer.py b/tests/_server/api/endpoints/test_file_explorer.py
index 7919747f8b..ed4f183336 100644
--- a/tests/_server/api/endpoints/test_file_explorer.py
+++ b/tests/_server/api/endpoints/test_file_explorer.py
@@ -473,6 +473,29 @@ def test_search_files_basic(client: TestClient, tmp_path: Path) -> None:
assert isinstance(data["totalFound"], int)
[email protected]("include_hidden", [None, True, False])
+def test_search_files_hidden_visibility(
+ client: TestClient, tmp_path: Path, include_hidden: bool | None
+) -> None:
+ (tmp_path / ".match.txt").write_text("")
+ visible = tmp_path / "visible"
+ visible.mkdir()
+ (visible / "match.txt").write_text("")
+ body = {"query": "txt", "path": str(tmp_path), "limit": 1}
+ if include_hidden is not None:
+ body["includeHidden"] = include_hidden
+ response = client.post("/api/files/search", headers=HEADERS, json=body)
+ assert response.status_code == 200, response.text
+ expected = (
+ tmp_path / ".match.txt"
+ if include_hidden is not False
+ else visible / "match.txt"
+ )
+ assert [file["path"] for file in response.json()["files"]] == [
+ str(expected)
+ ]
+
+
def test_search_files_with_matches(client: TestClient, tmp_path: Path) -> None:
"""Test search returns expected matches."""
# Create test structure
diff --git a/tests/_server/files/test_os_file_system.py b/tests/_server/files/test_os_file_system.py
index e079534cfa..75d01db2aa 100644
--- a/tests/_server/files/test_os_file_system.py
+++ b/tests/_server/files/test_os_file_system.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import sys
from pathlib import Path
from typing import Literal
+from unittest.mock import Mock, patch
import pytest
@@ -656,6 +657,43 @@ def test_get_details_non_utf8_encoding_and_contents(
class TestIsMarimoFile:
"""Tests for _is_marimo_file which delegates to is_marimo_app."""
+ def test_listing_reuses_detection_until_file_changes(
+ self, test_dir: Path, fs: OSFileSystem
+ ) -> None:
+ from marimo._server.files.directory_scanner import is_marimo_app
+
+ py_file = test_dir / "app.py"
+ py_file.write_text("print('hello')\n")
+ with patch(
+ "marimo._server.files.directory_scanner.is_marimo_app",
+ wraps=is_marimo_app,
+ ) as detect:
+ assert fs.list_files(str(test_dir))[0].is_marimo_file is False
+ assert fs.list_files(str(test_dir))[0].is_marimo_file is False
+ assert detect.call_count == 1
+
+ py_file.write_text("import marimo\napp = marimo.App()\n")
+ assert fs.list_files(str(test_dir))[0].is_marimo_file is True
+ assert detect.call_count == 2
+
+ def test_detection_expires_when_metadata_is_unchanged(
+ self, test_dir: Path, fs: OSFileSystem
+ ) -> None:
+ py_file = test_dir / "preserved.py"
+ notebook = "import marimo\napp = marimo.App()\n"
+ py_file.write_text("print(0)".ljust(len(notebook)))
+ unchanged_stat = py_file.stat()
+ with patch(
+ "marimo._server.files.os_file_system.time.monotonic",
+ return_value=100,
+ ) as clock:
+ assert fs._is_marimo_file(str(py_file), unchanged_stat) is False
+ py_file.write_text(notebook)
+ clock.return_value = 104
+ assert fs._is_marimo_file(str(py_file), unchanged_stat) is False
+ clock.return_value = 105
+ assert fs._is_marimo_file(str(py_file), unchanged_stat) is True
+
def test_python_marimo_file(
self, test_dir: Path, fs: OSFileSystem
) -> None:
@@ -733,6 +771,91 @@ def test_search_basic(test_dir: Path, fs: OSFileSystem) -> None:
assert "world.txt" not in file_names
[email protected](sys.platform == "win32", reason="Requires symlinks")
+def test_search_does_not_revisit_symlinked_directories(
+ test_dir: Path, fs: OSFileSystem
+) -> None:
+ (test_dir / "result.txt").write_text("result")
+ (test_dir / "loop").symlink_to(test_dir, target_is_directory=True)
+ results = fs.search("result", path=str(test_dir), depth=20)
+ assert [result.path for result in results] == [
+ str(test_dir / "result.txt")
+ ]
+
+
+def test_search_filters_hidden_entries_before_limit(
+ test_dir: Path, fs: OSFileSystem
+) -> None:
+ (test_dir / ".match").write_text("")
+ hidden = test_dir / ".cache"
+ hidden.mkdir()
+ (hidden / "match.txt").write_text("")
+ visible = test_dir / "visible"
+ visible.mkdir()
+ (visible / "match.txt").write_text("")
+
+ results = fs.search(
+ "match", path=str(test_dir), include_hidden=False, limit=1
+ )
+ assert [result.path for result in results] == [str(visible / "match.txt")]
+ assert (
+ len(fs.search("match", path=str(test_dir), include_hidden=True)) == 3
+ )
+
+
+def test_search_ranks_nested_matches_before_limiting(
+ test_dir: Path, fs: OSFileSystem
+) -> None:
+ for index in range(250):
+ (test_dir / f"weak-report-{index}.txt").write_text("")
+ nested = test_dir / "nested"
+ nested.mkdir()
+ (nested / "report").write_text("")
+ (nested / "report-summary.txt").write_text("")
+
+ results = fs.search("report", path=str(test_dir), limit=2)
+ assert [result.name for result in results] == [
+ "report",
+ "report-summary.txt",
+ ]
+
+
[email protected]("disappears", [False, True])
+def test_search_reads_metadata_only_for_selected_matches(
+ test_dir: Path, fs: OSFileSystem, disappears: bool
+) -> None:
+ import os
+
+ entries = []
+ for name in ["weak-report.txt", "report-summary.txt", "report"]:
+ path = test_dir / name
+ path.write_text("")
+ entry = Mock(spec=os.DirEntry)
+ entry.configure_mock(name=name, path=str(path))
+ entry.is_dir.return_value = False
+ entry.stat.return_value = path.stat()
+ entries.append(entry)
+ if disappears:
+ entries[-1].stat.side_effect = FileNotFoundError
+
+ with patch("marimo._server.files.os_file_system.os.scandir") as scandir:
+ scandir.return_value.__enter__.return_value = iter(entries)
+ results = fs.search("report", path=str(test_dir), limit=1)
+
+ assert [result.name for result in results] == (
+ [] if disappears else ["report"]
+ )
+ assert [entry.stat.call_count for entry in entries] == [0, 0, 1]
+
+
[email protected]("limit", [0, -1])
+def test_search_nonpositive_limit(
+ test_dir: Path, fs: OSFileSystem, limit: int
+) -> None:
+ (test_dir / "match.txt").write_text("")
+ assert fs.search("match", path=str(test_dir), limit=limit) == []
+
+
def test_search_empty_query(test_dir: Path, fs: OSFileSystem) -> None:
"""Test search with empty query returns no results."""
(test_dir / "test.txt").write_text("content")