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: upload files directly into folders (#10637)

Shahmir Varqha178487187896
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 50e2362a9c..64ed1c38b0 100644
--- a/frontend/src/components/editor/chrome/panels/file-explorer-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/file-explorer-panel.tsx
@@ -2,16 +2,25 @@
import { useAtom, useAtomValue } from "jotai";
import { FileIcon, HardDrive } from "lucide-react";
-import React, { useCallback, useMemo } from "react";
+import React, { useCallback, useMemo, useState } from "react";
+import type { DropEvent } from "react-dropzone";
import useResizeObserver from "use-resize-observer";
import { StorageInspector } from "@/components/storage/storage-inspector";
import { Accordion } from "@/components/ui/accordion";
import { storageNamespacesAtom } from "@/core/storage/state";
import { useDetectedDataSources } from "@/hooks/useDataSourceDiscovery";
import { cn } from "@/utils/cn";
+import type { FilePath } from "@/utils/paths";
import { TreeDndProvider } from "../../file-tree/dnd-wrapper";
-import { FileExplorer } from "../../file-tree/file-explorer";
-import { useFileExplorerUpload } from "../../file-tree/upload";
+import {
+ FileExplorer,
+ getUploadDestinationLabel,
+} from "../../file-tree/file-explorer";
+import { treeAtom } from "../../file-tree/state";
+import {
+ getUploadDestinationFromTarget,
+ useFileExplorerUpload,
+} from "../../file-tree/upload";
import {
DiscoveredSourcesBadge,
PanelAccordionContent,
@@ -25,10 +34,37 @@ import {
} from "./panel-accordion-state";
const FileExplorerComponent: React.FC<{ height: number }> = ({ height }) => {
+ const tree = useAtomValue(treeAtom);
+ const [dropDestinationPath, setDropDestinationPath] =
+ useState<FilePath | null>(null);
+
+ const getDropDestinationPath = useCallback(
+ (event: DropEvent) =>
+ getUploadDestinationForEvent(event, tree.getRootPath()),
+ [tree],
+ );
+ const refreshUploadDestination = useCallback(
+ (destinationPath: FilePath) => tree.refreshPath(destinationPath),
+ [tree],
+ );
const { getRootProps, getInputProps, isDragActive } = useFileExplorerUpload({
noClick: true,
noKeyboard: true,
+ destinationPath: getDropDestinationPath,
+ getDestinationLabel: (path) => getUploadDestinationLabel(tree, path),
+ refreshDestination: refreshUploadDestination,
+ onDragEnter: (event) =>
+ setDropDestinationPath(getDropDestinationPath(event)),
+ onDragOver: (event) =>
+ setDropDestinationPath(getDropDestinationPath(event)),
+ onDragLeave: () => setDropDestinationPath(null),
+ onUploadStart: () => setDropDestinationPath(null),
});
+ const displayedDestinationPath = dropDestinationPath ?? tree.getRootPath();
+ const displayedDestinationLabel = getUploadDestinationLabel(
+ tree,
+ displayedDestinationPath,
+ );
return (
<TreeDndProvider>
@@ -39,17 +75,34 @@ const FileExplorerComponent: React.FC<{ height: number }> = ({ height }) => {
>
<input {...getInputProps()} />
{isDragActive && (
- <div className="absolute inset-0 flex items-center uppercase justify-center text-xl font-bold text-primary/90 bg-accent/85 z-10 border-2 border-dashed border-primary/90 rounded-lg pointer-events-none">
- Drop files here
+ <div className="absolute inset-0 flex items-start justify-center pt-3 bg-accent/20 z-10 border-2 border-dashed border-primary/90 rounded-lg pointer-events-none">
+ <span className="px-3 py-1.5 rounded-md bg-background/95 border shadow-sm text-sm font-semibold text-primary">
+ Drop files into {displayedDestinationLabel}
+ </span>
</div>
)}
- <FileExplorer height={height} />
+ <FileExplorer
+ height={height}
+ externalDropDestinationPath={
+ isDragActive ? displayedDestinationPath : null
+ }
+ />
</div>
</TreeDndProvider>
);
};
+export function getUploadDestinationForEvent(
+ event: DropEvent,
+ rootPath: FilePath,
+): FilePath {
+ if (Array.isArray(event)) {
+ return rootPath;
+ }
+ return getUploadDestinationFromTarget(event.target, rootPath);
+}
+
// Height of each accordion trigger (px-3 py-2 text-xs = ~33px)
const TRIGGER_HEIGHT = 33;
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
new file mode 100644
index 0000000000..7fe7a9c70a
--- /dev/null
+++ b/frontend/src/components/editor/file-tree/__tests__/file-explorer-interactions.test.tsx
@@ -0,0 +1,128 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { Provider, createStore } from "jotai";
+import type React from "react";
+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";
+
+vi.mock("react-arborist", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("react-arborist")>();
+ return {
+ ...actual,
+ Tree: ({
+ data,
+ onSelect,
+ }: {
+ data: FileInfo[];
+ onSelect: (nodes: Array<{ data: FileInfo }>) => void;
+ }) => (
+ <div>
+ {data.map((item) => (
+ <button
+ type="button"
+ key={item.id}
+ onClick={() => onSelect([{ data: item }])}
+ >
+ {item.name}
+ </button>
+ ))}
+ </div>
+ ),
+ };
+});
+
+let testStore = createStore();
+
+const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <Provider store={testStore}>
+ <TooltipProvider>{children}</TooltipProvider>
+ </Provider>
+);
+
+describe("FileExplorer upload destination", () => {
+ let client: ReturnType<typeof MockRequestClient.create>;
+
+ beforeEach(() => {
+ localStorage.removeItem("marimo:showHiddenFiles");
+ testStore = createStore();
+ client = MockRequestClient.create({
+ sendListFiles: vi.fn().mockImplementation(async ({ path }) => {
+ if (path) {
+ return { files: [] };
+ }
+ return {
+ root: "/workspace",
+ files: [
+ {
+ id: "data-directory",
+ name: "data",
+ path: "/workspace/data",
+ isDirectory: true,
+ },
+ {
+ id: "hidden-directory",
+ name: ".hidden",
+ path: "/workspace/.hidden",
+ isDirectory: true,
+ },
+ ],
+ };
+ }),
+ sendCreateFileOrFolder: vi.fn().mockResolvedValue({ success: true }),
+ });
+ testStore.set(requestClientAtom, client);
+ });
+
+ 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();
+
+ fireEvent.click(await screen.findByText("data"));
+
+ const folderUpload = await screen.findByRole("button", {
+ name: "Upload files to data",
+ });
+ fireEvent.click(folderUpload);
+
+ const file = new File(["contents"], "report.csv");
+ fireEvent.change(screen.getByTestId("file-explorer-upload-input"), {
+ target: { files: [file] },
+ });
+
+ await waitFor(() => {
+ expect(client.sendCreateFileOrFolder).toHaveBeenCalledWith({
+ path: "/workspace/data",
+ type: "file",
+ name: "report.csv",
+ file,
+ });
+ });
+ });
+
+ it("clears a selected hidden folder when hidden files are hidden", async () => {
+ render(<FileExplorer height={300} />, { wrapper });
+
+ fireEvent.click(await screen.findByText(".hidden"));
+ expect(
+ await screen.findByRole("button", { name: "Upload files to .hidden" }),
+ ).toBeVisible();
+
+ fireEvent.click(screen.getByTestId("file-explorer-hidden-files-button"));
+
+ expect(
+ await screen.findByRole("button", {
+ name: "Upload files to workspace root",
+ }),
+ ).toBeVisible();
+ expect(screen.queryByText(".hidden")).not.toBeInTheDocument();
+ });
+});
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 ff84f54b6a..6c326ff3a3 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
@@ -52,6 +52,7 @@ describe("RequestingTree", () => {
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" },
@@ -261,6 +262,65 @@ describe("RequestingTree", () => {
`);
});
+ 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 requestingTree.refreshPath("/root/folder1" as FilePath);
+
+ 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",
+ },
+ ]);
+ });
+
describe("when API fails", () => {
test("initialize should handle errors gracefully", async () => {
requestingTree = new RequestingTree({
diff --git a/frontend/src/components/editor/file-tree/__tests__/upload.test.tsx b/frontend/src/components/editor/file-tree/__tests__/upload.test.tsx
new file mode 100644
index 0000000000..f37f162ab7
--- /dev/null
+++ b/frontend/src/components/editor/file-tree/__tests__/upload.test.tsx
@@ -0,0 +1,230 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { describe, expect, it, vi } from "vitest";
+import type { FileCreateInput, FileCreateResponse } from "@/core/network/types";
+import type { FilePath } from "@/utils/paths";
+import {
+ FILE_EXPLORER_DIRECTORY_PATH_ATTRIBUTE,
+ getUploadDestinationFromTarget,
+ resolveUploadDirectoryPath,
+ uploadFilesToDestination,
+} from "../upload";
+
+const filePath = (path: string) => path as FilePath;
+
+describe("resolveUploadDirectoryPath", () => {
+ it("uploads an individual file to the explicit destination", () => {
+ expect(
+ resolveUploadDirectoryPath({
+ destinationPath: filePath("/workspace/data"),
+ filePath: filePath("./sales.csv"),
+ }),
+ ).toBe("/workspace/data");
+ });
+
+ it("preserves a dropped folder's relative structure", () => {
+ expect(
+ resolveUploadDirectoryPath({
+ destinationPath: filePath("/workspace/data"),
+ filePath: filePath("raw/2026/sales.csv"),
+ }),
+ ).toBe("/workspace/data/raw/2026");
+ });
+
+ it("normalizes relative paths for a Windows destination", () => {
+ expect(
+ resolveUploadDirectoryPath({
+ destinationPath: filePath("C:\\workspace\\data"),
+ filePath: filePath("raw/2026/sales.csv"),
+ }),
+ ).toBe("C:\\workspace\\data\\raw\\2026");
+ });
+
+ it("normalizes mixed separators in relative paths", () => {
+ expect(
+ resolveUploadDirectoryPath({
+ destinationPath: filePath("/workspace/data"),
+ filePath: filePath("raw\\2026/sales.csv"),
+ }),
+ ).toBe("/workspace/data/raw/2026");
+ });
+
+ it("removes current-directory components", () => {
+ expect(
+ resolveUploadDirectoryPath({
+ destinationPath: filePath("/workspace/data"),
+ filePath: filePath("raw/./2026/sales.csv"),
+ }),
+ ).toBe("/workspace/data/raw/2026");
+ });
+
+ it.each(["../sales.csv", "raw/../../sales.csv", "raw\\..\\sales.csv"])(
+ "rejects parent traversal in %s",
+ (unsafePath) => {
+ expect(() =>
+ resolveUploadDirectoryPath({
+ destinationPath: filePath("/workspace/data"),
+ filePath: filePath(unsafePath),
+ }),
+ ).toThrow(/parent traversal/);
+ },
+ );
+
+ it.each([
+ "C:\\Users\\sales.csv",
+ "\\\\server\\share\\sales.csv",
+ "file://workspace/sales.csv",
+ "/Users/example/sales.csv",
+ ])("rejects absolute path %s", (absolutePath) => {
+ expect(() =>
+ resolveUploadDirectoryPath({
+ destinationPath: filePath("/workspace/data"),
+ filePath: filePath(absolutePath),
+ }),
+ ).toThrow(/must be relative/);
+ });
+});
+
+describe("getUploadDestinationFromTarget", () => {
+ it("uses the closest folder as the drop destination", () => {
+ const folder = document.createElement("div");
+ folder.setAttribute(
+ FILE_EXPLORER_DIRECTORY_PATH_ATTRIBUTE,
+ "/workspace/data",
+ );
+ const child = document.createElement("span");
+ folder.append(child);
+
+ expect(getUploadDestinationFromTarget(child, filePath("/workspace"))).toBe(
+ "/workspace/data",
+ );
+ });
+
+ it("uses the workspace root outside a folder", () => {
+ expect(
+ getUploadDestinationFromTarget(
+ document.createElement("div"),
+ filePath("/workspace"),
+ ),
+ ).toBe("/workspace");
+ });
+});
+
+describe("uploadFilesToDestination", () => {
+ it("sends files to the destination and separates server failures", async () => {
+ const successfulFile = new File(["success"], "success.txt");
+ const failedFile = new File(["failure"], "failure.txt");
+ Object.defineProperty(successfulFile, "path", {
+ value: "nested/success.txt",
+ });
+ const createFile = vi.fn(
+ async (request: FileCreateInput): Promise<FileCreateResponse> =>
+ request.name === "success.txt"
+ ? { success: true }
+ : { success: false, message: "Permission denied" },
+ );
+ const onFileProcessed = vi.fn();
+
+ const result = await uploadFilesToDestination({
+ files: [successfulFile, failedFile],
+ destinationPath: filePath("/workspace/data"),
+ createFile,
+ onFileProcessed,
+ });
+
+ expect(createFile.mock.calls.map(([request]) => request)).toEqual([
+ {
+ path: "/workspace/data/nested",
+ type: "file",
+ name: "success.txt",
+ file: successfulFile,
+ },
+ {
+ path: "/workspace/data",
+ type: "file",
+ name: "failure.txt",
+ file: failedFile,
+ },
+ ]);
+ expect(result).toEqual({
+ successful: [{ file: successfulFile, response: { success: true } }],
+ failed: [
+ {
+ file: failedFile,
+ response: { success: false, message: "Permission denied" },
+ },
+ ],
+ });
+ expect(onFileProcessed).toHaveBeenCalledTimes(2);
+ });
+
+ it("treats a browser-style leading slash as a relative drop path", async () => {
+ const browserFile = new File(["data"], "sales.csv");
+ Object.defineProperty(browserFile, "path", {
+ value: "/raw/2026/sales.csv",
+ });
+ const createFile = vi
+ .fn<(request: FileCreateInput) => Promise<FileCreateResponse>>()
+ .mockResolvedValue({ success: true });
+
+ await uploadFilesToDestination({
+ files: [browserFile],
+ destinationPath: filePath("/workspace/data"),
+ createFile,
+ });
+
+ expect(createFile).toHaveBeenCalledWith({
+ path: "/workspace/data/raw/2026",
+ type: "file",
+ name: "sales.csv",
+ file: browserFile,
+ });
+ });
+
+ it("waits for every file and normalizes thrown request errors", async () => {
+ const failedFile = new File(["failure"], "failure.txt");
+ const slowFile = new File(["success"], "slow.txt");
+ let finishSlowUpload: ((response: FileCreateResponse) => void) | undefined;
+ const createFile = vi.fn(
+ (request: FileCreateInput): Promise<FileCreateResponse> => {
+ if (request.name === "failure.txt") {
+ return Promise.reject(new Error("Connection lost"));
+ }
+ return new Promise((resolve) => {
+ finishSlowUpload = resolve;
+ });
+ },
+ );
+ const onFileProcessed = vi.fn();
+
+ const upload = uploadFilesToDestination({
+ files: [failedFile, slowFile],
+ destinationPath: filePath("/workspace/data"),
+ createFile,
+ onFileProcessed,
+ });
+
+ await vi.waitFor(() => {
+ expect(createFile).toHaveBeenCalledTimes(2);
+ expect(onFileProcessed).toHaveBeenCalledTimes(1);
+ });
+ let hasSettled = false;
+ void upload.finally(() => {
+ hasSettled = true;
+ });
+ await Promise.resolve();
+ expect(hasSettled).toBe(false);
+
+ finishSlowUpload?.({ success: true });
+ await expect(upload).resolves.toEqual({
+ successful: [{ file: slowFile, response: { success: true } }],
+ failed: [
+ {
+ file: failedFile,
+ response: { success: false, message: "Connection lost" },
+ },
+ ],
+ });
+ expect(onFileProcessed).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/frontend/src/components/editor/file-tree/file-explorer.tsx b/frontend/src/components/editor/file-tree/file-explorer.tsx
index 534cd094fb..cfd6358aeb 100644
--- a/frontend/src/components/editor/file-tree/file-explorer.tsx
+++ b/frontend/src/components/editor/file-tree/file-explorer.tsx
@@ -47,7 +47,7 @@ import { MarimoIcon, MarimoPlusIcon } from "@/components/icons/marimo-icons";
import { Spinner } from "@/components/icons/spinner";
import { useImperativeModal } from "@/components/modal/ImperativeModal";
import { AlertDialogDestructiveAction } from "@/components/ui/alert-dialog";
-import { Button, buttonVariants } from "@/components/ui/button";
+import { Button } from "@/components/ui/button";
import {
DropdownMenuItem,
DropdownMenuSeparator,
@@ -74,7 +74,10 @@ import { FileViewer } from "./file-viewer";
import type { RequestingTree } from "./requesting-tree";
import { openStateAtom, treeAtom } from "./state";
import { PYTHON_CODE_FOR_FILE_TYPE } from "./types";
-import { useFileExplorerUpload } from "./upload";
+import {
+ FILE_EXPLORER_DIRECTORY_PATH_ATTRIBUTE,
+ useFileExplorerUpload,
+} from "./upload";
const hiddenFilesState = atomWithStorage(
"marimo:showHiddenFiles",
@@ -85,23 +88,53 @@ const hiddenFilesState = atomWithStorage(
},
);
-const RequestingTreeContext = React.createContext<RequestingTree | null>(null);
+interface FileExplorerContextValue {
+ tree: RequestingTree;
+ uploadFiles: (destinationPath: FilePath) => void;
+ externalDropDestinationPath: FilePath | null;
+}
+
+const RequestingTreeContext =
+ React.createContext<FileExplorerContextValue | null>(null);
export const FileExplorer: React.FC<{
height: number;
-}> = ({ height }) => {
+ externalDropDestinationPath?: FilePath | null;
+}> = ({ height, externalDropDestinationPath = null }) => {
const treeRef = useRef<TreeApi<FileInfo>>(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 [showHiddenFiles, setShowHiddenFiles] =
useAtom<boolean>(hiddenFilesState);
+ // Keep external state to remember which folders are open when this
+ // component is unmounted.
+ const [openState, setOpenState] = useAtom(openStateAtom);
+
+ const refreshUploadDestination = useEvent((destinationPath: FilePath) => {
+ return tree.refreshPath(destinationPath);
+ });
+
+ const uploadDestinationRef = useRef<FilePath>("" as FilePath);
+ const { getInputProps: getUploadInputProps, open: openUploadPicker } =
+ useFileExplorerUpload({
+ noClick: true,
+ noDrag: true,
+ noKeyboard: true,
+ destinationPath: () => uploadDestinationRef.current,
+ getDestinationLabel: (path) => getUploadDestinationLabel(tree, path),
+ refreshDestination: refreshUploadDestination,
+ });
+ const handleUploadFiles = useEvent((destinationPath: FilePath) => {
+ uploadDestinationRef.current = destinationPath;
+ openUploadPicker();
+ });
const { openPrompt } = useImperativeModal();
- // Keep external state to remember which folders are open
- // when this component is unmounted
- const [openState, setOpenState] = useAtom(openStateAtom);
const { isPending, error } = useAsyncData(() => tree.initialize(setData), []);
const handleRefresh = useEvent(() => {
@@ -152,6 +185,22 @@ export const FileExplorer: React.FC<{
() => filterHiddenTree(data, showHiddenFiles),
[data, showHiddenFiles],
);
+ React.useEffect(() => {
+ if (
+ selectedFolderPath &&
+ !treeContainsPath(visibleData, selectedFolderPath)
+ ) {
+ setSelectedFolderPath(null);
+ }
+ }, [selectedFolderPath, visibleData]);
+ const contextValue = React.useMemo<FileExplorerContextValue>(
+ () => ({
+ tree,
+ uploadFiles: handleUploadFiles,
+ externalDropDestinationPath,
+ }),
+ [tree, handleUploadFiles, externalDropDestinationPath],
+ );
if (isPending) {
return <Spinner size="medium" centered={true} />;
@@ -193,6 +242,10 @@ export const FileExplorer: React.FC<{
return (
<>
+ <input
+ data-testid="file-explorer-upload-input"
+ {...getUploadInputProps()}
+ />
<Toolbar
onRefresh={handleRefresh}
onHidden={handleHiddenFilesToggle}
@@ -201,9 +254,14 @@ export const FileExplorer: React.FC<{
onCreateNotebook={handleCreateNotebook}
onCreateFolder={handleCreateFolder}
onCollapseAll={handleCollapseAll}
- tree={tree}
+ uploadDestinationPath={selectedFolderPath ?? tree.getRootPath()}
+ uploadDestinationLabel={getUploadDestinationLabel(
+ tree,
+ selectedFolderPath ?? tree.getRootPath(),
+ )}
+ onUpload={handleUploadFiles}
/>
- <RequestingTreeContext value={tree}>
+ <RequestingTreeContext value={contextValue}>
<Tree<FileInfo>
width="100%"
ref={treeRef}
@@ -232,11 +290,15 @@ export const FileExplorer: React.FC<{
onSelect={(nodes) => {
const first = nodes[0];
if (!first) {
+ setSelectedFolderPath(null);
return;
}
- if (!first.data.isDirectory) {
- setOpenFile(first.data);
+ if (first.data.isDirectory) {
+ setSelectedFolderPath(first.data.path as FilePath);
+ return;
}
+ setSelectedFolderPath(null);
+ setOpenFile(first.data);
}}
onToggle={async (id) => {
const result = await tree.expand(id);
@@ -269,7 +331,9 @@ interface ToolbarProps {
onCreateNotebook: () => void;
onCreateFolder: () => void;
onCollapseAll: () => void;
- tree: RequestingTree;
+ uploadDestinationPath: FilePath;
+ uploadDestinationLabel: string;
+ onUpload: (destinationPath: FilePath) => void;
}
const Toolbar = ({
@@ -280,11 +344,11 @@ const Toolbar = ({
onCreateNotebook,
onCreateFolder,
onCollapseAll,
+ uploadDestinationPath,
+ uploadDestinationLabel,
+ onUpload,
}: ToolbarProps) => {
- const { getRootProps, getInputProps } = useFileExplorerUpload({
- noDrag: true,
- noDragEventsBubbling: true,
- });
+ const uploadLabel = `Upload files to ${uploadDestinationLabel}`;
return (
<div className="flex items-center justify-end px-2 shrink-0 border-b">
@@ -318,19 +382,17 @@ const Toolbar = ({
<FolderPlusIcon size={16} />
</Button>
</Tooltip>
- <Tooltip content="Upload file">
- <button
+ <Tooltip content={uploadLabel}>
+ <Button
data-testid="file-explorer-upload-button"
- {...getRootProps({})}
- className={buttonVariants({
- variant: "text",
- size: "xs",
- })}
+ aria-label={uploadLabel}
+ onClick={() => onUpload(uploadDestinationPath)}
+ variant="text"
+ size="xs"
>
<UploadIcon size={16} />
- </button>
+ </Button>
</Tooltip>
- <input {...getInputProps({})} type="file" />
<RefreshIconButton
data-testid="file-explorer-refresh-button"
onClick={onRefresh}
@@ -411,7 +473,11 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
});
};
- const tree = use(RequestingTreeContext);
+ const fileExplorer = use(RequestingTreeContext);
+ const tree = fileExplorer?.tree;
+ const isExternalDropTarget =
+ node.data.isDirectory &&
+ fileExplorer?.externalDropDestinationPath === node.data.path;
const handleOpenMarimoFile = async (
evt: Pick<Event, "stopPropagation" | "preventDefault">,
@@ -483,6 +549,9 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
<div
style={style}
ref={dragHandle}
+ {...(node.data.isDirectory
+ ? { [FILE_EXPLORER_DIRECTORY_PATH_ATTRIBUTE]: node.data.path }
+ : {})}
className={cn(
"flex items-center cursor-pointer ml-1 text-muted-foreground whitespace-nowrap group",
)}
@@ -490,6 +559,7 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
onClick={(evt) => {
evt.stopPropagation();
if (node.data.isDirectory) {
+ node.select();
node.toggle();
}
}}
@@ -501,6 +571,10 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
node.willReceiveDrop &&
node.data.isDirectory &&
"bg-accent/80 hover:bg-accent/80 text-accent-foreground",
+ node.isSelected &&
+ "bg-accent/60 hover:bg-accent/60 text-accent-foreground",
+ isExternalDropTarget &&
+ "bg-primary/15 hover:bg-primary/15 text-accent-foreground ring-1 ring-inset ring-primary",
)}
>
{node.data.isMarimoFile ? (
@@ -563,6 +637,15 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
<FolderPlusIcon className={MENU_ITEM_ICON_CLASS} />
Create folder
</DropdownMenuItem>
+ <DropdownMenuItem
+ onSelect={() =>
+ fileExplorer?.uploadFiles(node.data.path as FilePath)
+ }
+ data-testid="file-explorer-upload-files-menu-item"
+ >
+ <UploadIcon className={MENU_ITEM_ICON_CLASS} />
+ Upload files here
+ </DropdownMenuItem>
<DropdownMenuSeparator />
</>
)}
@@ -680,6 +763,16 @@ function openMarimoNotebook(
openNotebook(path);
}
+export function getUploadDestinationLabel(
+ tree: RequestingTree,
+ destinationPath: FilePath,
+): string {
+ if (destinationPath === tree.getRootPath()) {
+ return "workspace root";
+ }
+ return tree.relativeFromRoot(destinationPath);
+}
+
export function filterHiddenTree(
list: FileInfo[],
showHidden: boolean,
@@ -711,3 +804,11 @@ export function isDirectoryOrFileHidden(filename: string): boolean {
}
return false;
}
+
+function treeContainsPath(list: FileInfo[], path: FilePath): boolean {
+ return list.some(
+ (item) =>
+ item.path === path ||
+ (item.children ? treeContainsPath(item.children, path) : false),
+ );
+}
diff --git a/frontend/src/components/editor/file-tree/requesting-tree.tsx b/frontend/src/components/editor/file-tree/requesting-tree.tsx
index 6dd989d579..afe18299f3 100644
--- a/frontend/src/components/editor/file-tree/requesting-tree.tsx
+++ b/frontend/src/components/editor/file-tree/requesting-tree.tsx
@@ -286,6 +286,24 @@ export class RequestingTree {
this.onChange(this.delegate.data);
};
+ refreshPath = async (path: FilePath): Promise<void> => {
+ const data = await this.callbacks.listFiles({ path }).catch(() => null);
+ if (!data) {
+ return;
+ }
+
+ if (path === this.rootPath) {
+ this.delegate = new SimpleTree(data.files);
+ } else {
+ const item = findFileByPath(this.delegate.data, path);
+ if (!item?.isDirectory) {
+ return;
+ }
+ this.delegate.update({ id: item.id, changes: { children: data.files } });
+ }
+ this.onChange(this.delegate.data);
+ };
+
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)
@@ -297,4 +315,23 @@ export class RequestingTree {
}
return path;
};
+
+ public getRootPath = (): FilePath => {
+ return this.rootPath;
+ };
+}
+
+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;
+ }
+ }
+ return undefined;
}
diff --git a/frontend/src/components/editor/file-tree/state.tsx b/frontend/src/components/editor/file-tree/state.tsx
index cdcd65f317..0862415000 100644
--- a/frontend/src/components/editor/file-tree/state.tsx
+++ b/frontend/src/components/editor/file-tree/state.tsx
@@ -2,7 +2,6 @@
import { atom } from "jotai";
import { requestClientAtom } from "@/core/network/requests";
-import { store } from "@/core/state/jotai";
import { invariant } from "@/utils/invariant";
import { RequestingTree } from "./requesting-tree";
@@ -21,7 +20,3 @@ export const treeAtom = atom<RequestingTree>((get) => {
});
export const openStateAtom = atom<Record<string, boolean>>({});
-
-export async function refreshRoot() {
- await store.get(treeAtom).refreshAll([]);
-}
diff --git a/frontend/src/components/editor/file-tree/upload.tsx b/frontend/src/components/editor/file-tree/upload.tsx
index 5eea44d65a..ce9d16b3c8 100644
--- a/frontend/src/components/editor/file-tree/upload.tsx
+++ b/frontend/src/components/editor/file-tree/upload.tsx
@@ -1,22 +1,61 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { type DropzoneOptions, useDropzone } from "react-dropzone";
+import {
+ type DropEvent,
+ type DropzoneOptions,
+ useDropzone,
+} from "react-dropzone";
import { toast } from "@/components/ui/use-toast";
import { useRequestClient } from "@/core/network/requests";
+import type { FileCreateInput, FileCreateResponse } from "@/core/network/types";
import { withLoadingToast } from "@/utils/download";
+import { prettyError } from "@/utils/errors";
import { Logger } from "@/utils/Logger";
-import { type FilePath, PathBuilder } from "@/utils/paths";
+import { type FilePath, PathBuilder, Paths } from "@/utils/paths";
import { mapWithConcurrency } from "@/utils/semaphore";
-import { refreshRoot } from "./state";
const MAX_SIZE = 1024 * 1024 * 100; // 100MB
const UPLOAD_CONCURRENCY = 5;
-export function useFileExplorerUpload(options: DropzoneOptions = {}) {
+export const FILE_EXPLORER_DIRECTORY_PATH_ATTRIBUTE =
+ "data-file-explorer-directory-path";
+
+type DestinationPath = FilePath | ((event: DropEvent) => FilePath);
+
+interface FileExplorerUploadOptions extends Omit<
+ DropzoneOptions,
+ "onDrop" | "onDropRejected" | "onError"
+> {
+ destinationPath: DestinationPath;
+ getDestinationLabel?: (path: FilePath) => string;
+ onUploadStart?: (destinationPath: FilePath, files: File[]) => void;
+ refreshDestination: (destinationPath: FilePath) => Promise<void>;
+}
+
+interface UploadFileResult {
+ file: File;
+ response: FileCreateResponse;
+}
+
+export interface UploadFilesResult {
+ successful: UploadFileResult[];
+ failed: UploadFileResult[];
+}
+
+export function useFileExplorerUpload(options: FileExplorerUploadOptions) {
+ const {
+ destinationPath,
+ getDestinationLabel = (path) => path,
+ onUploadStart,
+ refreshDestination,
+ ...dropzoneOptions
+ } = options;
const { sendCreateFileOrFolder } = useRequestClient();
+
return useDropzone({
multiple: true,
maxSize: MAX_SIZE,
+ ...dropzoneOptions,
onError: (error) => {
Logger.error(error);
toast({
@@ -41,53 +80,189 @@ export function useFileExplorerUpload(options: DropzoneOptions = {}) {
variant: "danger",
});
},
- onDrop: async (acceptedFiles) => {
+ onDrop: async (acceptedFiles, _rejectedFiles, event) => {
if (acceptedFiles.length === 0) {
return;
}
- const isSingle = acceptedFiles.length === 1;
+ const resolvedDestinationPath =
+ typeof destinationPath === "function"
+ ? destinationPath(event)
+ : destinationPath;
+ const destinationLabel = getDestinationLabel(resolvedDestinationPath);
+ const isSingle = acceptedFiles.length === 1;
const loadingTitle = isSingle
- ? "Uploading file..."
- : "Uploading files...";
- const onFinish = {
- title: isSingle
- ? "File uploaded"
- : `${acceptedFiles.length} files uploaded`,
- };
-
- await withLoadingToast(
- loadingTitle,
- async (progress) => {
+ ? `Uploading file to ${destinationLabel}...`
+ : `Uploading files to ${destinationLabel}...`;
+
+ onUploadStart?.(resolvedDestinationPath, acceptedFiles);
+
+ let result: UploadFilesResult;
+ try {
+ result = await withLoadingToast(loadingTitle, async (progress) => {
progress.addTotal(acceptedFiles.length);
- await mapWithConcurrency(
- acceptedFiles,
- UPLOAD_CONCURRENCY,
- async (file) => {
- // We strip the leading slash since File.path can return
- // `/path/to/file`.
- const filePath = stripLeadingSlash(getPath(file));
- let directoryPath = "" as FilePath;
- if (filePath) {
- directoryPath =
- PathBuilder.guessDeliminator(filePath).dirname(filePath);
- }
-
- await sendCreateFileOrFolder({
- path: directoryPath,
- type: "file",
- name: file.name,
- file,
- });
- progress.increment(1);
- },
- );
- await refreshRoot();
- },
- onFinish,
- );
+ return uploadFilesToDestination({
+ files: acceptedFiles,
+ destinationPath: resolvedDestinationPath,
+ createFile: sendCreateFileOrFolder,
+ onFileProcessed: () => progress.increment(1),
+ });
+ });
+ } catch {
+ await refreshDestination(resolvedDestinationPath);
+ return;
+ }
+
+ await refreshDestination(resolvedDestinationPath);
+ showUploadResultToast(result, destinationLabel);
+ },
+ });
+}
+
+export async function uploadFilesToDestination({
+ files,
+ destinationPath,
+ createFile,
+ onFileProcessed,
+}: {
+ files: File[];
+ destinationPath: FilePath;
+ createFile: (request: FileCreateInput) => Promise<FileCreateResponse>;
+ onFileProcessed?: () => void;
+}): Promise<UploadFilesResult> {
+ const results = await mapWithConcurrency(
+ files,
+ UPLOAD_CONCURRENCY,
+ async (file): Promise<UploadFileResult> => {
+ try {
+ const filePath = stripLeadingSlash(getPath(file));
+ const directoryPath = resolveUploadDirectoryPath({
+ destinationPath,
+ filePath,
+ });
+ const response = await createFile({
+ path: directoryPath,
+ type: "file",
+ name: file.name,
+ file,
+ });
+ return { file, response };
+ } catch (error) {
+ return {
+ file,
+ response: { success: false, message: prettyError(error) },
+ };
+ } finally {
+ onFileProcessed?.();
+ }
},
- ...options,
+ );
+
+ return {
+ successful: results.filter(({ response }) => response.success),
+ failed: results.filter(({ response }) => !response.success),
+ };
+}
+
+export function resolveUploadDirectoryPath({
+ destinationPath,
+ filePath,
+}: {
+ destinationPath: FilePath;
+ filePath: FilePath | undefined;
+}): FilePath {
+ if (!filePath) {
+ return destinationPath;
+ }
+
+ if (Paths.isAbsolute(filePath)) {
+ throw new Error(`Upload path must be relative: ${filePath}`);
+ }
+
+ const pathParts = filePath.split(/[\\/]+/);
+ const relativeDirectoryParts = pathParts.slice(0, -1).filter(Boolean);
+ if (relativeDirectoryParts.includes("..")) {
+ throw new Error(`Upload path cannot contain parent traversal: ${filePath}`);
+ }
+
+ const normalizedDirectoryParts = relativeDirectoryParts.filter(
+ (part) => part !== ".",
+ );
+ if (normalizedDirectoryParts.length === 0) {
+ return destinationPath;
+ }
+
+ const destinationPathBuilder = PathBuilder.guessDeliminator(destinationPath);
+ const normalizedRelativePath = normalizedDirectoryParts.join(
+ destinationPathBuilder.deliminator,
+ );
+ return destinationPathBuilder.join(destinationPath, normalizedRelativePath);
+}
+
+export function getUploadDestinationFromTarget(
+ target: EventTarget | null,
+ rootPath: FilePath,
+): FilePath {
+ if (!(target instanceof Element)) {
+ return rootPath;
+ }
+
+ const directory = target.closest(
+ `[${FILE_EXPLORER_DIRECTORY_PATH_ATTRIBUTE}]`,
+ );
+ const path = directory?.getAttribute(FILE_EXPLORER_DIRECTORY_PATH_ATTRIBUTE);
+ return path ? (path as FilePath) : rootPath;
+}
+
+function showUploadResultToast(
+ result: UploadFilesResult,
+ destinationLabel: string,
+) {
+ const total = result.successful.length + result.failed.length;
+ if (result.failed.length > 0) {
+ let title: string;
+ if (result.successful.length === 0) {
+ title = total === 1 ? "File upload failed" : "Files failed to upload";
+ } else {
+ title = `${result.successful.length} of ${total} files uploaded`;
+ }
+ toast({
+ title,
+ description: (
+ <div className="flex flex-col gap-1">
+ <div>Destination: {destinationLabel}.</div>
+ {result.failed.map(({ file, response }, index) => (
+ <div key={`${file.name}-${index}`}>
+ {file.name}:{" "}
+ {response.message || "The server rejected the upload."}
+ </div>
+ ))}
+ </div>
+ ),
+ variant: "danger",
+ });
+ return;
+ }
+
+ const renamedFiles = result.successful.filter(
+ ({ file, response }) =>
+ response.info?.name && response.info.name !== file.name,
+ );
+ toast({
+ title: total === 1 ? "File uploaded" : `${total} files uploaded`,
+ description:
+ renamedFiles.length === 0 ? (
+ `Uploaded to ${destinationLabel}.`
+ ) : (
+ <div className="flex flex-col gap-1">
+ <div>Uploaded to {destinationLabel}.</div>
+ {renamedFiles.map(({ file, response }, index) => (
+ <div key={`${file.name}-${index}`}>
+ {file.name} was saved as {response.info?.name}.
+ </div>
+ ))}
+ </div>
+ ),
});
}