Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat(frontend): uploading multiple files (#1718)

sp.wack15685f9aba21
diff --git a/frontend/src/components/file-explorer/FileExplorer.test.tsx b/frontend/src/components/file-explorer/FileExplorer.test.tsx
index 9ceb073906..00029f55c2 100644
--- a/frontend/src/components/file-explorer/FileExplorer.test.tsx
+++ b/frontend/src/components/file-explorer/FileExplorer.test.tsx
@@ -4,7 +4,7 @@ import userEvent from "@testing-library/user-event";
import { act } from "react-dom/test-utils";
import { describe, it, expect, vi, Mock } from "vitest";
import FileExplorer from "./FileExplorer";
-import { getWorkspace, uploadFile } from "#/services/fileService";
+import { getWorkspace, uploadFiles } from "#/services/fileService";
import toast from "#/utils/toast";
const toastSpy = vi.spyOn(toast, "stickyError");
@@ -18,7 +18,7 @@ vi.mock("../../services/fileService", async () => ({
],
})),
- uploadFile: vi.fn(),
+ uploadFiles: vi.fn(),
}));
describe("FileExplorer", () => {
@@ -89,23 +89,43 @@ describe("FileExplorer", () => {
expect(queryByText("root")).not.toBeVisible();
});
- it("should upload a file", async () => {
+ it("should upload files", async () => {
+ // TODO: Improve this test by passing expected argument to `uploadFiles`
const { getByTestId } = render(<FileExplorer onFileClick={vi.fn} />);
+ const file = new File([""], "file-name");
+ const file2 = new File([""], "file-name-2");
const uploadFileInput = getByTestId("file-input");
- const file = new File([""], "test");
// The 'await' keyword is required here to avoid a warning during test runs
await act(() => {
userEvent.upload(uploadFileInput, file);
});
- expect(uploadFile).toHaveBeenCalledWith(file);
+ expect(uploadFiles).toHaveBeenCalledOnce();
+ expect(getWorkspace).toHaveBeenCalled();
+
+ const uploadDirInput = getByTestId("file-input");
+
+ // The 'await' keyword is required here to avoid a warning during test runs
+ await act(() => {
+ userEvent.upload(uploadDirInput, [file, file2]);
+ });
+
+ expect(uploadFiles).toHaveBeenCalledTimes(2);
expect(getWorkspace).toHaveBeenCalled();
});
+ it.skip("should upload files when dragging them to the explorer", () => {
+ // It will require too much work to mock drag logic, especially for our case
+ // https://github.com/testing-library/user-event/issues/440#issuecomment-685010755
+ // TODO: should be tested in an e2e environment such as Cypress/Playwright
+ });
+
+ it.todo("should download a file");
+
it.todo("should display an error toast if file upload fails", async () => {
- (uploadFile as Mock).mockRejectedValue(new Error());
+ (uploadFiles as Mock).mockRejectedValue(new Error());
const { getByTestId } = render(<FileExplorer onFileClick={vi.fn} />);
@@ -116,7 +136,7 @@ describe("FileExplorer", () => {
userEvent.upload(uploadFileInput, file);
});
- expect(uploadFile).rejects.toThrow();
+ expect(uploadFiles).rejects.toThrow();
// TODO: figure out why spy isnt called to pass test
expect(toastSpy).toHaveBeenCalledWith("ws", "Error uploading file");
});
diff --git a/frontend/src/components/file-explorer/FileExplorer.tsx b/frontend/src/components/file-explorer/FileExplorer.tsx
index 4f6d8e03be..2b0414672d 100644
--- a/frontend/src/components/file-explorer/FileExplorer.tsx
+++ b/frontend/src/components/file-explorer/FileExplorer.tsx
@@ -5,11 +5,12 @@ import {
IoIosRefresh,
IoIosCloudUpload,
} from "react-icons/io";
+import { IoFileTray } from "react-icons/io5";
import { twMerge } from "tailwind-merge";
import {
WorkspaceFile,
getWorkspace,
- uploadFile,
+ uploadFiles,
} from "#/services/fileService";
import IconButton from "../IconButton";
import ExplorerTree from "./ExplorerTree";
@@ -92,6 +93,8 @@ interface FileExplorerProps {
function FileExplorer({ onFileClick }: FileExplorerProps) {
const [workspace, setWorkspace] = React.useState<WorkspaceFile>();
const [isHidden, setIsHidden] = React.useState(false);
+ const [isDragging, setIsDragging] = React.useState(false);
+
const fileInputRef = React.useRef<HTMLInputElement | null>(null);
const getWorkspaceData = async () => {
@@ -99,16 +102,14 @@ function FileExplorer({ onFileClick }: FileExplorerProps) {
setWorkspace(removeEmptyNodes(wsFile));
};
- const selectFileInput = () => {
- fileInputRef.current?.click(); // Trigger the file browser
+ const selectFileInput = async () => {
+ // Trigger the file browser
+ fileInputRef.current?.click();
};
- const uploadFileData = async (event: React.ChangeEvent<HTMLInputElement>) => {
- const file = event.target.files ? event.target.files[0] : null;
- if (!file) return;
-
+ const uploadFileData = async (files: FileList) => {
try {
- await uploadFile(file);
+ await uploadFiles(files);
await getWorkspaceData(); // Refresh the workspace to show the new file
} catch (error) {
toast.stickyError("ws", "Error uploading file");
@@ -119,40 +120,77 @@ function FileExplorer({ onFileClick }: FileExplorerProps) {
(async () => {
await getWorkspaceData();
})();
+
+ const enableDragging = () => {
+ setIsDragging(true);
+ };
+
+ const disableDragging = () => {
+ setIsDragging(false);
+ };
+
+ document.addEventListener("dragenter", enableDragging);
+ document.addEventListener("drop", disableDragging);
+
+ return () => {
+ document.removeEventListener("dragenter", enableDragging);
+ document.removeEventListener("drop", disableDragging);
+ };
}, []);
return (
- <div
- className={twMerge(
- "bg-neutral-800 h-full border-r-1 border-r-neutral-600 flex flex-col transition-all ease-soft-spring overflow-auto",
- isHidden ? "min-w-[48px]" : "min-w-[228px]",
- )}
- >
- <div className="flex p-2 items-center justify-between relative">
- <div style={{ display: isHidden ? "none" : "block" }}>
- {workspace && (
- <ExplorerTree
- root={workspace}
- onFileClick={onFileClick}
- defaultOpen
- />
- )}
+ <div className="relative">
+ {isDragging && (
+ <div
+ data-testid="dropzone"
+ onDrop={(event) => {
+ event.preventDefault();
+ uploadFileData(event.dataTransfer.files);
+ }}
+ onDragOver={(event) => event.preventDefault()}
+ className="z-10 absolute flex flex-col justify-center items-center bg-black top-0 bottom-0 left-0 right-0 opacity-65"
+ >
+ <IoFileTray size={32} />
+ <p className="font-bold text-xl">Drop Files Here</p>
</div>
+ )}
+ <div
+ className={twMerge(
+ "bg-neutral-800 h-full border-r-1 border-r-neutral-600 flex flex-col transition-all ease-soft-spring overflow-auto",
+ isHidden ? "min-w-[48px]" : "min-w-[228px]",
+ )}
+ >
+ <div className="flex p-2 items-center justify-between relative">
+ <div style={{ display: isHidden ? "none" : "block" }}>
+ {workspace && (
+ <ExplorerTree
+ root={workspace}
+ onFileClick={onFileClick}
+ defaultOpen
+ />
+ )}
+ </div>
- <ExplorerActions
- isHidden={isHidden}
- toggleHidden={() => setIsHidden((prev) => !prev)}
- onRefresh={getWorkspaceData}
- onUpload={selectFileInput}
+ <ExplorerActions
+ isHidden={isHidden}
+ toggleHidden={() => setIsHidden((prev) => !prev)}
+ onRefresh={getWorkspaceData}
+ onUpload={selectFileInput}
+ />
+ </div>
+ <input
+ data-testid="file-input"
+ type="file"
+ multiple
+ ref={fileInputRef}
+ style={{ display: "none" }}
+ onChange={(event) => {
+ if (event.target.files) {
+ uploadFileData(event.target.files);
+ }
+ }}
/>
</div>
- <input
- data-testid="file-input"
- type="file"
- ref={fileInputRef}
- style={{ display: "none" }}
- onChange={uploadFileData}
- />
</div>
);
}
diff --git a/frontend/src/services/fileService.ts b/frontend/src/services/fileService.ts
index e4d23b1803..17fe10ec7e 100644
--- a/frontend/src/services/fileService.ts
+++ b/frontend/src/services/fileService.ts
@@ -12,11 +12,13 @@ export async function selectFile(file: string): Promise<string> {
return data.code as string;
}
-export async function uploadFile(file: File) {
+export async function uploadFiles(files: FileList) {
const formData = new FormData();
- formData.append("file", file);
+ for (let i = 0; i < files.length; i += 1) {
+ formData.append("files", files[i]);
+ }
- const res = await fetch("/api/upload-file", {
+ const res = await fetch("/api/upload-files", {
method: "POST",
body: formData,
});
@@ -24,7 +26,7 @@ export async function uploadFile(file: File) {
const data = await res.json();
if (res.status !== 200) {
- throw new Error(data.error || "Failed to upload file.");
+ throw new Error(data.error || "Failed to upload files.");
}
}
diff --git a/opendevin/server/listen.py b/opendevin/server/listen.py
index 540b108ca1..71911282fd 100644
--- a/opendevin/server/listen.py
+++ b/opendevin/server/listen.py
@@ -266,30 +266,31 @@ def select_file(file: str):
return {'code': content}
[email protected]('/api/upload-file')
-async def upload_file(file: UploadFile):
[email protected]('/api/upload-files')
+async def upload_files(files: list[UploadFile]):
"""
- Upload a file.
+ Upload files to the workspace.
- To upload a file:
+ To upload files:
```sh
- curl -X POST -F "file=@<file_path>" http://localhost:3000/api/upload-file
+ curl -X POST -F "file=@<file_path1>" -F "file=@<file_path2>" http://localhost:3000/api/upload-files
```
"""
try:
workspace_base = config.workspace_base
- file_path = Path(workspace_base, file.filename)
- # The following will check if the file is within the workspace base and throw an exception if not
- file_path.resolve().relative_to(Path(workspace_base).resolve())
- with open(file_path, 'wb') as buffer:
- shutil.copyfileobj(file.file, buffer)
+ for file in files:
+ file_path = Path(workspace_base, file.filename)
+ # The following will check if the file is within the workspace base and throw an exception if not
+ file_path.resolve().relative_to(Path(workspace_base).resolve())
+ with open(file_path, 'wb') as buffer:
+ shutil.copyfileobj(file.file, buffer)
except Exception as e:
- logger.error(f'Error saving file {file.filename}: {e}', exc_info=True)
+ logger.error(f'Error saving files: {e}', exc_info=True)
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- content={'error': f'Error saving file: {e}'},
+ content={'error': f'Error saving file:s {e}'},
)
- return {'filename': file.filename, 'location': str(file_path)}
+ return {'message': 'Files uploaded successfully', 'file_count': len(files)}
@app.get('/api/root_task')