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: support multi-root file browsing (#10727)

Myles Scolnick4daf46b19ec6
diff --git a/docs/guides/configuration/index.md b/docs/guides/configuration/index.md
index 08bf65760f..68e2322d0e 100644
--- a/docs/guides/configuration/index.md
+++ b/docs/guides/configuration/index.md
@@ -94,6 +94,19 @@ default_sql_output = "native"
You can override any user configuration setting in this way. To find these settings run `marimo config show`.
+### Additional file browser roots
+
+Add absolute local directories to the file browser with project configuration:
+
+```toml title="pyproject.toml"
+[tool.marimo.file_browser]
+folders = [{ path = "/absolute/path/to/data", name = "Data" }]
+```
+
+For `marimo.toml`, use `[file_browser]` instead. `name` is optional. Invalid or
+duplicate paths are ignored. Additional roots affect only the file browser and
+cannot be set through notebook script metadata.
+
!!! note "Overridden settings"
Settings overridden in `pyproject.toml` or script metadata cannot be changed through the marimo editor's settings menu. Any changes made to overridden settings in the editor will not take effect.
diff --git a/frontend/src/__mocks__/requests.ts b/frontend/src/__mocks__/requests.ts
index ece24aba1d..49fa93f9ac 100644
--- a/frontend/src/__mocks__/requests.ts
+++ b/frontend/src/__mocks__/requests.ts
@@ -48,6 +48,7 @@ export const MockRequestClient = {
getEnvironmentInfo: vi
.fn()
.mockRejectedValue(new Error("Environment information unavailable")),
+ getFileRoots: vi.fn().mockResolvedValue({ roots: [] }),
sendPdb: vi.fn().mockResolvedValue({}),
sendSetBreakpoints: vi.fn().mockResolvedValue({}),
sendListFiles: vi.fn().mockResolvedValue({ files: [] }),
diff --git a/frontend/src/components/editor/chrome/panels/file-explorer-panel.tsx b/frontend/src/components/editor/chrome/panels/file-explorer-panel.tsx
index 64ed1c38b0..c383d991b4 100644
--- a/frontend/src/components/editor/chrome/panels/file-explorer-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/file-explorer-panel.tsx
@@ -40,7 +40,7 @@ const FileExplorerComponent: React.FC<{ height: number }> = ({ height }) => {
const getDropDestinationPath = useCallback(
(event: DropEvent) =>
- getUploadDestinationForEvent(event, tree.getRootPath()),
+ getUploadDestinationForEvent(event, tree.getPrimaryRootPath()),
[tree],
);
const refreshUploadDestination = useCallback(
@@ -60,7 +60,8 @@ const FileExplorerComponent: React.FC<{ height: number }> = ({ height }) => {
onDragLeave: () => setDropDestinationPath(null),
onUploadStart: () => setDropDestinationPath(null),
});
- const displayedDestinationPath = dropDestinationPath ?? tree.getRootPath();
+ const displayedDestinationPath =
+ dropDestinationPath ?? tree.getPrimaryRootPath();
const displayedDestinationLabel = getUploadDestinationLabel(
tree,
displayedDestinationPath,
diff --git a/frontend/src/components/editor/file-tree/__tests__/file-explorer-interactions.test.tsx b/frontend/src/components/editor/file-tree/__tests__/file-explorer-interactions.test.tsx
index 7fe7a9c70a..d838f71ca4 100644
--- a/frontend/src/components/editor/file-tree/__tests__/file-explorer-interactions.test.tsx
+++ b/frontend/src/components/editor/file-tree/__tests__/file-explorer-interactions.test.tsx
@@ -7,8 +7,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { MockRequestClient } from "@/__mocks__/requests";
import { TooltipProvider } from "@/components/ui/tooltip";
import { requestClientAtom } from "@/core/network/requests";
-import type { FileInfo } from "@/core/network/types";
import { FileExplorer } from "../file-explorer";
+import type { FileTreeNode } from "../requesting-tree";
vi.mock("react-arborist", async (importOriginal) => {
const actual = await importOriginal<typeof import("react-arborist")>();
@@ -17,20 +17,29 @@ vi.mock("react-arborist", async (importOriginal) => {
Tree: ({
data,
onSelect,
+ onToggle,
}: {
- data: FileInfo[];
- onSelect: (nodes: Array<{ data: FileInfo }>) => void;
+ data: FileTreeNode[];
+ onSelect: (nodes: Array<{ id: string; data: FileTreeNode }>) => void;
+ onToggle: (id: string) => void;
}) => (
<div>
- {data.map((item) => (
- <button
- type="button"
- key={item.id}
- onClick={() => onSelect([{ data: item }])}
- >
- {item.name}
- </button>
- ))}
+ {data
+ .flatMap((item) => [item, ...item.children])
+ .map((item) => (
+ <button
+ type="button"
+ key={item.id}
+ onClick={() => {
+ onSelect([{ id: item.id, data: item }]);
+ if (item.isDirectory) {
+ void onToggle(item.id);
+ }
+ }}
+ >
+ {item.name}
+ </button>
+ ))}
</div>
),
};
@@ -51,8 +60,11 @@ describe("FileExplorer upload destination", () => {
localStorage.removeItem("marimo:showHiddenFiles");
testStore = createStore();
client = MockRequestClient.create({
+ getFileRoots: vi.fn().mockResolvedValue({
+ roots: [{ path: "/workspace", name: "workspace", isPrimary: true }],
+ }),
sendListFiles: vi.fn().mockImplementation(async ({ path }) => {
- if (path) {
+ if (path !== "/workspace") {
return { files: [] };
}
return {
@@ -81,10 +93,11 @@ describe("FileExplorer upload destination", () => {
it("uses the selected folder for toolbar uploads", async () => {
render(<FileExplorer height={300} />, { wrapper });
- const rootUpload = await screen.findByRole("button", {
- name: "Upload files to workspace root",
- });
- expect(rootUpload).toBeVisible();
+ expect(
+ await screen.findByRole("button", {
+ name: "Upload files to workspace",
+ }),
+ ).toBeVisible();
fireEvent.click(await screen.findByText("data"));
@@ -120,7 +133,7 @@ describe("FileExplorer upload destination", () => {
expect(
await screen.findByRole("button", {
- name: "Upload files to workspace root",
+ name: "Upload files to workspace",
}),
).toBeVisible();
expect(screen.queryByText(".hidden")).not.toBeInTheDocument();
diff --git a/frontend/src/components/editor/file-tree/__tests__/file-explorer.test.ts b/frontend/src/components/editor/file-tree/__tests__/file-explorer.test.ts
index ca5ea4cf98..510b86e658 100644
--- a/frontend/src/components/editor/file-tree/__tests__/file-explorer.test.ts
+++ b/frontend/src/components/editor/file-tree/__tests__/file-explorer.test.ts
@@ -1,29 +1,35 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { describe, expect, it } from "vitest";
-import type { FileInfo } from "@/core/network/types";
+import type { FileTreeNode } from "../requesting-tree";
import { filterHiddenTree, isDirectoryOrFileHidden } from "../file-explorer";
// Helpers to build FileInfo objects for tests
-const file = (name: string, path: string): FileInfo => ({
+const file = (name: string, path: string): FileTreeNode => ({
id: path,
name,
path,
isDirectory: false,
isMarimoFile: false,
children: [],
+ isRoot: false,
+ rootPath: "/",
+ isPrimaryRoot: true,
});
const dir = (
name: string,
path: string,
- children: FileInfo[] = [],
-): FileInfo => ({
+ children: FileTreeNode[] = [],
+): FileTreeNode => ({
id: path,
name,
path,
isDirectory: true,
isMarimoFile: false,
children,
+ isRoot: false,
+ rootPath: "/",
+ isPrimaryRoot: true,
});
describe("isDirectoryOrFileHidden", () => {
@@ -47,7 +53,7 @@ describe("isDirectoryOrFileHidden", () => {
describe("filterHiddenTree", () => {
it("should return all items when showHidden is true", () => {
- const list: FileInfo[] = [
+ const list: FileTreeNode[] = [
dir(".git", "/.git", []),
file("README.md", "/README.md"),
file(".env", "/.env"),
@@ -60,7 +66,7 @@ describe("filterHiddenTree", () => {
});
it("should filter out hidden files when showHidden is false", () => {
- const list: FileInfo[] = [
+ const list: FileTreeNode[] = [
dir(".git", "/.git"),
file("README.md", "/README.md"),
file(".env", "/.env"),
@@ -75,7 +81,7 @@ describe("filterHiddenTree", () => {
});
it("should filter hidden directories recursively", () => {
- const list: FileInfo[] = [
+ const list: FileTreeNode[] = [
dir("src", "/src", [
file("index.ts", "/src/index.ts"),
file(".DS_Store", "/src/.DS_Store"),
@@ -94,7 +100,7 @@ describe("filterHiddenTree", () => {
});
it("should handle nested hidden files", () => {
- const list: FileInfo[] = [
+ const list: FileTreeNode[] = [
dir("project", "/project", [
dir("src", "/project/src", [
file("index.ts", "/project/src/index.ts"),
@@ -114,7 +120,7 @@ describe("filterHiddenTree", () => {
});
it("should preserve directory structure when no children are filtered", () => {
- const list: FileInfo[] = [
+ const list: FileTreeNode[] = [
dir("src", "/src", [
file("index.ts", "/src/index.ts"),
file("utils.ts", "/src/utils.ts"),
@@ -128,7 +134,7 @@ describe("filterHiddenTree", () => {
});
it("should create new object only when children are filtered", () => {
- const list: FileInfo[] = [
+ const list: FileTreeNode[] = [
dir("src", "/src", [
file("index.ts", "/src/index.ts"),
file(".hidden", "/src/.hidden"),
@@ -148,7 +154,7 @@ describe("filterHiddenTree", () => {
});
it("should handle empty children arrays", () => {
- const list: FileInfo[] = [dir("empty-dir", "/empty-dir", [])];
+ const list: FileTreeNode[] = [dir("empty-dir", "/empty-dir", [])];
const result = filterHiddenTree(list, false);
@@ -157,7 +163,7 @@ describe("filterHiddenTree", () => {
});
it("should handle deeply nested structures", () => {
- const list: FileInfo[] = [
+ const list: FileTreeNode[] = [
dir("level1", "/level1", [
dir("level2", "/level1/level2", [
dir("level3", "/level1/level2/level3", [
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 6c326ff3a3..a478861e6d 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
@@ -3,8 +3,9 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { MockModules } from "@/__mocks__/common";
import { toast } from "@/components/ui/use-toast";
import type { FilePath } from "@/utils/paths";
-import { RequestingTree } from "../requesting-tree";
+import { fileTreeNodeId, RequestingTree } from "../requesting-tree";
+const getRoots = vi.fn();
const sendListFiles = vi.fn();
const sendCreateFileOrFolder = vi.fn();
const sendDeleteFileOrFolder = vi.fn();
@@ -13,499 +14,475 @@ const sendRenameFileOrFolder = vi.fn();
vi.mock("@/components/ui/use-toast", () => MockModules.toast());
+const PRIMARY_FILES = [
+ {
+ id: "/root/file1",
+ name: "file1",
+ path: "/root/file1",
+ isDirectory: false,
+ isMarimoFile: false,
+ children: [],
+ },
+ {
+ id: "/root/folder1",
+ name: "folder1",
+ path: "/root/folder1",
+ isDirectory: true,
+ isMarimoFile: false,
+ children: [],
+ },
+];
+
+const PRIMARY_ROOT_ID = fileTreeNodeId("/root", "/root");
+const PRIMARY_FILE_ID = fileTreeNodeId("/root", "/root/file1");
+const EXTERNAL_ROOT_ID = fileTreeNodeId("/external", "/external");
+
describe("RequestingTree", () => {
- let requestingTree: RequestingTree;
- const mockOnChange = vi.fn();
+ let tree: RequestingTree;
+ const onChange = vi.fn();
beforeEach(async () => {
- requestingTree = new RequestingTree({
+ getRoots.mockResolvedValue({
+ roots: [
+ { path: "/root", name: "workspace", isPrimary: true },
+ { path: "/external", name: "Shared", isPrimary: false },
+ ],
+ });
+ sendListFiles.mockImplementation(async ({ path }: { path: string }) => ({
+ files: path === "/root" ? PRIMARY_FILES : [],
+ root: path,
+ }));
+ sendCreateFileOrFolder.mockResolvedValue({ success: true });
+ sendDeleteFileOrFolder.mockResolvedValue({ success: true });
+ sendCopyFileOrFolder.mockResolvedValue({ success: true });
+ sendRenameFileOrFolder.mockResolvedValue({ success: true });
+
+ tree = new RequestingTree({
+ getRoots,
listFiles: sendListFiles,
createFileOrFolder: sendCreateFileOrFolder,
deleteFileOrFolder: sendDeleteFileOrFolder,
copyFileOrFolder: sendCopyFileOrFolder,
renameFileOrFolder: sendRenameFileOrFolder,
});
- sendListFiles.mockResolvedValue({
- files: [
- { id: "1.1", name: "file1", path: "/root/file1" },
- {
- id: "1.2",
- name: "folder1",
- isDirectory: true,
- path: "/root/folder1",
- },
- {
- id: "1.3",
- name: "folder2",
- isDirectory: true,
- path: "/root/folder2",
- },
- ],
- root: "/root",
- });
- await requestingTree.initialize(mockOnChange);
+ await tree.initialize(onChange);
});
afterEach(() => {
vi.clearAllMocks();
});
- test("initialize should load files and set rootPath", async () => {
- expect(sendListFiles).toHaveBeenCalledWith({ path: "" });
- expect(requestingTree.getRootPath()).toBe("/root");
- expect(mockOnChange).toHaveBeenCalledWith([
- { id: "1.1", name: "file1", path: "/root/file1" },
- { id: "1.2", name: "folder1", isDirectory: true, path: "/root/folder1" },
- { id: "1.3", name: "folder2", isDirectory: true, path: "/root/folder2" },
+ test("initializes with visible, unloaded root nodes", () => {
+ expect(getRoots).toHaveBeenCalledOnce();
+ expect(sendListFiles).not.toHaveBeenCalled();
+ expect(tree.getPrimaryRootPath()).toBe("/root");
+ expect(onChange).toHaveBeenLastCalledWith([
+ expect.objectContaining({
+ id: PRIMARY_ROOT_ID,
+ name: "workspace",
+ isRoot: true,
+ isPrimaryRoot: true,
+ children: [],
+ }),
+ expect.objectContaining({
+ id: EXTERNAL_ROOT_ID,
+ name: "Shared",
+ isRoot: true,
+ isPrimaryRoot: false,
+ children: [],
+ }),
]);
});
- test("expand should load children for a directory", async () => {
- sendListFiles.mockResolvedValue({
- files: [{ id: "2", name: "file2", path: "/roo/folder1/file2" }],
+ test("flattens the primary root when there are no additional roots", async () => {
+ getRoots.mockResolvedValueOnce({
+ roots: [{ path: "/root", name: "workspace", isPrimary: true }],
+ });
+ const singleRootOnChange = vi.fn();
+ const singleRootTree = new RequestingTree({
+ getRoots,
+ listFiles: sendListFiles,
+ createFileOrFolder: sendCreateFileOrFolder,
+ deleteFileOrFolder: sendDeleteFileOrFolder,
+ copyFileOrFolder: sendCopyFileOrFolder,
+ renameFileOrFolder: sendRenameFileOrFolder,
});
- const result = await requestingTree.expand("1.2");
- expect(result).toBe(true);
- expect(sendListFiles).toHaveBeenCalledWith({ path: "/root/folder1" });
- expect(mockOnChange).toHaveBeenCalled();
- const lastCall = mockOnChange.mock.calls.at(-1);
- expect(lastCall).toBeDefined();
- expect(lastCall![0]).toMatchInlineSnapshot(`
- [
- {
- "id": "1.1",
- "name": "file1",
- "path": "/root/file1",
- },
- {
- "children": [
- {
- "id": "2",
- "name": "file2",
- "path": "/roo/folder1/file2",
- },
- ],
- "id": "1.2",
- "isDirectory": true,
- "name": "folder1",
- "path": "/root/folder1",
- },
- {
- "id": "1.3",
- "isDirectory": true,
- "name": "folder2",
- "path": "/root/folder2",
- },
- ]
- `);
- });
- test("rename should change the name and path of a file", async () => {
- sendRenameFileOrFolder.mockResolvedValue({ success: true });
+ await singleRootTree.initialize(singleRootOnChange);
- await requestingTree.rename("1.1", "file2");
- expect(sendRenameFileOrFolder).toHaveBeenCalledWith({
- path: "/root/file1",
- newPath: "/root/file2",
+ expect(sendListFiles).toHaveBeenCalledWith({ path: "/root" });
+ expect(singleRootOnChange).toHaveBeenLastCalledWith([
+ expect.objectContaining({
+ id: PRIMARY_FILE_ID,
+ path: "/root/file1",
+ isRoot: false,
+ isPrimaryRoot: true,
+ }),
+ expect.objectContaining({
+ id: fileTreeNodeId("/root", "/root/folder1"),
+ path: "/root/folder1",
+ isRoot: false,
+ isPrimaryRoot: true,
+ }),
+ ]);
+
+ await singleRootTree.createFile({ name: "new.txt", parentId: null });
+ expect(sendCreateFileOrFolder).toHaveBeenCalledWith({
+ path: "/root",
+ type: "file",
+ name: "new.txt",
});
- expect(mockOnChange).toHaveBeenCalled();
- const lastCall = mockOnChange.mock.calls.at(-1);
- expect(lastCall).toBeDefined();
- expect(lastCall![0]).toMatchInlineSnapshot(`
- [
- {
- "id": "1.1",
- "name": "file1",
- "path": "/root/file1",
- },
- {
- "id": "1.2",
- "isDirectory": true,
- "name": "folder1",
- "path": "/root/folder1",
- },
- {
- "id": "1.3",
- "isDirectory": true,
- "name": "folder2",
- "path": "/root/folder2",
- },
- ]
- `);
});
- test("move should change the parent of a file", async () => {
- sendRenameFileOrFolder.mockResolvedValue({ success: true });
-
- await requestingTree.move(["1.1"], "1.2");
- expect(sendRenameFileOrFolder).toHaveBeenCalled();
- expect(mockOnChange).toHaveBeenCalled();
- const lastCall = mockOnChange.mock.calls.at(-1);
- expect(lastCall).toBeDefined();
- expect(lastCall![0]).toMatchInlineSnapshot(`
- [
- {
- "id": "1.1",
- "name": "file1",
- "path": "/root/file1",
- },
- {
- "children": [
- {
- "id": "1.1",
- "name": "file1",
- "path": "/root/folder1/file1",
- },
- ],
- "id": "1.2",
- "isDirectory": true,
- "name": "folder1",
- "path": "/root/folder1",
- },
+ test("expands each root lazily and annotates its descendants", async () => {
+ sendListFiles.mockResolvedValueOnce({
+ files: [
{
- "id": "1.3",
- "isDirectory": true,
- "name": "folder2",
- "path": "/root/folder2",
+ id: "/external/data.csv",
+ path: "/external/data.csv",
+ name: "data.csv",
+ isDirectory: false,
+ isMarimoFile: false,
+ children: [],
},
- ]
- `);
- });
-
- test("copy should duplicate a file", async () => {
- sendCopyFileOrFolder.mockResolvedValue({ success: true });
-
- await requestingTree.copy("1.1", "file1_copy");
- expect(sendCopyFileOrFolder).toHaveBeenCalledWith({
- path: "/root/file1",
- newPath: "/root/file1_copy",
+ ],
+ root: "/external",
});
- expect(mockOnChange).toHaveBeenCalled();
- });
-
- test("delete should drop a file on success", async () => {
- sendDeleteFileOrFolder.mockResolvedValue({ success: true });
- await requestingTree.delete("1.1");
- expect(sendDeleteFileOrFolder).toHaveBeenCalledWith({
- path: "/root/file1",
- });
- const lastCall = mockOnChange.mock.calls.at(-1);
- expect(lastCall?.[0].map((f: { id: string }) => f.id)).toEqual([
- "1.2",
- "1.3",
- ]);
+ expect(await tree.expand(EXTERNAL_ROOT_ID)).toBe(true);
+ expect(sendListFiles).toHaveBeenCalledWith({ path: "/external" });
+ expect(onChange.mock.calls.at(-1)?.[0][1].children[0]).toEqual(
+ expect.objectContaining({
+ path: "/external/data.csv",
+ rootPath: "/external",
+ isPrimaryRoot: false,
+ isRoot: false,
+ }),
+ );
});
- test("createFile should create a new file", async () => {
- sendCreateFileOrFolder.mockResolvedValue({ success: true });
-
- await requestingTree.createFile({ name: "file3", parentId: "1.2" });
+ test("uses the primary root for toolbar creation without a selection", async () => {
+ await tree.createFile({ name: "new.txt", parentId: null });
expect(sendCreateFileOrFolder).toHaveBeenCalledWith({
- path: "/root/folder1",
+ path: "/root",
type: "file",
- name: "file3",
+ name: "new.txt",
});
- expect(mockOnChange).toHaveBeenCalled();
});
- test("createFile should create a new notebook", async () => {
- sendCreateFileOrFolder.mockResolvedValue({ success: true });
-
- await requestingTree.createFile({
- name: "notebook1",
- parentId: "1.2",
- type: "notebook",
- });
+ test("creates and uploads into an explicitly selected root", async () => {
+ await tree.createFolder("exports", EXTERNAL_ROOT_ID);
expect(sendCreateFileOrFolder).toHaveBeenCalledWith({
- path: "/root/folder1",
- type: "notebook",
- name: "notebook1",
+ path: "/external",
+ type: "directory",
+ name: "exports",
});
- expect(mockOnChange).toHaveBeenCalled();
});
- test("createFolder should create a new folder", async () => {
- sendCreateFileOrFolder.mockResolvedValue({ success: true });
-
- await requestingTree.createFolder("folder3", "1.2");
- expect(sendCreateFileOrFolder).toHaveBeenCalled();
- expect(mockOnChange).toHaveBeenCalled();
+ test("prevents mutations of structural root nodes", async () => {
+ await tree.rename(EXTERNAL_ROOT_ID, "renamed");
+ await tree.copy(EXTERNAL_ROOT_ID, "copy");
+ await tree.delete(EXTERNAL_ROOT_ID);
+
+ expect(sendRenameFileOrFolder).not.toHaveBeenCalled();
+ expect(sendCopyFileOrFolder).not.toHaveBeenCalled();
+ expect(sendDeleteFileOrFolder).not.toHaveBeenCalled();
+ expect(toast).toHaveBeenCalledWith(
+ expect.objectContaining({
+ description: "File browser roots cannot be modified",
+ }),
+ );
});
- test("refreshAll should refresh data for all open folders", async () => {
- await requestingTree.refreshAll(["1.1"]);
- expect(sendListFiles).toHaveBeenCalled();
- expect(mockOnChange).toHaveBeenCalled();
- const lastCall = mockOnChange.mock.calls.at(-1);
- expect(lastCall).toBeDefined();
- expect(lastCall![0]).toMatchInlineSnapshot(`
- [
- {
- "id": "1.1",
- "name": "file1",
- "path": "/root/file1",
- },
- {
- "id": "1.2",
- "isDirectory": true,
- "name": "folder1",
- "path": "/root/folder1",
- },
- {
- "id": "1.3",
- "isDirectory": true,
- "name": "folder2",
- "path": "/root/folder2",
- },
- ]
- `);
- });
+ test("supports copying, renaming, and deleting files by absolute path", async () => {
+ await tree.expand(PRIMARY_ROOT_ID);
- test("refreshPath should refresh an uploaded file's destination", async () => {
- sendListFiles.mockImplementation(async ({ path }: { path: string }) => {
- if (path === "/root/folder1") {
- return {
- files: [
- {
- id: "uploaded",
- name: "uploaded.csv",
- path: "/root/folder1/uploaded.csv",
- },
- ],
- };
- }
- return {
- files: [
- { id: "1.1", name: "file1", path: "/root/file1" },
- {
- id: "1.2",
- name: "folder1",
- isDirectory: true,
- path: "/root/folder1",
- },
- {
- id: "1.3",
- name: "folder2",
- isDirectory: true,
- path: "/root/folder2",
- },
- ],
- };
+ await tree.copy(PRIMARY_FILE_ID, "file1_copy");
+ expect(sendCopyFileOrFolder).toHaveBeenCalledWith({
+ path: "/root/file1",
+ newPath: "/root/file1_copy",
});
- await requestingTree.refreshPath("/root/folder1" as FilePath);
+ await tree.rename(PRIMARY_FILE_ID, "file2");
+ expect(sendRenameFileOrFolder).toHaveBeenCalledWith({
+ path: "/root/file1",
+ newPath: "/root/file2",
+ });
- expect(sendListFiles).toHaveBeenCalledWith({ path: "/root/folder1" });
- expect(mockOnChange.mock.calls.at(-1)?.[0]).toEqual([
- { id: "1.1", name: "file1", path: "/root/file1" },
- {
- id: "1.2",
- name: "folder1",
- isDirectory: true,
- path: "/root/folder1",
- children: [
- {
- id: "uploaded",
- name: "uploaded.csv",
- path: "/root/folder1/uploaded.csv",
- },
- ],
- },
- {
- id: "1.3",
- name: "folder2",
- isDirectory: true,
- path: "/root/folder2",
- },
- ]);
+ await tree.delete(PRIMARY_FILE_ID);
+ expect(sendDeleteFileOrFolder).toHaveBeenCalledWith({
+ path: "/root/file1",
+ });
});
- describe("when API fails", () => {
- test("initialize should handle errors gracefully", async () => {
- requestingTree = new RequestingTree({
- listFiles: sendListFiles,
- createFileOrFolder: sendCreateFileOrFolder,
- deleteFileOrFolder: sendDeleteFileOrFolder,
- copyFileOrFolder: sendCopyFileOrFolder,
- renameFileOrFolder: sendRenameFileOrFolder,
- });
- sendListFiles.mockRejectedValue(new Error("Network error"));
- await requestingTree.initialize(mockOnChange);
- expect(toast).toHaveBeenCalledWith({
- title: "Failed",
- description: expect.any(String),
- });
+ describe("failed mutations", () => {
+ beforeEach(async () => {
+ await tree.expand(PRIMARY_ROOT_ID);
+ sendListFiles.mockClear();
+ onChange.mockClear();
});
- test("rename should handle API failure", async () => {
- sendRenameFileOrFolder.mockResolvedValue({
+ test("does not update or refresh after a failed copy", async () => {
+ sendCopyFileOrFolder.mockResolvedValueOnce({
success: false,
- message: "Error renaming",
+ message: "Permission denied",
});
- await requestingTree.rename("1.1", "file2");
- expect(sendRenameFileOrFolder).toHaveBeenCalledWith({
- path: "/root/file1",
- newPath: "/root/file2",
- });
+ await tree.copy(PRIMARY_FILE_ID, "file1_copy");
+
+ expect(sendListFiles).not.toHaveBeenCalled();
+ expect(onChange).not.toHaveBeenCalled();
expect(toast).toHaveBeenCalledWith({
title: "Failed",
- description: "Error renaming",
+ description: "Permission denied",
});
});
- test("rename should NOT mutate the local tree on API failure", async () => {
- sendRenameFileOrFolder.mockResolvedValue({
+ test("does not update or refresh after a failed rename", async () => {
+ sendRenameFileOrFolder.mockResolvedValueOnce({
success: false,
- message: "Error renaming",
+ message: "Permission denied",
});
- const changesBefore = mockOnChange.mock.calls.length;
-
- await requestingTree.rename("1.1", "file2");
- // No further onChange calls should fire after the failed rename, so the
- // tree stays in sync with the backend.
- expect(mockOnChange.mock.calls.length).toBe(changesBefore);
- });
+ await tree.rename(PRIMARY_FILE_ID, "file2");
- test("delete should NOT drop the node on API failure", async () => {
- sendDeleteFileOrFolder.mockResolvedValue({
- success: false,
- message: "Error deleting",
- });
- const changesBefore = mockOnChange.mock.calls.length;
-
- await requestingTree.delete("1.1");
- expect(sendDeleteFileOrFolder).toHaveBeenCalledWith({
- path: "/root/file1",
- });
+ expect(sendListFiles).not.toHaveBeenCalled();
+ expect(onChange).not.toHaveBeenCalled();
expect(toast).toHaveBeenCalledWith({
title: "Failed",
- description: "Error deleting",
+ description: "Permission denied",
});
- expect(mockOnChange.mock.calls.length).toBe(changesBefore);
});
- test("move should NOT mutate the local tree when rename fails", async () => {
- sendRenameFileOrFolder.mockResolvedValue({
+ test("does not update or refresh after a failed delete", async () => {
+ sendDeleteFileOrFolder.mockResolvedValueOnce({
success: false,
- message: "Error moving",
+ message: "Permission denied",
});
- await requestingTree.move(["1.1"], "1.2");
+ await tree.delete(PRIMARY_FILE_ID);
+ expect(sendListFiles).not.toHaveBeenCalled();
+ expect(onChange).not.toHaveBeenCalled();
expect(toast).toHaveBeenCalledWith({
title: "Failed",
- description: "Error moving",
+ description: "Permission denied",
});
- // The last emitted state should still have file1 at the top level, not
- // moved under folder1.
- const lastCall = mockOnChange.mock.calls.at(-1);
- expect(lastCall?.[0]).toEqual([
- { id: "1.1", name: "file1", path: "/root/file1" },
- {
- id: "1.2",
- name: "folder1",
- isDirectory: true,
- path: "/root/folder1",
- },
- {
- id: "1.3",
- name: "folder2",
- isDirectory: true,
- path: "/root/folder2",
- },
- ]);
});
- test("copy should handle API failure", async () => {
- sendCopyFileOrFolder.mockResolvedValue({
+ test("does not update or refresh after a failed move", async () => {
+ sendRenameFileOrFolder.mockResolvedValueOnce({
success: false,
- message: "Error duplicating",
+ message: "Permission denied",
});
- await requestingTree.copy("1.1", "file1_copy");
- expect(sendCopyFileOrFolder).toHaveBeenCalledWith({
- path: "/root/file1",
- newPath: "/root/file1_copy",
- });
+ await tree.move([PRIMARY_FILE_ID], EXTERNAL_ROOT_ID);
+
+ expect(sendListFiles).not.toHaveBeenCalled();
+ expect(onChange).not.toHaveBeenCalled();
expect(toast).toHaveBeenCalledWith({
title: "Failed",
- description: "Error duplicating",
+ description: "Permission denied",
});
});
+ });
+
+ test("moves files across roots and refreshes both parents", async () => {
+ await tree.expand(PRIMARY_ROOT_ID);
+ sendListFiles.mockClear();
+
+ await tree.move([PRIMARY_FILE_ID], EXTERNAL_ROOT_ID);
- test("move should handle missing parent node gracefully", async () => {
- await requestingTree.move(["1.x"], "2");
- expect(sendRenameFileOrFolder).not.toHaveBeenCalled();
- expect(mockOnChange).toHaveBeenCalledTimes(3);
+ expect(sendRenameFileOrFolder).toHaveBeenCalledWith({
+ path: "/root/file1",
+ newPath: "/external/file1",
});
+ expect(sendListFiles).toHaveBeenCalledWith({ path: "/root" });
+ expect(sendListFiles).toHaveBeenCalledWith({ path: "/external" });
+ });
+
+ test("refreshes configured roots when every node is collapsed", async () => {
+ await tree.refreshAll([]);
+ expect(sendListFiles).toHaveBeenCalledWith({ path: "/root" });
+ expect(sendListFiles).toHaveBeenCalledWith({ path: "/external" });
+ });
+
+ test("refreshes supplied open folders in addition to configured roots", async () => {
+ await tree.expand(PRIMARY_ROOT_ID);
+ sendListFiles.mockClear();
+
+ await tree.refreshAll([fileTreeNodeId("/root", "/root/folder1")]);
+
+ expect(sendListFiles).toHaveBeenCalledWith({ path: "/root" });
+ expect(sendListFiles).toHaveBeenCalledWith({ path: "/external" });
+ expect(sendListFiles).toHaveBeenCalledWith({ 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];
+ sendListFiles.mockRejectedValueOnce(new Error("Network error"));
+
+ await tree.refreshPath("/root" as FilePath);
+
+ expect(onChange.mock.calls.at(-1)?.[0]).toEqual(beforeRefresh);
+ });
- test("refreshAll should handle API errors without crashing", async () => {
- sendListFiles.mockRejectedValue(new Error("Network error"));
- await requestingTree.refreshAll(["1.2"]);
- expect(sendListFiles).toHaveBeenCalled();
- // Ensure onChange is still called to update UI even if data might not have changed
- expect(mockOnChange).toHaveBeenCalled();
+ test("namespaces duplicate paths under overlapping roots", async () => {
+ getRoots.mockResolvedValueOnce({
+ roots: [
+ { path: "/repo", name: "repo", isPrimary: true },
+ { path: "/repo/data", name: "Data", isPrimary: false },
+ ],
});
+ sendListFiles.mockImplementation(async ({ path }: { path: string }) => ({
+ root: path,
+ files:
+ path === "/repo"
+ ? [
+ {
+ id: "/repo/data",
+ name: "data",
+ path: "/repo/data",
+ isDirectory: true,
+ isMarimoFile: false,
+ children: [],
+ },
+ ]
+ : [
+ {
+ id: "/repo/data/file.csv",
+ name: "file.csv",
+ path: "/repo/data/file.csv",
+ isDirectory: false,
+ isMarimoFile: false,
+ children: [],
+ },
+ ],
+ }));
+ const overlapOnChange = vi.fn();
+ const overlapTree = new RequestingTree({
+ getRoots,
+ listFiles: sendListFiles,
+ createFileOrFolder: sendCreateFileOrFolder,
+ deleteFileOrFolder: sendDeleteFileOrFolder,
+ copyFileOrFolder: sendCopyFileOrFolder,
+ renameFileOrFolder: sendRenameFileOrFolder,
+ });
+ await overlapTree.initialize(overlapOnChange);
+
+ const primaryRootId = fileTreeNodeId("/repo", "/repo");
+ const nestedDirectoryId = fileTreeNodeId("/repo", "/repo/data");
+ const additionalRootId = fileTreeNodeId("/repo/data", "/repo/data");
+ expect(nestedDirectoryId).not.toBe(additionalRootId);
+
+ await overlapTree.expand(primaryRootId);
+ await overlapTree.expand(nestedDirectoryId);
+ await overlapTree.expand(additionalRootId);
+
+ const roots = overlapOnChange.mock.calls.at(-1)?.[0];
+ expect(roots[0].children[0].id).toBe(nestedDirectoryId);
+ expect(roots[1].id).toBe(additionalRootId);
+ expect(roots[0].children[0].children[0].id).toBe(
+ fileTreeNodeId("/repo", "/repo/data/file.csv"),
+ );
+ expect(roots[1].children[0].id).toBe(
+ fileTreeNodeId("/repo/data", "/repo/data/file.csv"),
+ );
});
- describe("relativeFromRoot", () => {
- test("should return relative path for Unix paths", async () => {
- const tree = new RequestingTree({
+ describe("primary-root paths", () => {
+ test("returns relative paths only inside the primary root", () => {
+ expect(tree.getPrimaryRelativePath("/root/src/file.py" as FilePath)).toBe(
+ "src/file.py",
+ );
+ expect(
+ tree.getPrimaryRelativePath("/rooted/file.py" as FilePath),
+ ).toBeNull();
+ expect(
+ tree.getPrimaryRelativePath("/external/file.py" as FilePath),
+ ).toBeNull();
+ });
+
+ test("supports Windows path boundaries case-insensitively", async () => {
+ getRoots.mockResolvedValueOnce({
+ roots: [
+ {
+ path: "C:\\Users\\Test\\Project",
+ name: "Project",
+ isPrimary: true,
+ },
+ ],
+ });
+ const windowsTree = new RequestingTree({
+ getRoots,
listFiles: sendListFiles,
createFileOrFolder: sendCreateFileOrFolder,
deleteFileOrFolder: sendDeleteFileOrFolder,
copyFileOrFolder: sendCopyFileOrFolder,
renameFileOrFolder: sendRenameFileOrFolder,
});
-
- sendListFiles.mockResolvedValue({
- files: [],
- root: "/home/user/project",
- });
-
- await tree.initialize(vi.fn());
-
- const relativePath = tree.relativeFromRoot(
- "/home/user/project/src/file.py" as FilePath,
- );
- expect(relativePath).toBe("src/file.py");
+ await windowsTree.initialize(vi.fn());
+
+ expect(
+ windowsTree.getPrimaryRelativePath(
+ "c:\\users\\test\\project\\src\\file.py" as FilePath,
+ ),
+ ).toBe("src\\file.py");
+ expect(
+ windowsTree.getPrimaryRelativePath(
+ "C:\\Users\\Test\\Project-old\\file.py" as FilePath,
+ ),
+ ).toBeNull();
});
- test("should return relative path for Windows paths", async () => {
- const tree = new RequestingTree({
+ test("treats backslashes in POSIX paths as filename characters", async () => {
+ const rootPath = "/root/data\\archive";
+ const filePath = `${rootPath}/file.txt`;
+ getRoots.mockResolvedValueOnce({
+ roots: [{ path: rootPath, name: "archive", isPrimary: true }],
+ });
+ sendListFiles.mockResolvedValueOnce({
+ root: rootPath,
+ files: [
+ {
+ id: filePath,
+ path: filePath,
+ name: "file.txt",
+ isDirectory: false,
+ isMarimoFile: false,
+ children: [],
+ },
+ ],
+ });
+ const posixTree = new RequestingTree({
+ getRoots,
listFiles: sendListFiles,
createFileOrFolder: sendCreateFileOrFolder,
deleteFileOrFolder: sendDeleteFileOrFolder,
copyFileOrFolder: sendCopyFileOrFolder,
renameFileOrFolder: sendRenameFileOrFolder,
});
+ await posixTree.initialize(vi.fn());
- sendListFiles.mockResolvedValue({
- files: [],
- root: "C:\\Users\\test\\project",
- });
-
- await tree.initialize(vi.fn());
-
- const relativePath = tree.relativeFromRoot(
- "C:\\Users\\test\\project\\src\\file.py" as FilePath,
+ expect(posixTree.getPrimaryRelativePath(filePath as FilePath)).toBe(
+ "file.txt",
);
- expect(relativePath).toBe("src\\file.py");
+ await posixTree.copy(fileTreeNodeId(rootPath, filePath), "copy.txt");
+ expect(sendCopyFileOrFolder).toHaveBeenCalledWith({
+ path: filePath,
+ newPath: `${rootPath}/copy.txt`,
+ });
});
- test("should return original path when not under root", async () => {
- const relativePath = requestingTree.relativeFromRoot(
- "/other/path/file.py" as FilePath,
+ test("uses configured names in root-qualified display paths", () => {
+ expect(tree.getDisplayPath("/root/data.csv" as FilePath)).toBe(
+ "data.csv",
);
- expect(relativePath).toBe("/other/path/file.py");
- });
-
- test("should handle root path exactly", async () => {
- const relativePath = requestingTree.relativeFromRoot("/root" as FilePath);
- expect(relativePath).toBe("/root");
+ expect(tree.getDisplayPath("/external/data.csv" as FilePath)).toBe(
+ "Shared/data.csv",
+ );
+ expect(tree.getDisplayPath("/external" as FilePath)).toBe("Shared");
});
});
});
diff --git a/frontend/src/components/editor/file-tree/file-explorer.tsx b/frontend/src/components/editor/file-tree/file-explorer.tsx
index cfd6358aeb..92dcbb8cb1 100644
--- a/frontend/src/components/editor/file-tree/file-explorer.tsx
+++ b/frontend/src/components/editor/file-tree/file-explorer.tsx
@@ -11,6 +11,7 @@ import {
ExternalLinkIcon,
FilePlus2Icon,
FolderPlusIcon,
+ FolderRootIcon,
ListTreeIcon,
PlaySquareIcon,
UploadIcon,
@@ -58,7 +59,6 @@ import { useCellActions } from "@/core/cells/cells";
import { useLastFocusedCellId } from "@/core/cells/focus";
import { disableFileDownloadsAtom } from "@/core/config/config";
import { useRequestClient } from "@/core/network/requests";
-import type { FileInfo } from "@/core/network/types";
import { isWasm } from "@/core/wasm/utils";
import { useAsyncData } from "@/hooks/useAsyncData";
import { ErrorBanner } from "@/plugins/impl/common/error-banner";
@@ -71,7 +71,7 @@ import { jotaiJsonStorage } from "@/utils/storage/jotai";
import { useTreeDndManager } from "./dnd-wrapper";
import { downloadFile } from "./download";
import { FileViewer } from "./file-viewer";
-import type { RequestingTree } from "./requesting-tree";
+import type { FileTreeNode, RequestingTree } from "./requesting-tree";
import { openStateAtom, treeAtom } from "./state";
import { PYTHON_CODE_FOR_FILE_TYPE } from "./types";
import {
@@ -101,14 +101,15 @@ export const FileExplorer: React.FC<{
height: number;
externalDropDestinationPath?: FilePath | null;
}> = ({ height, externalDropDestinationPath = null }) => {
- const treeRef = useRef<TreeApi<FileInfo>>(null);
+ const treeRef = useRef<TreeApi<FileTreeNode>>(null);
const dndManager = useTreeDndManager();
const [tree] = useAtom(treeAtom);
- const [data, setData] = useState<FileInfo[]>([]);
- const [openFile, setOpenFile] = useState<FileInfo | null>(null);
- const [selectedFolderPath, setSelectedFolderPath] = useState<FilePath | null>(
- null,
- );
+ const [data, setData] = useState<FileTreeNode[]>([]);
+ const [openFile, setOpenFile] = useState<FileTreeNode | null>(null);
+ const [selectedFolder, setSelectedFolder] = useState<{
+ id: string;
+ path: FilePath;
+ } | null>(null);
const [showHiddenFiles, setShowHiddenFiles] =
useAtom<boolean>(hiddenFilesState);
// Keep external state to remember which folders are open when this
@@ -153,7 +154,7 @@ export const FileExplorer: React.FC<{
openPrompt({
title: "Folder name",
onConfirm: async (name) => {
- tree.createFolder(name, null);
+ tree.createFolder(name, selectedFolder?.id ?? null);
},
});
});
@@ -162,7 +163,7 @@ export const FileExplorer: React.FC<{
openPrompt({
title: "File name",
onConfirm: async (name) => {
- tree.createFile({ name, parentId: null });
+ tree.createFile({ name, parentId: selectedFolder?.id ?? null });
},
});
});
@@ -171,7 +172,11 @@ export const FileExplorer: React.FC<{
openPrompt({
title: "Notebook name",
onConfirm: async (name) => {
- tree.createFile({ name, parentId: null, type: "notebook" });
+ tree.createFile({
+ name,
+ parentId: selectedFolder?.id ?? null,
+ type: "notebook",
+ });
},
});
});
@@ -186,13 +191,10 @@ export const FileExplorer: React.FC<{
[data, showHiddenFiles],
);
React.useEffect(() => {
- if (
- selectedFolderPath &&
- !treeContainsPath(visibleData, selectedFolderPath)
- ) {
- setSelectedFolderPath(null);
+ if (selectedFolder && !treeContainsId(visibleData, selectedFolder.id)) {
+ setSelectedFolder(null);
}
- }, [selectedFolderPath, visibleData]);
+ }, [selectedFolder, visibleData]);
const contextValue = React.useMemo<FileExplorerContextValue>(
() => ({
tree,
@@ -227,11 +229,17 @@ export const FileExplorer: React.FC<{
</div>
<Suspense>
<FileViewer
- onOpenNotebook={(evt) =>
- openMarimoNotebook(
- evt,
- tree.relativeFromRoot(openFile.path as FilePath),
- )
+ onOpenNotebook={
+ tree.isPrimaryNode(openFile)
+ ? (evt) => {
+ const path = tree.getPrimaryRelativePath(
+ openFile.path as FilePath,
+ );
+ if (path !== null) {
+ openMarimoNotebook(evt, path);
+ }
+ }
+ : undefined
}
file={openFile}
/>
@@ -254,15 +262,17 @@ export const FileExplorer: React.FC<{
onCreateNotebook={handleCreateNotebook}
onCreateFolder={handleCreateFolder}
onCollapseAll={handleCollapseAll}
- uploadDestinationPath={selectedFolderPath ?? tree.getRootPath()}
+ uploadDestinationPath={
+ selectedFolder?.path ?? tree.getPrimaryRootPath()
+ }
uploadDestinationLabel={getUploadDestinationLabel(
tree,
- selectedFolderPath ?? tree.getRootPath(),
+ selectedFolder?.path ?? tree.getPrimaryRootPath(),
)}
onUpload={handleUploadFiles}
/>
<RequestingTreeContext value={contextValue}>
- <Tree<FileInfo>
+ <Tree<FileTreeNode>
width="100%"
ref={treeRef}
height={height - 33}
@@ -275,7 +285,11 @@ export const FileExplorer: React.FC<{
// Hide the drop cursor
renderCursor={() => null}
// Disable dropping files into files
- disableDrop={({ parentNode }) => !parentNode.data.isDirectory}
+ 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);
@@ -290,14 +304,17 @@ export const FileExplorer: React.FC<{
onSelect={(nodes) => {
const first = nodes[0];
if (!first) {
- setSelectedFolderPath(null);
+ setSelectedFolder(null);
return;
}
if (first.data.isDirectory) {
- setSelectedFolderPath(first.data.path as FilePath);
+ setSelectedFolder({
+ id: first.id,
+ path: first.data.path as FilePath,
+ });
return;
}
- setSelectedFolderPath(null);
+ setSelectedFolder(null);
setOpenFile(first.data);
}}
onToggle={async (id) => {
@@ -422,12 +439,12 @@ const Show = ({
node,
onOpenMarimoFile,
}: {
- node: NodeApi<FileInfo>;
+ node: NodeApi<FileTreeNode>;
onOpenMarimoFile: (
evt: Pick<Event, "stopPropagation" | "preventDefault">,
) => void;
}) => {
- return (
+ const label = (
<span
className="flex-1 overflow-hidden text-ellipsis"
onClick={(e) => {
@@ -439,7 +456,7 @@ const Show = ({
}}
>
{node.data.name}
- {node.data.isMarimoFile && !isWasm() && (
+ {node.data.isMarimoFile && node.data.isPrimaryRoot && !isWasm() && (
<span
data-testid="file-explorer-open-marimo-button"
className="shrink-0 ml-2 text-sm hidden group-hover:inline hover:underline"
@@ -450,9 +467,15 @@ const Show = ({
)}
</span>
);
+
+ return node.data.isRoot ? (
+ <Tooltip content={node.data.path}>{label}</Tooltip>
+ ) : (
+ label
+ );
};
-const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
+const Node = ({ node, style, dragHandle }: NodeRendererProps<FileTreeNode>) => {
const { openFile } = useRequestClient();
const disableFileDownloads = useAtomValue(disableFileDownloadsAtom);
@@ -482,10 +505,10 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
const handleOpenMarimoFile = async (
evt: Pick<Event, "stopPropagation" | "preventDefault">,
) => {
- const path = tree
- ? tree.relativeFromRoot(node.data.path as FilePath)
- : node.data.path;
- openMarimoNotebook(evt, path);
+ const path = tree?.getPrimaryRelativePath(node.data.path as FilePath);
+ if (path !== null && path !== undefined) {
+ openMarimoNotebook(evt, path);
+ }
};
const handleDeleteFile = async (evt: Event) => {
@@ -555,7 +578,7 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
className={cn(
"flex items-center cursor-pointer ml-1 text-muted-foreground whitespace-nowrap group",
)}
- draggable={true}
+ draggable={!node.data.isRoot}
onClick={(evt) => {
evt.stopPropagation();
if (node.data.isDirectory) {
@@ -577,7 +600,12 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
"bg-primary/15 hover:bg-primary/15 text-accent-foreground ring-1 ring-inset ring-primary",
)}
>
- {node.data.isMarimoFile ? (
+ {node.data.isRoot ? (
+ <FolderRootIcon
+ className="w-5 h-5 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} />
) : (
<Icon
@@ -649,14 +677,18 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
<DropdownMenuSeparator />
</>
)}
- <RenameMenuItem
- onSelect={() => node.edit()}
- testId="file-explorer-rename-menu-item"
- />
- <DuplicateMenuItem
- onSelect={handleDuplicate}
- testId="file-explorer-duplicate-menu-item"
- />
+ {!node.data.isRoot && (
+ <>
+ <RenameMenuItem
+ onSelect={() => node.edit()}
+ testId="file-explorer-rename-menu-item"
+ />
+ <DuplicateMenuItem
+ onSelect={handleDuplicate}
+ testId="file-explorer-duplicate-menu-item"
+ />
+ </>
+ )}
<DropdownMenuItem
onSelect={async () => {
await copyToClipboard(node.data.path);
@@ -667,13 +699,16 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
<ListTreeIcon className={MENU_ITEM_ICON_CLASS} />
Copy path
</DropdownMenuItem>
- {tree && (
+ {tree && node.data.isPrimaryRoot && !node.data.isRoot && (
<DropdownMenuItem
onSelect={async () => {
- await copyToClipboard(
- tree.relativeFromRoot(node.data.path as FilePath),
+ const path = tree.getPrimaryRelativePath(
+ node.data.path as FilePath,
);
- toast({ title: "Copied to clipboard" });
+ if (path !== null) {
+ await copyToClipboard(path);
+ toast({ title: "Copied to clipboard" });
+ }
}}
data-testid="file-explorer-copy-relative-path-menu-item"
>
@@ -681,35 +716,39 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
Copy relative path
</DropdownMenuItem>
)}
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onSelect={() => {
- const { path } = node.data;
- const pythonCode = PYTHON_CODE_FOR_FILE_TYPE[fileType](path);
- handleInsertCode(pythonCode);
- }}
- data-testid="file-explorer-insert-snippet-menu-item"
- >
- <BetweenHorizontalStartIcon className={MENU_ITEM_ICON_CLASS} />
- Insert snippet for reading file
- </DropdownMenuItem>
- <DropdownMenuItem
- onSelect={async () => {
- toast({
- title: "Copied to clipboard",
- description:
- "Code to open the file has been copied to your clipboard. You can also drag and drop this file into the editor",
- });
- const { path } = node.data;
- const pythonCode = PYTHON_CODE_FOR_FILE_TYPE[fileType](path);
- await copyToClipboard(pythonCode);
- }}
- data-testid="file-explorer-copy-snippet-menu-item"
- >
- <BracesIcon className={MENU_ITEM_ICON_CLASS} />
- Copy snippet for reading file
- </DropdownMenuItem>
- {node.data.isMarimoFile && !isWasm() && (
+ {!node.data.isRoot && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => {
+ const { path } = node.data;
+ const pythonCode = PYTHON_CODE_FOR_FILE_TYPE[fileType](path);
+ handleInsertCode(pythonCode);
+ }}
+ data-testid="file-explorer-insert-snippet-menu-item"
+ >
+ <BetweenHorizontalStartIcon className={MENU_ITEM_ICON_CLASS} />
+ Insert snippet for reading file
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onSelect={async () => {
+ toast({
+ title: "Copied to clipboard",
+ description:
+ "Code to open the file has been copied to your clipboard. You can also drag and drop this file into the editor",
+ });
+ const { path } = node.data;
+ const pythonCode = PYTHON_CODE_FOR_FILE_TYPE[fileType](path);
+ await copyToClipboard(pythonCode);
+ }}
+ data-testid="file-explorer-copy-snippet-menu-item"
+ >
+ <BracesIcon className={MENU_ITEM_ICON_CLASS} />
+ Copy snippet for reading file
+ </DropdownMenuItem>
+ </>
+ )}
+ {node.data.isMarimoFile && node.data.isPrimaryRoot && !isWasm() && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
@@ -721,9 +760,9 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
</DropdownMenuItem>
</>
)}
- <DropdownMenuSeparator />
{!node.data.isDirectory && !disableFileDownloads && (
<>
+ <DropdownMenuSeparator />
<DropdownMenuItem
onSelect={async () => {
await downloadFile(node.data.path, node.data.name);
@@ -733,20 +772,24 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
<DownloadIcon className={MENU_ITEM_ICON_CLASS} />
Download
</DropdownMenuItem>
+ </>
+ )}
+ {!node.data.isRoot && (
+ <>
<DropdownMenuSeparator />
+ <DeleteMenuItem
+ onSelect={handleDeleteFile}
+ testId="file-explorer-delete-menu-item"
+ />
</>
)}
- <DeleteMenuItem
- onSelect={handleDeleteFile}
- testId="file-explorer-delete-menu-item"
- />
</FileActionsDropdown>
</span>
</div>
);
};
-const FolderArrow = ({ node }: { node: NodeApi<FileInfo> }) => {
+const FolderArrow = ({ node }: { node: NodeApi<FileTreeNode> }) => {
if (!node.data.isDirectory) {
return <span className="w-4 h-4 shrink-0" />;
}
@@ -767,23 +810,20 @@ export function getUploadDestinationLabel(
tree: RequestingTree,
destinationPath: FilePath,
): string {
- if (destinationPath === tree.getRootPath()) {
- return "workspace root";
- }
- return tree.relativeFromRoot(destinationPath);
+ return tree.getDisplayPath(destinationPath);
}
export function filterHiddenTree(
- list: FileInfo[],
+ list: FileTreeNode[],
showHidden: boolean,
-): FileInfo[] {
+): FileTreeNode[] {
if (showHidden) {
return list;
}
- const out: FileInfo[] = [];
+ const out: FileTreeNode[] = [];
for (const item of list) {
- if (isDirectoryOrFileHidden(item.name)) {
+ if (!item.isRoot && isDirectoryOrFileHidden(item.name)) {
continue;
}
let next = item;
@@ -805,10 +845,10 @@ export function isDirectoryOrFileHidden(filename: string): boolean {
return false;
}
-function treeContainsPath(list: FileInfo[], path: FilePath): boolean {
+function treeContainsId(list: FileTreeNode[], id: string): boolean {
return list.some(
(item) =>
- item.path === path ||
- (item.children ? treeContainsPath(item.children, path) : false),
+ item.id === id ||
+ (item.children ? treeContainsId(item.children, id) : false),
);
}
diff --git a/frontend/src/components/editor/file-tree/file-name-input.tsx b/frontend/src/components/editor/file-tree/file-name-input.tsx
index 7c672b2ea6..4804be085f 100644
--- a/frontend/src/components/editor/file-tree/file-name-input.tsx
+++ b/frontend/src/components/editor/file-tree/file-name-input.tsx
@@ -9,7 +9,11 @@ import type { FileInfo } from "@/core/network/types";
* is true. Auto-focuses and selects everything except the extension so a
* user can type straight into the name.
*/
-export const FileNameInput = ({ node }: { node: NodeApi<FileInfo> }) => {
+export const FileNameInput = <T extends FileInfo>({
+ node,
+}: {
+ node: NodeApi<T>;
+}) => {
const ref = useRef<HTMLInputElement>(null);
useEffect(() => {
ref.current?.focus();
diff --git a/frontend/src/components/editor/file-tree/file-viewer.tsx b/frontend/src/components/editor/file-tree/file-viewer.tsx
index ee8a382bbe..40e72e8028 100644
--- a/frontend/src/components/editor/file-tree/file-viewer.tsx
+++ b/frontend/src/components/editor/file-tree/file-viewer.tsx
@@ -32,7 +32,7 @@ export const MAX_FILE_PREVIEW_BYTES = 10 * 1024 * 1024;
interface Props {
file: FileInfo;
- onOpenNotebook: (
+ onOpenNotebook?: (
evt: Pick<Event, "stopPropagation" | "preventDefault">,
) => void;
}
@@ -156,7 +156,7 @@ export const FileViewer: React.FC<Props> = ({ file, onOpenNotebook }) => {
onDownload={disableFileDownloads ? undefined : handleDownload}
actions={
<>
- {file.isMarimoFile && !isWasm() && (
+ {file.isMarimoFile && onOpenNotebook && !isWasm() && (
<Tooltip content="Open notebook">
<Button
variant="text"
diff --git a/frontend/src/components/editor/file-tree/requesting-tree.tsx b/frontend/src/components/editor/file-tree/requesting-tree.tsx
index afe18299f3..6e75e89169 100644
--- a/frontend/src/components/editor/file-tree/requesting-tree.tsx
+++ b/frontend/src/components/editor/file-tree/requesting-tree.tsx
@@ -5,15 +5,24 @@ import { toast } from "@/components/ui/use-toast";
import type {
EditRequests,
FileInfo,
+ FileRoot,
FileUpdateResponse,
} from "@/core/network/types";
import { prettyError } from "@/utils/errors";
import { Functions } from "@/utils/functions";
import { type FilePath, PathBuilder } from "@/utils/paths";
-import { resolvePaths } from "@/utils/pathUtils";
import { mapWithConcurrency } from "@/utils/semaphore";
const FILE_OP_CONCURRENCY = 5;
+const WINDOWS_DRIVE_PATH = /^[A-Za-z]:[/\\]/;
+const WINDOWS_UNC_PATH = /^\\\\/;
+
+export type FileTreeNode = Omit<FileInfo, "children"> & {
+ children: FileTreeNode[];
+ isRoot: boolean;
+ rootPath: string;
+ isPrimaryRoot: boolean;
+};
/**
* Normalized result of a file mutation: the server response when successful,
@@ -35,8 +44,9 @@ export function handleFileResponse(
}
export class RequestingTree {
- private delegate = new SimpleTree<FileInfo>([]);
- private callbacks: {
+ private delegate = new SimpleTree<FileTreeNode>([]);
+ private readonly callbacks: {
+ getRoots: EditRequests["getFileRoots"];
listFiles: EditRequests["sendListFiles"];
createFileOrFolder: EditRequests["sendCreateFileOrFolder"];
deleteFileOrFolder: EditRequests["sendDeleteFileOrFolder"];
@@ -45,6 +55,7 @@ export class RequestingTree {
};
constructor(callbacks: {
+ getRoots: EditRequests["getFileRoots"];
listFiles: EditRequests["sendListFiles"];
createFileOrFolder: EditRequests["sendCreateFileOrFolder"];
deleteFileOrFolder: EditRequests["sendDeleteFileOrFolder"];
@@ -54,18 +65,35 @@ export class RequestingTree {
this.callbacks = callbacks;
}
- private rootPath: FilePath = "" as FilePath;
- private onChange: (data: FileInfo[]) => void = Functions.NOOP;
+ private roots: FileRoot[] = [];
+ private onChange: (data: FileTreeNode[]) => void = Functions.NOOP;
private path = new PathBuilder("/");
- initialize = async (onChange: (data: FileInfo[]) => void): Promise<void> => {
+ initialize = async (
+ onChange: (data: FileTreeNode[]) => void,
+ ): Promise<void> => {
this.onChange = onChange;
if (this.delegate.data.length === 0) {
try {
- const data = await this.callbacks.listFiles({ path: this.rootPath });
- this.delegate = new SimpleTree(data.files);
- this.rootPath = data.root as FilePath;
- this.path = PathBuilder.guessDeliminator(data.root);
+ const { roots } = await this.callbacks.getRoots();
+ const primaryRoot = roots.find((root) => root.isPrimary);
+ if (!primaryRoot) {
+ throw new Error("File browser response is missing a primary root");
+ }
+ this.roots = roots;
+ this.path = PathBuilder.guessDeliminator(primaryRoot.path);
+ this.delegate = new SimpleTree(roots.map(toRootNode));
+ if (roots.length === 1) {
+ const data = await this.callbacks.listFiles({
+ path: primaryRoot.path,
+ });
+ this.delegate.update({
+ id: this.getPrimaryRootId(),
+ changes: {
+ children: annotateFiles(data.files, primaryRoot),
+ },
+ });
+ }
} catch (error) {
toast({
title: "Failed",
@@ -74,119 +102,91 @@ export class RequestingTree {
}
}
- this.onChange(this.delegate.data);
+ this.emitChange();
};
async expand(id: string): Promise<boolean> {
const node = this.delegate.find(id);
- if (!node) {
- return false;
- }
- if (!node.data.isDirectory) {
+ if (!node?.data.isDirectory) {
return false;
}
- // We may attempt to load empty directories multiple times
- // but that is fine
if (node.children && node.children.length > 0) {
- // Already loaded
return true;
}
const data = await this.callbacks.listFiles({ path: node.data.path });
- this.delegate.update({ id, changes: { children: data.files } });
- this.onChange(this.delegate.data);
+ this.delegate.update({
+ id,
+ changes: {
+ children: annotateFiles(data.files, this.getRootForNode(node.data)),
+ },
+ });
+ this.emitChange();
return true;
}
async copy(id: string, newName: string): Promise<void> {
- const node = this.delegate.find(id);
+ const node = this.getMutableNode(id);
if (!node) {
- toast({
- title: "Failed",
- description: `Node with id ${id} not found in the tree`,
- });
return;
}
- const { path, newPath } = resolvePaths({
- path: node.data.path,
- name: newName,
- root: this.rootPath,
- });
- const parentPath = this.path.dirname(path);
- const newFile = await this.callbacks
+ const path = node.data.path as FilePath;
+ const parentPath = this.getParentPath(node.data);
+ const newPath = joinPath(parentPath, newName);
+ const result = await this.callbacks
.copyFileOrFolder({ path, newPath })
.then(handleFileResponse);
- if (!newFile?.info) {
- return;
+ if (result) {
+ await this.refreshPath(parentPath);
}
- this.delegate.create({
- parentId: node.parent?.id ?? null,
- index: 0,
- data: newFile.info,
- });
- this.onChange(this.delegate.data);
- // Refresh the parent folder
- await this.refreshAll([parentPath]);
}
async rename(id: string, name: string): Promise<void> {
- const node = this.delegate.find(id);
+ const node = this.getMutableNode(id);
if (!node) {
- toast({
- title: "Failed",
- description: `Node with id ${id} not found in the tree`,
- });
return;
}
- const { path, newPath } = resolvePaths({
- path: node.data.path,
- name,
- root: this.rootPath,
- });
+ const path = node.data.path as FilePath;
+ const parentPath = this.getParentPath(node.data);
+ const newPath = joinPath(parentPath, name);
const result = await this.callbacks
.renameFileOrFolder({ path, newPath })
.then(handleFileResponse);
- if (!result) {
- return;
+ if (result) {
+ await this.refreshPath(parentPath);
}
-
- this.delegate.update({ id, changes: { name, path: newPath } });
- this.onChange(this.delegate.data);
- // Rename all of its children
- await this.refreshAll([newPath]);
}
async move(fromIds: string[], parentId: string | null): Promise<void> {
- const parentPath = parentId
- ? (this.delegate.find(parentId)?.data.path ?? parentId)
- : this.rootPath;
+ const targetParentId = parentId ?? this.getPrimaryRootId();
+ const parent = this.delegate.find(targetParentId);
+ if (!parent?.data.isDirectory) {
+ return;
+ }
+ const refreshPaths = new Set<string>();
await mapWithConcurrency(fromIds, FILE_OP_CONCURRENCY, async (id) => {
- const node = this.delegate.find(id);
+ const node = this.getMutableNode(id, false);
if (!node) {
return;
}
const originalPath = node.data.path;
- const newPath = this.path.join(
- parentPath,
+ const sourceParentPath = this.getParentPath(node.data);
+ const newPath = joinPath(
+ parent.data.path,
this.path.basename(originalPath as FilePath),
);
const result = await this.callbacks
.renameFileOrFolder({ path: originalPath, newPath })
.then(handleFileResponse);
- if (!result) {
- return;
+ if (result) {
+ refreshPaths.add(parent.data.path);
+ refreshPaths.add(sourceParentPath);
}
-
- this.delegate.move({ id, parentId, index: 0 });
- this.delegate.update({ id, changes: { path: newPath } });
});
- this.onChange(this.delegate.data);
-
- // Refresh the parent folder
- await this.refreshAll([parentPath]);
+ await this.refreshPaths([...refreshPaths]);
}
async createFile({
@@ -198,140 +198,260 @@ export class RequestingTree {
parentId: string | null;
type?: "file" | "notebook";
}): Promise<void> {
- const parentPath = parentId
- ? (this.delegate.find(parentId)?.data.path ?? parentId)
- : this.rootPath;
- const newFile = await this.callbacks
- .createFileOrFolder({ path: parentPath, type: type, name: name })
- .then(handleFileResponse);
- if (!newFile?.info) {
+ const parent = this.getParentNode(parentId);
+ if (!parent) {
return;
}
- this.delegate.create({
- parentId,
- index: 0,
- data: newFile.info,
- });
- this.onChange(this.delegate.data);
- // Refresh the parent folder
- await this.refreshAll([parentPath]);
+ const result = await this.callbacks
+ .createFileOrFolder({
+ path: parent.data.path,
+ type,
+ name,
+ })
+ .then(handleFileResponse);
+ if (result) {
+ await this.refreshPath(parent.data.path as FilePath);
+ }
}
async createFolder(name: string, parentId: string | null): Promise<void> {
- const parentPath = parentId
- ? (this.delegate.find(parentId)?.data.path ?? parentId)
- : this.rootPath;
- const newFolder = await this.callbacks
- .createFileOrFolder({ path: parentPath, type: "directory", name: name })
- .then(handleFileResponse);
- if (!newFolder?.info) {
+ const parent = this.getParentNode(parentId);
+ if (!parent) {
return;
}
- this.delegate.create({
- parentId,
- index: 0,
- data: newFolder.info,
- });
- this.onChange(this.delegate.data);
- // Refresh the parent folder
- await this.refreshAll([parentPath]);
+ const result = await this.callbacks
+ .createFileOrFolder({
+ path: parent.data.path,
+ type: "directory",
+ name,
+ })
+ .then(handleFileResponse);
+ if (result) {
+ await this.refreshPath(parent.data.path as FilePath);
+ }
}
async delete(id: string): Promise<void> {
- const node = this.delegate.find(id);
+ const node = this.getMutableNode(id);
if (!node) {
- toast({
- title: "Failed",
- description: `Node with id ${id} not found in the tree`,
- });
return;
}
-
+ const parentPath = this.getParentPath(node.data);
const result = await this.callbacks
.deleteFileOrFolder({ path: node.data.path })
.then(handleFileResponse);
- if (!result) {
- return;
+ if (result) {
+ await this.refreshPath(parentPath);
}
- this.delegate.drop({ id });
- this.onChange(this.delegate.data);
}
refreshAll = async (ids: string[]): Promise<void> => {
- // For each open folder, refresh
- const openFolders = [
- this.rootPath,
- ...ids.map((id) => this.delegate.find(id)?.data.path),
- ].filter(Boolean);
- // Request open folders with bounded concurrency; swallow per-folder errors.
- const data = await mapWithConcurrency(
- openFolders,
- FILE_OP_CONCURRENCY,
- (path) =>
- this.callbacks.listFiles({ path: path }).catch(() => ({ files: [] })),
+ const paths = [
+ ...this.roots.map((root) => root.path),
+ ...ids
+ .map((id) => this.delegate.find(id)?.data.path)
+ .filter((path): path is string => Boolean(path)),
+ ];
+ await this.refreshPaths(paths);
+ };
+
+ refreshPath = async (path: FilePath): Promise<void> => {
+ await this.refreshPaths([path]);
+ };
+
+ public getPrimaryRelativePath = (path: FilePath): FilePath | null => {
+ const primaryRoot = this.getPrimaryRoot();
+ if (!primaryRoot) {
+ return null;
+ }
+ return relativePath(path, primaryRoot.path);
+ };
+
+ public getPrimaryRootPath = (): FilePath => {
+ return (this.getPrimaryRoot()?.path ?? "") as FilePath;
+ };
+
+ public getPrimaryRootId = (): string => {
+ const path = this.getPrimaryRoot()?.path ?? "";
+ return fileTreeNodeId(path, path);
+ };
+
+ public isPrimaryNode = (node: FileTreeNode): boolean => {
+ return node.isPrimaryRoot;
+ };
+
+ public getDisplayPath = (path: FilePath): string => {
+ const root = this.getRootForPath(path);
+ if (!root) {
+ return path;
+ }
+ const relative = relativePath(path, root.path);
+ if (!relative) {
+ return root.name;
+ }
+ return root.isPrimary ? relative : `${root.name}/${relative}`;
+ };
+
+ public isRootPath = (path: FilePath): boolean => {
+ return this.roots.some((root) => pathsEqual(path, root.path));
+ };
+
+ private getPrimaryRoot(): FileRoot | undefined {
+ return this.roots.find((root) => root.isPrimary);
+ }
+
+ private getRootForNode(node: FileTreeNode): FileRoot {
+ return (
+ this.roots.find((root) => pathsEqual(root.path, node.rootPath)) ??
+ this.getPrimaryRoot() ?? {
+ path: node.rootPath,
+ name: node.rootPath,
+ isPrimary: node.isPrimaryRoot,
+ }
);
+ }
- for (const [idx, openFolder] of openFolders.entries()) {
- const datum = data[idx];
- if (openFolder === this.rootPath) {
- this.delegate = new SimpleTree(datum.files);
- } else {
- this.delegate.update({
- id: openFolder,
- changes: { children: datum.files },
+ private getRootForPath(path: FilePath): FileRoot | undefined {
+ return this.roots
+ .filter((root) => relativePath(path, root.path) !== null)
+ .toSorted((left, right) => right.path.length - left.path.length)[0];
+ }
+
+ private getParentNode(parentId: string | null) {
+ const resolvedId = parentId ?? this.getPrimaryRootId();
+ const node = this.delegate.find(resolvedId);
+ return node?.data.isDirectory ? node : null;
+ }
+
+ private getParentPath(node: FileTreeNode): FilePath {
+ const parent = this.delegate.find(node.id)?.parent;
+ return (parent?.data.path ?? node.rootPath) as FilePath;
+ }
+
+ private getMutableNode(id: string, showError = true) {
+ const node = this.delegate.find(id);
+ if (!node || node.data.isRoot) {
+ if (showError) {
+ toast({
+ title: "Failed",
+ description: node
+ ? "File browser roots cannot be modified"
+ : `Node with id ${id} not found in the tree`,
});
}
+ return null;
}
+ return node;
+ }
- this.onChange(this.delegate.data);
- };
-
- refreshPath = async (path: FilePath): Promise<void> => {
- const data = await this.callbacks.listFiles({ path }).catch(() => null);
- if (!data) {
+ private refreshPaths = async (paths: string[]): Promise<void> => {
+ const uniquePaths = [...new Set(paths)];
+ if (uniquePaths.length === 0) {
return;
}
+ const results = await mapWithConcurrency(
+ uniquePaths,
+ FILE_OP_CONCURRENCY,
+ (path) => this.callbacks.listFiles({ path }).catch(() => null),
+ );
- if (path === this.rootPath) {
- this.delegate = new SimpleTree(data.files);
- } else {
- const item = findFileByPath(this.delegate.data, path);
- if (!item?.isDirectory) {
- return;
+ for (const [index, path] of uniquePaths.entries()) {
+ const result = results[index];
+ 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.
+ for (const root of this.roots) {
+ const node = this.delegate.find(fileTreeNodeId(root.path, path));
+ if (!node?.data.isDirectory) {
+ continue;
+ }
+ this.delegate.update({
+ id: node.id,
+ changes: {
+ children: annotateFiles(result.files, root),
+ },
+ });
}
- this.delegate.update({ id: item.id, changes: { children: data.files } });
}
- this.onChange(this.delegate.data);
+ this.emitChange();
};
- public relativeFromRoot = (path: FilePath): FilePath => {
- // Add a trailing delimiter to the root path if it doesn't have one
- const root = this.rootPath.endsWith(this.path.deliminator)
- ? this.rootPath
- : `${this.rootPath}${this.path.deliminator}`;
+ private emitChange(): void {
+ const data = this.delegate.data;
+ this.onChange(this.roots.length === 1 ? (data[0]?.children ?? []) : data);
+ }
+}
- if (path.startsWith(root)) {
- return path.slice(root.length) as FilePath;
- }
- return path;
+function toRootNode(root: FileRoot): FileTreeNode {
+ return {
+ id: fileTreeNodeId(root.path, root.path),
+ path: root.path,
+ name: root.name,
+ isDirectory: true,
+ isMarimoFile: false,
+ children: [],
+ isRoot: true,
+ rootPath: root.path,
+ isPrimaryRoot: root.isPrimary,
};
+}
- public getRootPath = (): FilePath => {
- return this.rootPath;
- };
+function annotateFiles(files: FileInfo[], root: FileRoot): FileTreeNode[] {
+ return files.map((file) => ({
+ ...file,
+ id: fileTreeNodeId(root.path, file.path),
+ children: annotateFiles(file.children ?? [], root),
+ isRoot: false,
+ rootPath: root.path,
+ isPrimaryRoot: root.isPrimary,
+ }));
}
-function findFileByPath(list: FileInfo[], path: string): FileInfo | undefined {
- for (const item of list) {
- if (item.path === path) {
- return item;
- }
- const child = item.children
- ? findFileByPath(item.children, path)
- : undefined;
- if (child) {
- return child;
- }
+/** A stable, globally unique tree ID for a path as viewed from one root. */
+export function fileTreeNodeId(rootPath: string, path: string): string {
+ return `${encodeURIComponent(rootPath)}:${encodeURIComponent(path)}`;
+}
+
+function relativePath(path: string, root: string): FilePath | null {
+ const windowsPath = isWindowsPath(root);
+ const normalizeCase = (value: string) =>
+ windowsPath ? value.toLowerCase() : value;
+ const comparedPath = normalizeCase(path);
+ const comparedRoot = normalizeCase(root);
+ if (comparedPath === comparedRoot) {
+ return "" as FilePath;
+ }
+
+ const delimiter = pathDelimiter(root);
+ const rootWithDelimiter = root.endsWith(delimiter)
+ ? root
+ : `${root}${delimiter}`;
+ const comparedPrefix = normalizeCase(rootWithDelimiter);
+ if (!comparedPath.startsWith(comparedPrefix)) {
+ return null;
+ }
+ return path.slice(rootWithDelimiter.length) as FilePath;
+}
+
+function pathsEqual(left: string, right: string): boolean {
+ return relativePath(left, right) === ("" as FilePath);
+}
+
+function joinPath(parent: string, name: string): FilePath {
+ const delimiter = pathDelimiter(parent);
+ return `${parent}${parent.endsWith(delimiter) ? "" : delimiter}${name}` as FilePath;
+}
+
+function isWindowsPath(path: string): boolean {
+ return WINDOWS_DRIVE_PATH.test(path) || WINDOWS_UNC_PATH.test(path);
+}
+
+function pathDelimiter(path: string): "/" | "\\" {
+ if (WINDOWS_UNC_PATH.test(path) || /^[A-Za-z]:\\/.test(path)) {
+ return "\\";
}
- return undefined;
+ return "/";
}
diff --git a/frontend/src/components/editor/file-tree/state.tsx b/frontend/src/components/editor/file-tree/state.tsx
index 0862415000..d2a4edff78 100644
--- a/frontend/src/components/editor/file-tree/state.tsx
+++ b/frontend/src/components/editor/file-tree/state.tsx
@@ -11,6 +11,7 @@ export const treeAtom = atom<RequestingTree>((get) => {
const client = get(requestClientAtom);
invariant(client, "no requestClientAtom set");
return new RequestingTree({
+ getRoots: client.getFileRoots,
listFiles: client.sendListFiles,
createFileOrFolder: client.sendCreateFileOrFolder,
deleteFileOrFolder: client.sendDeleteFileOrFolder,
diff --git a/frontend/src/core/config/__tests__/config-schema.test.ts b/frontend/src/core/config/__tests__/config-schema.test.ts
index cac08c3f2c..0ba002824c 100644
--- a/frontend/src/core/config/__tests__/config-schema.test.ts
+++ b/frontend/src/core/config/__tests__/config-schema.test.ts
@@ -77,6 +77,7 @@ test("default UserConfig - empty", () => {
"theme": "light",
},
"experimental": {},
+ "file_browser": {},
"formatting": {
"line_length": 79,
},
@@ -152,6 +153,7 @@ test("default UserConfig - one level", () => {
"theme": "light",
},
"experimental": {},
+ "file_browser": {},
"formatting": {
"line_length": 79,
},
@@ -212,6 +214,19 @@ test("default UserConfig with additional information", () => {
);
});
+test("UserConfig with file browser folders", () => {
+ const config = UserConfigSchema.parse({
+ file_browser: {
+ folders: [{ path: "/data", name: "Data" }, { path: "/shared" }],
+ },
+ });
+
+ expect(config.file_browser?.folders).toEqual([
+ { path: "/data", name: "Data" },
+ { path: "/shared" },
+ ]);
+});
+
test("UserConfig with custom_providers", () => {
const config = UserConfigSchema.parse({
ai: {
diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.ts
index b75af26b69..350cbde940 100644
--- a/frontend/src/core/config/config-schema.ts
+++ b/frontend/src/core/config/config-schema.ts
@@ -214,6 +214,19 @@ export const UserConfigSchema = z
sql_linter: z.boolean().optional(),
})
.prefault(() => ({})),
+ file_browser: z
+ .looseObject({
+ folders: z
+ .array(
+ z.object({
+ path: z.string(),
+ name: z.string().optional(),
+ }),
+ )
+ .optional(),
+ })
+ .optional()
+ .prefault({}),
sharing: z
.looseObject({
html: z.boolean().optional(),
@@ -237,6 +250,7 @@ export const UserConfigSchema = z
runtime: {},
display: {},
diagnostics: {},
+ file_browser: {},
experimental: {},
server: {},
ai: {},
@@ -341,6 +355,7 @@ export function defaultUserConfig(): UserConfig {
runtime: {},
display: {},
diagnostics: {},
+ file_browser: {},
experimental: {},
server: {},
ai: {},
diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.ts
index 38eddcb1d8..6830a8b2be 100644
--- a/frontend/src/core/islands/bridge.ts
+++ b/frontend/src/core/islands/bridge.ts
@@ -344,6 +344,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
discoverDataSources = throwNotImplemented;
validateSQL = throwNotImplemented;
openFile = throwNotImplemented;
+ getFileRoots = throwNotImplemented;
sendListFiles = throwNotImplemented;
sendSearchFiles = throwNotImplemented;
sendPdb = throwNotImplemented;
diff --git a/frontend/src/core/network/__tests__/requests-network.test.ts b/frontend/src/core/network/__tests__/requests-network.test.ts
index 0806eccb9a..81ceac652d 100644
--- a/frontend/src/core/network/__tests__/requests-network.test.ts
+++ b/frontend/src/core/network/__tests__/requests-network.test.ts
@@ -136,6 +136,13 @@ describe("createNetworkRequests", () => {
expect(mockClient.GET).toHaveBeenCalledWith("/api/environment");
});
+ it("getFileRoots should GET /api/files/roots", async () => {
+ const requests = createNetworkRequests();
+ await requests.getFileRoots();
+
+ expect(mockClient.GET).toHaveBeenCalledWith("/api/files/roots");
+ });
+
it("getExportAvailability should GET /api/export/availability", async () => {
const requests = createNetworkRequests();
await requests.getExportAvailability();
diff --git a/frontend/src/core/network/__tests__/requests-toasting.test.tsx b/frontend/src/core/network/__tests__/requests-toasting.test.tsx
index 713b50550b..8bb7581188 100644
--- a/frontend/src/core/network/__tests__/requests-toasting.test.tsx
+++ b/frontend/src/core/network/__tests__/requests-toasting.test.tsx
@@ -43,4 +43,14 @@ describe("createErrorToastingRequests", () => {
expect.objectContaining({ variant: "danger" }),
);
});
+
+ it("leaves file-root errors for the requesting tree to surface", async () => {
+ const error = new Error("Failed to load roots");
+ const requests = createErrorToastingRequests({
+ getFileRoots: vi.fn().mockRejectedValue(error),
+ } as unknown as EditRequests & RunRequests);
+
+ await expect(requests.getFileRoots()).rejects.toBe(error);
+ expect(toastMock).not.toHaveBeenCalled();
+ });
});
diff --git a/frontend/src/core/network/requests-lazy.ts b/frontend/src/core/network/requests-lazy.ts
index 0ee57ea922..8a30594d18 100644
--- a/frontend/src/core/network/requests-lazy.ts
+++ b/frontend/src/core/network/requests-lazy.ts
@@ -98,6 +98,7 @@ const ACTIONS: Record<keyof AllRequests, Action> = {
removePackage: "throwError",
// Folder and file operations throw errors
+ getFileRoots: "startConnection",
sendListFiles: "startConnection",
sendSearchFiles: "startConnection",
sendCreateFileOrFolder: "throwError",
diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.ts
index 4d6dd37d8b..47de80a1de 100644
--- a/frontend/src/core/network/requests-network.ts
+++ b/frontend/src/core/network/requests-network.ts
@@ -319,6 +319,10 @@ export function createNetworkRequests(): EditRequests & RunRequests {
})
.then(handleResponseReturnNull);
},
+ getFileRoots: async () => {
+ await waitForConnectionOpen();
+ return getClient().GET("/api/files/roots").then(handleResponse);
+ },
sendListFiles: async (request) => {
await waitForConnectionOpen();
return getClient()
diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.ts
index e1343b2880..901f08d268 100644
--- a/frontend/src/core/network/requests-static.ts
+++ b/frontend/src/core/network/requests-static.ts
@@ -67,6 +67,7 @@ export function createStaticRequests(): EditRequests & RunRequests {
openFile: throwNotInEditMode,
getUsageStats: throwNotInEditMode,
getEnvironmentInfo: throwNotInEditMode,
+ getFileRoots: throwNotInEditMode,
sendListFiles: throwNotInEditMode,
sendSearchFiles: throwNotInEditMode,
sendPdb: throwNotInEditMode,
diff --git a/frontend/src/core/network/requests-toasting.tsx b/frontend/src/core/network/requests-toasting.tsx
index a16f8997c1..5527423319 100644
--- a/frontend/src/core/network/requests-toasting.tsx
+++ b/frontend/src/core/network/requests-toasting.tsx
@@ -48,6 +48,7 @@ export function createErrorToastingRequests(
openFile: "Failed to open file",
getUsageStats: "", // No toast
getEnvironmentInfo: "", // No toast
+ getFileRoots: "", // RequestingTree surfaces this error
sendListFiles: "Failed to list files",
sendSearchFiles: "Failed to search files",
sendPdb: "Failed to start debug session",
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index 595ec371be..4cb233d666 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -50,6 +50,8 @@ export type FileDetailsResponse = schemas["FileDetailsResponse"];
export type FileInfo = schemas["FileInfo"];
export type FileListRequest = schemas["FileListRequest"];
export type FileListResponse = schemas["FileListResponse"];
+export type FileRoot = schemas["FileRoot"];
+export type FileRootsResponse = schemas["FileRootsResponse"];
export type FileSearchRequest = schemas["FileSearchRequest"];
export type FileSearchResponse = schemas["FileSearchResponse"];
export type FileMoveRequest = schemas["FileMoveRequest"];
@@ -197,6 +199,7 @@ export interface EditRequests {
sendPdb: (request: DebugCellRequest) => Promise<null>;
sendSetBreakpoints: (request: SetBreakpointsRequest) => Promise<null>;
// File explorer requests
+ getFileRoots: () => Promise<FileRootsResponse>;
sendListFiles: (request: FileListRequest) => Promise<FileListResponse>;
sendSearchFiles: (request: FileSearchRequest) => Promise<FileSearchResponse>;
sendCreateFileOrFolder: (
diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.ts
index ebb9a55358..8a053f3f81 100644
--- a/frontend/src/core/wasm/bridge.ts
+++ b/frontend/src/core/wasm/bridge.ts
@@ -26,6 +26,7 @@ import type {
FileDeleteResponse,
FileDetailsResponse,
FileListResponse,
+ FileRootsResponse,
FileMoveResponse,
FileSearchResponse,
FileUpdateResponse,
@@ -419,6 +420,14 @@ export class PyodideBridge implements RunRequests, EditRequests {
return response as FileListResponse;
};
+ getFileRoots: EditRequests["getFileRoots"] = async () => {
+ const response = await this.rpc.proxy.request.bridge({
+ functionName: "file_roots",
+ payload: undefined,
+ });
+ return response as FileRootsResponse;
+ };
+
sendSearchFiles: EditRequests["sendSearchFiles"] = async (request) => {
const response = await this.rpc.proxy.request.bridge({
functionName: "search_files",
diff --git a/frontend/src/core/wasm/worker/types.ts b/frontend/src/core/wasm/worker/types.ts
index 1d37b2e434..c74d4e3f60 100644
--- a/frontend/src/core/wasm/worker/types.ts
+++ b/frontend/src/core/wasm/worker/types.ts
@@ -23,6 +23,7 @@ import type {
FileDetailsResponse,
FileListRequest,
FileListResponse,
+ FileRootsResponse,
FileMoveRequest,
FileMoveResponse,
FileSearchRequest,
@@ -84,6 +85,7 @@ export interface RawBridge {
save_user_config(request: SaveUserConfigurationRequest): Promise<null>;
rename_file(request: string): Promise<string>;
list_files(request: FileListRequest): Promise<FileListResponse>;
+ file_roots(): Promise<FileRootsResponse>;
search_files(request: FileSearchRequest): Promise<FileSearchResponse>;
file_details(request: { path: string }): Promise<FileDetailsResponse>;
create_file_or_directory(
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index eab1b62d07..88a9bb2d2c 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -339,6 +339,7 @@ def _generate_server_api_schema() -> dict[str, Any]:
home.MarimoFile,
opengraph.OpenGraphMetadata,
files.FileInfo,
+ files.FileRoot,
commands.ExecuteCellCommand,
snippets.SnippetSection,
snippets.Snippet,
@@ -371,6 +372,7 @@ def _generate_server_api_schema() -> dict[str, Any]:
files.FileDetailsResponse,
files.FileListRequest,
files.FileListResponse,
+ files.FileRootsResponse,
files.FileSearchRequest,
files.FileSearchResponse,
files.FileMoveRequest,
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index 3231f2214a..4aa5d76d0a 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -574,6 +574,32 @@ class DatasourcesConfig(TypedDict):
auto_discover_columns: NotRequired[bool | Literal["auto"]]
+@dataclass
+class FolderConfig(TypedDict):
+ """Configuration for an additional file browser root.
+
+ **Keys.**
+
+ - `path`: the absolute path to the folder
+ - `name`: an optional display name for the folder
+ """
+
+ path: str
+ name: NotRequired[str]
+
+
+@dataclass
+class FileBrowserConfig(TypedDict):
+ """Configuration for the file browser panel.
+
+ **Keys.**
+
+ - `folders`: additional absolute folders to show in the file browser
+ """
+
+ folders: NotRequired[list[FolderConfig]]
+
+
@mddoc
@dataclass
class SharingConfig(TypedDict):
@@ -673,6 +699,7 @@ class MarimoConfig(TypedDict):
experimental: NotRequired[ExperimentalConfigType]
snippets: NotRequired[SnippetsConfig]
datasources: NotRequired[DatasourcesConfig]
+ file_browser: NotRequired[FileBrowserConfig]
sharing: NotRequired[SharingConfig]
mcp: NotRequired[MCPConfig]
venv: NotRequired[VenvConfig]
@@ -743,6 +770,7 @@ class PartialMarimoConfig(TypedDict, total=False):
experimental: NotRequired[ExperimentalConfigType]
snippets: SnippetsConfig
datasources: NotRequired[DatasourcesConfig]
+ file_browser: NotRequired[FileBrowserConfig]
sharing: NotRequired[SharingConfig]
venv: NotRequired[VenvConfig]
cache: NotRequired[CacheConfig]
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index 982016e379..dbbbddc7ce 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -49,6 +49,7 @@ from marimo._schemas.export import (
to_markdown_export_options,
)
from marimo._server.files.os_file_system import OSFileSystem
+from marimo._server.files.roots import resolve_file_roots
from marimo._server.models.files import (
FileCopyRequest,
FileCopyResponse,
@@ -61,6 +62,7 @@ from marimo._server.models.files import (
FileListResponse,
FileMoveRequest,
FileMoveResponse,
+ FileRootsResponse,
FileSearchRequest,
FileSearchResponse,
FileUpdateRequest,
@@ -302,6 +304,13 @@ class PyodideBridge:
response = FileListResponse(files=files, root=root)
return self._dump(response)
+ def file_roots(self) -> str:
+ roots = resolve_file_roots(
+ self.file_system.get_root(),
+ self.session._initial_user_config.get("file_browser"),
+ )
+ return self._dump(FileRootsResponse(roots=roots))
+
def search_files(
self,
request: str,
diff --git a/marimo/_server/api/endpoints/file_explorer.py b/marimo/_server/api/endpoints/file_explorer.py
index 5b8ca31699..b94a7411a6 100644
--- a/marimo/_server/api/endpoints/file_explorer.py
+++ b/marimo/_server/api/endpoints/file_explorer.py
@@ -16,6 +16,7 @@ from marimo._server.files.os_file_system import (
OSFileSystem,
UploadTooLargeError,
)
+from marimo._server.files.roots import resolve_file_roots
from marimo._server.models.files import (
FileCopyRequest,
FileCopyResponse,
@@ -30,6 +31,7 @@ from marimo._server.models.files import (
FileMoveRequest,
FileMoveResponse,
FileOpenRequest,
+ FileRootsResponse,
FileSearchRequest,
FileSearchResponse,
FileUpdateRequest,
@@ -76,6 +78,28 @@ router = APIRouter()
file_system = OSFileSystem()
+@requires("edit")
+def file_roots(*, request: Request) -> FileRootsResponse:
+ """
+ responses:
+ 200:
+ description: List roots shown in the file browser
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/FileRootsResponse"
+ """
+ app_state = AppState(request)
+ primary_root = (
+ app_state.session_manager.workspace.directory or file_system.get_root()
+ )
+ config = app_state.config_manager.get_config().get("file_browser")
+ return FileRootsResponse(
+ roots=resolve_file_roots(primary_root, config),
+ )
+
+
@router.post("/list_files")
@requires("edit")
async def list_files(
diff --git a/marimo/_server/files/roots.py b/marimo/_server/files/roots.py
new file mode 100644
index 0000000000..c984224db0
--- /dev/null
+++ b/marimo/_server/files/roots.py
@@ -0,0 +1,103 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+from marimo import _loggers
+from marimo._config.config import FileBrowserConfig
+from marimo._server.models.files import FileRoot
+
+LOGGER = _loggers.marimo_logger()
+
+
+def resolve_file_roots(
+ primary_root: str,
+ config: FileBrowserConfig | None,
+) -> list[FileRoot]:
+ """Resolve the primary and configured roots for the file browser."""
+ primary_path = _normalize_primary_root(primary_root)
+ roots = [
+ FileRoot(
+ path=primary_path,
+ name=_default_root_name(primary_path),
+ is_primary=True,
+ )
+ ]
+ seen = {_deduplication_key(primary_path)}
+
+ if config is not None and not isinstance(config, dict):
+ _warn_invalid_root(config, "file_browser must be a table")
+ return roots
+ folders = (config or {}).get("folders", [])
+ if not isinstance(folders, list):
+ _warn_invalid_root(folders, "folders must be a list")
+ return roots
+
+ for folder in folders:
+ if not isinstance(folder, dict):
+ _warn_invalid_root(folder, "folder must be a table")
+ continue
+ path = folder.get("path")
+ if not isinstance(path, str) or not path:
+ _warn_invalid_root(path, "path must be a non-empty string")
+ continue
+
+ candidate = Path(path)
+ if not candidate.is_absolute():
+ _warn_invalid_root(path, "path must be absolute")
+ continue
+
+ try:
+ normalized = str(candidate.resolve(strict=True))
+ except FileNotFoundError:
+ _warn_invalid_root(path, "path does not exist")
+ continue
+ except (OSError, RuntimeError) as error:
+ _warn_invalid_root(path, str(error))
+ continue
+
+ if not Path(normalized).is_dir():
+ _warn_invalid_root(path, "path is not a directory")
+ continue
+ if not os.access(normalized, os.R_OK | os.X_OK):
+ _warn_invalid_root(path, "directory is not readable")
+ continue
+
+ key = _deduplication_key(normalized)
+ if key in seen:
+ _warn_invalid_root(path, "duplicate root")
+ continue
+ seen.add(key)
+
+ configured_name = folder.get("name")
+ name = (
+ configured_name.strip()
+ if isinstance(configured_name, str) and configured_name.strip()
+ else _default_root_name(normalized)
+ )
+ roots.append(FileRoot(path=normalized, name=name, is_primary=False))
+
+ return roots
+
+
+def _normalize_primary_root(path: str) -> str:
+ try:
+ return str(Path(path).resolve(strict=True))
+ except (OSError, RuntimeError):
+ # The existing browser root is authoritative even if it becomes
+ # unavailable after startup. Keep it visible so refreshes can recover.
+ return os.path.abspath(path)
+
+
+def _deduplication_key(path: str) -> str:
+ return os.path.normcase(os.path.normpath(path))
+
+
+def _default_root_name(path: str) -> str:
+ name = Path(path).name
+ return name or Path(path).anchor or path
+
+
+def _warn_invalid_root(path: object, reason: str) -> None:
+ LOGGER.warning("Ignoring file browser root %r: %s", path, reason)
diff --git a/marimo/_server/models/files.py b/marimo/_server/models/files.py
index 1397dfe985..ac1ede9289 100644
--- a/marimo/_server/models/files.py
+++ b/marimo/_server/models/files.py
@@ -23,6 +23,16 @@ class FileInfo(msgspec.Struct, rename="camel"):
opengraph: OpenGraphMetadata | None = None
+class FileRoot(msgspec.Struct, rename="camel"):
+ path: str
+ name: str
+ is_primary: bool
+
+
+class FileRootsResponse(msgspec.Struct, rename="camel"):
+ roots: list[FileRoot]
+
+
class FileListRequest(msgspec.Struct, rename="camel"):
# The directory path to list files from
# If None, the root directory will be used
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index fc8ffb1d8c..d70e8aa4fd 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -2057,6 +2057,17 @@ components:
- command
title: ExportSetupRequirement
type: object
+ FileBrowserConfig:
+ description: "Configuration for the file browser panel.\n\n **Keys.**\n\n\
+ \ - `folders`: additional absolute folders to show in the file browser"
+ properties:
+ folders:
+ items:
+ $ref: '#/components/schemas/FolderConfig'
+ type: array
+ required: []
+ title: FileBrowserConfig
+ type: object
FileCopyRequest:
properties:
newPath:
@@ -2317,6 +2328,30 @@ components:
- path
title: FileOpenRequest
type: object
+ FileRoot:
+ properties:
+ isPrimary:
+ type: boolean
+ name:
+ type: string
+ path:
+ type: string
+ required:
+ - path
+ - name
+ - isPrimary
+ title: FileRoot
+ type: object
+ FileRootsResponse:
+ properties:
+ roots:
+ items:
+ $ref: '#/components/schemas/FileRoot'
+ type: array
+ required:
+ - roots
+ title: FileRootsResponse
+ type: object
FileSearchRequest:
properties:
depth:
@@ -2409,6 +2444,19 @@ components:
- cellId
title: FocusCellRequest
type: object
+ FolderConfig:
+ description: "Configuration for an additional file browser root.\n\n **Keys.**\n\
+ \n - `path`: the absolute path to the folder\n - `name`: an optional\
+ \ display name for the folder"
+ properties:
+ name:
+ type: string
+ path:
+ type: string
+ required:
+ - path
+ title: FolderConfig
+ type: object
FormatCellsRequest:
properties:
codes:
@@ -3606,6 +3654,8 @@ components:
$ref: '#/components/schemas/DisplayConfig'
experimental:
type: object
+ file_browser:
+ $ref: '#/components/schemas/FileBrowserConfig'
formatting:
$ref: '#/components/schemas/FormattingConfig'
keymap:
@@ -7035,6 +7085,15 @@ paths:
schema:
$ref: '#/components/schemas/BaseResponse'
description: Open a file in the system editor
+ /api/files/roots:
+ get:
+ responses:
+ 200:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/FileRootsResponse'
+ description: List roots shown in the file browser
/api/files/search:
post:
requestBody:
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 17e9f757d0..33b22ff0e2 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -1593,6 +1593,41 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/api/files/roots": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description List roots shown in the file browser */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["FileRootsResponse"];
+ };
+ };
+ };
+ };
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/files/search": {
parameters: {
query?: never;
@@ -4921,6 +4956,17 @@ export interface components {
/** @enum {unknown} */
name: "playwright-chromium";
};
+ /**
+ * FileBrowserConfig
+ * @description Configuration for the file browser panel.
+ *
+ * **Keys.**
+ *
+ * - `folders`: additional absolute folders to show in the file browser
+ */
+ FileBrowserConfig: {
+ folders?: components["schemas"]["FolderConfig"][];
+ };
/** FileCopyRequest */
FileCopyRequest: {
newPath: string;
@@ -5044,6 +5090,16 @@ export interface components {
lineNumber?: number | null;
path: string;
};
+ /** FileRoot */
+ FileRoot: {
+ isPrimary: boolean;
+ name: string;
+ path: string;
+ };
+ /** FileRootsResponse */
+ FileRootsResponse: {
+ roots: components["schemas"]["FileRoot"][];
+ };
/** FileSearchRequest */
FileSearchRequest: {
/** @default 3 */
@@ -5093,6 +5149,19 @@ export interface components {
FocusCellRequest: {
cellId: components["schemas"]["CellId"];
};
+ /**
+ * FolderConfig
+ * @description Configuration for an additional file browser root.
+ *
+ * **Keys.**
+ *
+ * - `path`: the absolute path to the folder
+ * - `name`: an optional display name for the folder
+ */
+ FolderConfig: {
+ name?: string;
+ path: string;
+ };
/** FormatCellsRequest */
FormatCellsRequest: {
codes: {
@@ -5846,6 +5915,7 @@ export interface components {
diagnostics?: components["schemas"]["DiagnosticsConfig"];
display: components["schemas"]["DisplayConfig"];
experimental?: Record<string, any>;
+ file_browser?: components["schemas"]["FileBrowserConfig"];
formatting: components["schemas"]["FormattingConfig"];
keymap: components["schemas"]["KeymapConfig"];
language_servers?: components["schemas"]["LanguageServersConfig"];
diff --git a/tests/_config/test_config.py b/tests/_config/test_config.py
index 5e9fc215a8..7100726cef 100644
--- a/tests/_config/test_config.py
+++ b/tests/_config/test_config.py
@@ -32,6 +32,19 @@ def test_configure_partial_keymap() -> None:
)
+def test_configure_file_browser_folders() -> None:
+ assert_config(
+ PartialMarimoConfig(
+ file_browser={
+ "folders": [
+ {"path": "/data", "name": "Data"},
+ {"path": "/shared"},
+ ]
+ }
+ )
+ )
+
+
def test_configure_full() -> None:
assert_config(
PartialMarimoConfig(
diff --git a/tests/_config/test_manager.py b/tests/_config/test_manager.py
index f1e77c56ef..aff8c18e2d 100644
--- a/tests/_config/test_manager.py
+++ b/tests/_config/test_manager.py
@@ -434,6 +434,21 @@ def test_script_config_manager_with_metadata(tmp_path: Path) -> None:
}
+def test_script_config_manager_ignores_file_browser(tmp_path: Path) -> None:
+ notebook_path = tmp_path / "notebook.py"
+ notebook_content = """
+ # /// script
+ # [tool.marimo.file_browser]
+ # folders = [{path = "/private", name = "Private"}]
+ # ///
+ import marimo as mo
+ """
+ notebook_path.write_text(textwrap.dedent(notebook_content))
+
+ manager = ScriptConfigManager(str(notebook_path))
+ assert manager.get_config() == {}
+
+
def test_script_config_manager_invalid_toml(tmp_path: Path) -> None:
notebook_path = tmp_path / "notebook.py"
notebook_content = """
diff --git a/tests/_pyodide/test_pyodide_session.py b/tests/_pyodide/test_pyodide_session.py
index 3acf9409b4..3f3f290283 100644
--- a/tests/_pyodide/test_pyodide_session.py
+++ b/tests/_pyodide/test_pyodide_session.py
@@ -894,6 +894,43 @@ def test_pyodide_bridge_list_files(
assert response["root"] == str(tmp_path)
+def test_pyodide_bridge_file_roots(
+ pyodide_bridge: PyodideBridge,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Test listing configured file-browser roots through the bridge."""
+ primary = tmp_path / "project"
+ shared = tmp_path / "shared"
+ primary.mkdir()
+ shared.mkdir()
+ monkeypatch.setattr(
+ pyodide_bridge.file_system, "get_root", lambda: str(primary)
+ )
+ monkeypatch.setitem(
+ pyodide_bridge.session._initial_user_config,
+ "file_browser",
+ {"folders": [{"path": str(shared), "name": "Shared"}]},
+ )
+
+ response = json.loads(pyodide_bridge.file_roots())
+
+ assert response == {
+ "roots": [
+ {
+ "path": str(primary.resolve()),
+ "name": "project",
+ "isPrimary": True,
+ },
+ {
+ "path": str(shared.resolve()),
+ "name": "Shared",
+ "isPrimary": False,
+ },
+ ]
+ }
+
+
def test_pyodide_bridge_file_details(
pyodide_bridge: PyodideBridge,
tmp_path: Path,
diff --git a/tests/_server/api/endpoints/test_file_explorer.py b/tests/_server/api/endpoints/test_file_explorer.py
index 19ba921cdb..7919747f8b 100644
--- a/tests/_server/api/endpoints/test_file_explorer.py
+++ b/tests/_server/api/endpoints/test_file_explorer.py
@@ -9,7 +9,11 @@ from typing import TYPE_CHECKING, cast
import pytest
from marimo._utils.platform import is_windows
-from tests._server.mocks import get_session_manager, token_header
+from tests._server.mocks import (
+ get_session_manager,
+ token_header,
+ workspace_scope,
+)
if TYPE_CHECKING:
from starlette.testclient import TestClient
@@ -41,6 +45,74 @@ def test_list_files(client: TestClient) -> None:
assert "files" in response.json()
+def test_file_roots(
+ client: TestClient,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from marimo._config.manager import MarimoConfigManager
+ from marimo._server.api.endpoints.file_explorer import file_system
+
+ primary = tmp_path / "project"
+ shared = tmp_path / "shared"
+ primary.mkdir()
+ shared.mkdir()
+ monkeypatch.setattr(file_system, "get_root", lambda: str(primary))
+ config_manager = client.app.state.config_manager.with_overrides(
+ {
+ "file_browser": {
+ "folders": [{"path": str(shared), "name": "Shared"}]
+ }
+ }
+ )
+ assert isinstance(config_manager, MarimoConfigManager)
+ monkeypatch.setattr(client.app.state, "config_manager", config_manager)
+
+ response = client.get("/api/files/roots", headers=HEADERS)
+
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "roots": [
+ {
+ "path": str(primary.resolve()),
+ "name": "project",
+ "isPrimary": True,
+ },
+ {
+ "path": str(shared.resolve()),
+ "name": "Shared",
+ "isPrimary": False,
+ },
+ ]
+ }
+
+
+def test_file_roots_prefers_workspace_directory(
+ client: TestClient,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from marimo._server.api.endpoints.file_explorer import file_system
+ from marimo._server.workspace import DirectoryWorkspace
+
+ fallback = tmp_path / "fallback"
+ workspace_directory = tmp_path / "workspace"
+ fallback.mkdir()
+ workspace_directory.mkdir()
+ monkeypatch.setattr(file_system, "get_root", lambda: str(fallback))
+
+ workspace = DirectoryWorkspace(
+ str(workspace_directory), include_markdown=False
+ )
+ with workspace_scope(client, workspace):
+ response = client.get("/api/files/roots", headers=HEADERS)
+
+ assert response.status_code == 200, response.text
+ assert response.json()["roots"][0]["path"] == str(
+ workspace_directory.resolve()
+ )
+
+
def test_file_details(client: TestClient) -> None:
response = client.post(
"/api/files/file_details",
diff --git a/tests/_server/files/test_roots.py b/tests/_server/files/test_roots.py
new file mode 100644
index 0000000000..abac6bd188
--- /dev/null
+++ b/tests/_server/files/test_roots.py
@@ -0,0 +1,143 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+from unittest.mock import Mock
+
+import pytest
+
+from marimo._server.files.roots import resolve_file_roots
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+
+def test_resolve_file_roots_orders_and_names_roots(tmp_path: Path) -> None:
+ primary = tmp_path / "project"
+ shared = tmp_path / "shared"
+ unnamed = tmp_path / "unnamed"
+ primary.mkdir()
+ shared.mkdir()
+ unnamed.mkdir()
+
+ roots = resolve_file_roots(
+ str(primary),
+ {
+ "folders": [
+ {"path": str(shared), "name": "Shared data"},
+ {"path": str(unnamed)},
+ ]
+ },
+ )
+
+ assert [(root.path, root.name, root.is_primary) for root in roots] == [
+ (str(primary.resolve()), "project", True),
+ (str(shared.resolve()), "Shared data", False),
+ (str(unnamed.resolve()), "unnamed", False),
+ ]
+
+
+def test_resolve_file_roots_skips_invalid_and_duplicate_paths(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ primary = tmp_path / "project"
+ valid = tmp_path / "valid"
+ inaccessible = tmp_path / "inaccessible"
+ file_path = tmp_path / "file.txt"
+ primary.mkdir()
+ valid.mkdir()
+ inaccessible.mkdir()
+ file_path.write_text("not a directory")
+
+ real_access = __import__("os").access
+ monkeypatch.setattr(
+ "marimo._server.files.roots.os.access",
+ lambda path, mode: (
+ False
+ if path == str(inaccessible.resolve())
+ else real_access(path, mode)
+ ),
+ )
+ warning = Mock()
+ monkeypatch.setattr("marimo._server.files.roots.LOGGER.warning", warning)
+
+ roots = resolve_file_roots(
+ str(primary),
+ {
+ "folders": [
+ {"path": "relative"},
+ {"path": str(tmp_path / "missing")},
+ {"path": str(file_path)},
+ {"path": str(inaccessible)},
+ {"path": str(primary)},
+ {"path": str(valid)},
+ {"path": str(valid / ".." / "valid")},
+ ]
+ },
+ )
+
+ assert [root.path for root in roots] == [
+ str(primary.resolve()),
+ str(valid.resolve()),
+ ]
+ assert warning.call_count == 6
+
+
+def test_resolve_file_roots_uses_basename_for_blank_name(
+ tmp_path: Path,
+) -> None:
+ primary = tmp_path / "project"
+ shared = tmp_path / "shared"
+ primary.mkdir()
+ shared.mkdir()
+
+ roots = resolve_file_roots(
+ str(primary),
+ {"folders": [{"path": str(shared), "name": " "}]},
+ )
+
+ assert roots[1].name == "shared"
+
+
+def test_resolve_file_roots_warns_when_folder_does_not_exist(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ primary = tmp_path / "project"
+ missing = tmp_path / "missing"
+ primary.mkdir()
+ warning = Mock()
+ monkeypatch.setattr("marimo._server.files.roots.LOGGER.warning", warning)
+
+ roots = resolve_file_roots(
+ str(primary),
+ {"folders": [{"path": str(missing)}]},
+ )
+
+ assert len(roots) == 1
+ warning.assert_called_once_with(
+ "Ignoring file browser root %r: %s",
+ str(missing),
+ "path does not exist",
+ )
+
+
+ "config",
+ [
+ {"folders": "not-a-list"},
+ {"folders": ["not-a-table"]},
+ ],
+)
+def test_resolve_file_roots_ignores_malformed_config(
+ tmp_path: Path,
+ config: object,
+) -> None:
+ primary = tmp_path / "project"
+ primary.mkdir()
+
+ roots = resolve_file_roots(str(primary), config) # type: ignore[arg-type]
+
+ assert len(roots) == 1
+ assert roots[0].is_primary is True