Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Remove download workspace and download files buttons (#7333)

Xingyao Wang9bd199273830
diff --git a/frontend/__tests__/components/features/conversation-panel/conversation-card.test.tsx b/frontend/__tests__/components/features/conversation-panel/conversation-card.test.tsx
index b6d3a92eab..d6f2b52fcb 100644
--- a/frontend/__tests__/components/features/conversation-panel/conversation-card.test.tsx
+++ b/frontend/__tests__/components/features/conversation-panel/conversation-card.test.tsx
@@ -18,7 +18,6 @@ describe("ConversationCard", () => {
const onClick = vi.fn();
const onDelete = vi.fn();
const onChangeTitle = vi.fn();
- const onDownloadWorkspace = vi.fn();
beforeAll(() => {
vi.stubGlobal("window", { open: vi.fn() });
@@ -269,30 +268,7 @@ describe("ConversationCard", () => {
expect(onClick).not.toHaveBeenCalled();
});
- it("should call onDownloadWorkspace when the download button is clicked", async () => {
- const user = userEvent.setup();
- render(
- <ConversationCard
- onClick={onClick}
- onDelete={onDelete}
- onChangeTitle={onChangeTitle}
- onDownloadWorkspace={onDownloadWorkspace}
- title="Conversation 1"
- selectedRepository={null}
- lastUpdatedAt="2021-10-01T12:00:00Z"
- />,
- );
-
- const ellipsisButton = screen.getByTestId("ellipsis-button");
- await user.click(ellipsisButton);
- const menu = screen.getByTestId("context-menu");
- const downloadButton = within(menu).getByTestId("download-button");
-
- await user.click(downloadButton);
-
- expect(onDownloadWorkspace).toHaveBeenCalled();
- });
it("should not display the edit or delete options if the handler is not provided", async () => {
const user = userEvent.setup();
@@ -337,7 +313,6 @@ describe("ConversationCard", () => {
onClick={onClick}
onDelete={onDelete}
onChangeTitle={onChangeTitle}
- onDownloadWorkspace={onDownloadWorkspace}
title="Conversation 1"
selectedRepository={null}
lastUpdatedAt="2021-10-01T12:00:00Z"
@@ -350,7 +325,6 @@ describe("ConversationCard", () => {
<ConversationCard
onClick={onClick}
onDelete={onDelete}
- onDownloadWorkspace={onDownloadWorkspace}
title="Conversation 1"
selectedRepository={null}
lastUpdatedAt="2021-10-01T12:00:00Z"
@@ -359,18 +333,6 @@ describe("ConversationCard", () => {
expect(screen.getByTestId("ellipsis-button")).toBeInTheDocument();
- rerender(
- <ConversationCard
- onClick={onClick}
- onDownloadWorkspace={onDownloadWorkspace}
- title="Conversation 1"
- selectedRepository={null}
- lastUpdatedAt="2021-10-01T12:00:00Z"
- />,
- );
-
- expect(screen.queryByTestId("ellipsis-button")).toBeInTheDocument();
-
rerender(
<ConversationCard
onClick={onClick}
diff --git a/frontend/__tests__/components/feedback-actions.test.tsx b/frontend/__tests__/components/feedback-actions.test.tsx
index 267375a347..ad61901729 100644
--- a/frontend/__tests__/components/feedback-actions.test.tsx
+++ b/frontend/__tests__/components/feedback-actions.test.tsx
@@ -59,7 +59,7 @@ describe("TrajectoryActions", () => {
expect(onNegativeFeedback).toHaveBeenCalled();
});
- it("should call onExportTrajectory when negative feedback is clicked", async () => {
+ it("should call onExportTrajectory when export button is clicked", async () => {
renderWithProviders(
<TrajectoryActions
onPositiveFeedback={onPositiveFeedback}
diff --git a/frontend/src/components/features/chat/action-suggestions.tsx b/frontend/src/components/features/chat/action-suggestions.tsx
index 020835645b..c38e6c9544 100644
--- a/frontend/src/components/features/chat/action-suggestions.tsx
+++ b/frontend/src/components/features/chat/action-suggestions.tsx
@@ -2,7 +2,6 @@ import posthog from "posthog-js";
import React from "react";
import { useSelector } from "react-redux";
import { SuggestionItem } from "#/components/features/suggestions/suggestion-item";
-import { DownloadModal } from "#/components/shared/download-modal";
import type { RootState } from "#/store";
import { useAuth } from "#/context/auth-context";
@@ -18,21 +17,11 @@ export function ActionSuggestions({
(state: RootState) => state.initialQuery,
);
- const [isDownloading, setIsDownloading] = React.useState(false);
const [hasPullRequest, setHasPullRequest] = React.useState(false);
- const handleDownloadClose = () => {
- setIsDownloading(false);
- };
-
return (
<div className="flex flex-col gap-2 mb-2">
- <DownloadModal
- initialPath=""
- onClose={handleDownloadClose}
- isOpen={isDownloading}
- />
- {githubTokenIsSet && selectedRepository ? (
+ {githubTokenIsSet && selectedRepository && (
<div className="flex flex-row gap-2 justify-center w-full">
{!hasPullRequest ? (
<>
@@ -74,21 +63,6 @@ export function ActionSuggestions({
/>
)}
</div>
- ) : (
- <SuggestionItem
- suggestion={{
- label: !isDownloading
- ? "Download files"
- : "Downloading, please wait...",
- value: "Download files",
- }}
- onClick={() => {
- posthog.capture("download_workspace_button_clicked");
- if (!isDownloading) {
- setIsDownloading(true);
- }
- }}
- />
)}
</div>
);
diff --git a/frontend/src/components/features/chat/chat-interface.tsx b/frontend/src/components/features/chat/chat-interface.tsx
index d6b8a458bd..32f33c09c2 100644
--- a/frontend/src/components/features/chat/chat-interface.tsx
+++ b/frontend/src/components/features/chat/chat-interface.tsx
@@ -21,7 +21,7 @@ import { ContinueButton } from "#/components/shared/buttons/continue-button";
import { ScrollToBottomButton } from "#/components/shared/buttons/scroll-to-bottom-button";
import { LoadingSpinner } from "#/components/shared/loading-spinner";
import { useGetTrajectory } from "#/hooks/mutation/use-get-trajectory";
-import { downloadTrajectory } from "#/utils/download-files";
+import { downloadTrajectory } from "#/utils/download-trajectory";
import { displayErrorToast } from "#/utils/custom-toast-handlers";
function getEntryPoint(
diff --git a/frontend/src/components/features/controls/controls.tsx b/frontend/src/components/features/controls/controls.tsx
index 0984dae1e9..918980196b 100644
--- a/frontend/src/components/features/controls/controls.tsx
+++ b/frontend/src/components/features/controls/controls.tsx
@@ -1,12 +1,10 @@
import { useParams } from "react-router";
import React from "react";
-import posthog from "posthog-js";
import { AgentControlBar } from "./agent-control-bar";
import { AgentStatusBar } from "./agent-status-bar";
import { SecurityLock } from "./security-lock";
import { useUserConversation } from "#/hooks/query/use-user-conversation";
import { ConversationCard } from "../conversation-panel/conversation-card";
-import { DownloadModal } from "#/components/shared/download-modal";
interface ControlsProps {
setSecurityOpen: (isOpen: boolean) => void;
@@ -19,13 +17,6 @@ export function Controls({ setSecurityOpen, showSecurityLock }: ControlsProps) {
params.conversationId ?? null,
);
- const [downloading, setDownloading] = React.useState(false);
-
- const handleDownloadWorkspace = () => {
- posthog.capture("download_workspace_button_clicked");
- setDownloading(true);
- };
-
return (
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
@@ -39,17 +30,11 @@ export function Controls({ setSecurityOpen, showSecurityLock }: ControlsProps) {
<ConversationCard
variant="compact"
- onDownloadWorkspace={handleDownloadWorkspace}
title={conversation?.title ?? ""}
lastUpdatedAt={conversation?.created_at ?? ""}
selectedRepository={conversation?.selected_repository ?? null}
status={conversation?.status}
- />
-
- <DownloadModal
- initialPath=""
- onClose={() => setDownloading(false)}
- isOpen={downloading}
+ conversationId={conversation?.conversation_id}
/>
</div>
);
diff --git a/frontend/src/components/features/conversation-panel/conversation-card-context-menu.tsx b/frontend/src/components/features/conversation-panel/conversation-card-context-menu.tsx
index 33088c72f3..37355cf439 100644
--- a/frontend/src/components/features/conversation-panel/conversation-card-context-menu.tsx
+++ b/frontend/src/components/features/conversation-panel/conversation-card-context-menu.tsx
@@ -7,7 +7,7 @@ interface ConversationCardContextMenuProps {
onClose: () => void;
onDelete?: (event: React.MouseEvent<HTMLButtonElement>) => void;
onEdit?: (event: React.MouseEvent<HTMLButtonElement>) => void;
- onDownload?: (event: React.MouseEvent<HTMLButtonElement>) => void;
+ onDownloadViaVSCode?: (event: React.MouseEvent<HTMLButtonElement>) => void;
position?: "top" | "bottom";
}
@@ -15,7 +15,7 @@ export function ConversationCardContextMenu({
onClose,
onDelete,
onEdit,
- onDownload,
+ onDownloadViaVSCode,
position = "bottom",
}: ConversationCardContextMenuProps) {
const ref = useClickOutsideElement<HTMLUListElement>(onClose);
@@ -40,9 +40,12 @@ export function ConversationCardContextMenu({
Edit Title
</ContextMenuListItem>
)}
- {onDownload && (
- <ContextMenuListItem testId="download-button" onClick={onDownload}>
- Download Workspace
+ {onDownloadViaVSCode && (
+ <ContextMenuListItem
+ testId="download-vscode-button"
+ onClick={onDownloadViaVSCode}
+ >
+ Download via VS Code
</ContextMenuListItem>
)}
</ContextMenu>
diff --git a/frontend/src/components/features/conversation-panel/conversation-card.tsx b/frontend/src/components/features/conversation-panel/conversation-card.tsx
index 19a82be117..2b7f956a29 100644
--- a/frontend/src/components/features/conversation-panel/conversation-card.tsx
+++ b/frontend/src/components/features/conversation-panel/conversation-card.tsx
@@ -1,4 +1,5 @@
import React from "react";
+import posthog from "posthog-js";
import { formatTimeDelta } from "#/utils/format-time-delta";
import { ConversationRepoLink } from "./conversation-repo-link";
import {
@@ -13,31 +14,34 @@ interface ConversationCardProps {
onClick?: () => void;
onDelete?: () => void;
onChangeTitle?: (title: string) => void;
- onDownloadWorkspace?: () => void;
isActive?: boolean;
title: string;
selectedRepository: string | null;
lastUpdatedAt: string; // ISO 8601
status?: ProjectStatus;
variant?: "compact" | "default";
+ conversationId?: string; // Optional conversation ID for VS Code URL
}
export function ConversationCard({
onClick,
onDelete,
onChangeTitle,
- onDownloadWorkspace,
isActive,
title,
selectedRepository,
lastUpdatedAt,
status = "STOPPED",
variant = "default",
+ conversationId,
}: ConversationCardProps) {
const [contextMenuVisible, setContextMenuVisible] = React.useState(false);
const [titleMode, setTitleMode] = React.useState<"view" | "edit">("view");
const inputRef = React.useRef<HTMLInputElement>(null);
+ // We don't use the VS Code URL hook directly here to avoid test failures
+ // Instead, we'll add the download button conditionally
+
const handleBlur = () => {
if (inputRef.current?.value) {
const trimmed = inputRef.current.value.trim();
@@ -78,9 +82,32 @@ export function ConversationCard({
setContextMenuVisible(false);
};
- const handleDownload = (event: React.MouseEvent<HTMLButtonElement>) => {
+ const handleDownloadViaVSCode = async (
+ event: React.MouseEvent<HTMLButtonElement>,
+ ) => {
+ event.preventDefault();
event.stopPropagation();
- onDownloadWorkspace?.();
+ posthog.capture("download_via_vscode_button_clicked");
+
+ // Fetch the VS Code URL from the API
+ if (conversationId) {
+ try {
+ const response = await fetch(
+ `/api/conversations/${conversationId}/vscode-url`,
+ );
+ const data = await response.json();
+
+ if (data.vscode_url) {
+ window.open(data.vscode_url, "_blank");
+ } else {
+ console.error("VS Code URL not available", data.error);
+ }
+ } catch (error) {
+ console.error("Failed to fetch VS Code URL", error);
+ }
+ }
+
+ setContextMenuVisible(false);
};
React.useEffect(() => {
@@ -89,7 +116,11 @@ export function ConversationCard({
}
}, [titleMode]);
- const hasContextMenu = !!(onDelete || onChangeTitle || onDownloadWorkspace);
+ const hasContextMenu = !!(
+ onDelete ||
+ onChangeTitle ||
+ conversationId // If we have a conversation ID, we can show the download button
+ );
return (
<div
@@ -145,7 +176,9 @@ export function ConversationCard({
onClose={() => setContextMenuVisible(false)}
onDelete={onDelete && handleDelete}
onEdit={onChangeTitle && handleEdit}
- onDownload={onDownloadWorkspace && handleDownload}
+ onDownloadViaVSCode={
+ conversationId ? handleDownloadViaVSCode : undefined
+ }
position={variant === "compact" ? "top" : "bottom"}
/>
)}
diff --git a/frontend/src/components/shared/download-modal.tsx b/frontend/src/components/shared/download-modal.tsx
deleted file mode 100644
index 0d2b92d4fc..0000000000
--- a/frontend/src/components/shared/download-modal.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import { useDownloadProgress } from "#/hooks/use-download-progress";
-import { DownloadProgress } from "./download-progress";
-
-interface DownloadModalProps {
- initialPath: string;
- onClose: () => void;
- isOpen: boolean;
-}
-
-function ActiveDownload({
- initialPath,
- onClose,
-}: {
- initialPath: string;
- onClose: () => void;
-}) {
- const { progress, cancelDownload } = useDownloadProgress(
- initialPath,
- onClose,
- );
-
- return <DownloadProgress progress={progress} onCancel={cancelDownload} />;
-}
-
-export function DownloadModal({
- initialPath,
- onClose,
- isOpen,
-}: DownloadModalProps) {
- if (!isOpen) return null;
-
- return <ActiveDownload initialPath={initialPath} onClose={onClose} />;
-}
diff --git a/frontend/src/components/shared/download-progress.tsx b/frontend/src/components/shared/download-progress.tsx
deleted file mode 100644
index 9790ed46c7..0000000000
--- a/frontend/src/components/shared/download-progress.tsx
+++ /dev/null
@@ -1,94 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { I18nKey } from "#/i18n/declaration";
-
-export interface DownloadProgressState {
- filesTotal: number;
- filesDownloaded: number;
- currentFile: string;
- totalBytesDownloaded: number;
- bytesDownloadedPerSecond: number;
- isDiscoveringFiles: boolean;
-}
-
-interface DownloadProgressProps {
- progress: DownloadProgressState;
- onCancel: () => void;
-}
-
-export function DownloadProgress({
- progress,
- onCancel,
-}: DownloadProgressProps) {
- const { t } = useTranslation();
- const formatBytes = (bytes: number) => {
- const units = ["B", "KB", "MB", "GB"];
- let size = bytes;
- let unitIndex = 0;
- while (size >= 1024 && unitIndex < units.length - 1) {
- size /= 1024;
- unitIndex += 1;
- }
- return `${size.toFixed(1)} ${units[unitIndex]}`;
- };
-
- return (
- <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-20">
- <div className="bg-[#1C1C1C] rounded-lg p-6 max-w-md w-full mx-4 border border-[#525252]">
- <div className="mb-4">
- <h3 className="text-lg font-semibold mb-2 text-white">
- {progress.isDiscoveringFiles
- ? t(I18nKey.DOWNLOAD$PREPARING)
- : t(I18nKey.DOWNLOAD$DOWNLOADING)}
- </h3>
- <p className="text-sm text-gray-400 truncate">
- {progress.isDiscoveringFiles
- ? t(I18nKey.DOWNLOAD$FOUND_FILES, { count: progress.filesTotal })
- : progress.currentFile}
- </p>
- </div>
-
- <div className="mb-4">
- <div className="h-2 bg-[#2C2C2C] rounded-full overflow-hidden">
- {progress.isDiscoveringFiles ? (
- <div
- className="h-full bg-blue-500 animate-pulse"
- style={{ width: "100%" }}
- />
- ) : (
- <div
- className="h-full bg-blue-500 transition-all duration-300"
- style={{
- width: `${(progress.filesDownloaded / progress.filesTotal) * 100}%`,
- }}
- />
- )}
- </div>
- </div>
-
- <div className="flex justify-between text-sm text-gray-400">
- <span>
- {progress.isDiscoveringFiles
- ? t(I18nKey.DOWNLOAD$SCANNING)
- : t(I18nKey.DOWNLOAD$FILES_PROGRESS, {
- downloaded: progress.filesDownloaded,
- total: progress.filesTotal,
- })}
- </span>
- {!progress.isDiscoveringFiles && (
- <span>{formatBytes(progress.bytesDownloadedPerSecond)}/s</span>
- )}
- </div>
-
- <div className="mt-4 flex justify-end">
- <button
- type="button"
- onClick={onCancel}
- className="px-4 py-2 text-sm text-gray-400 hover:text-white transition-colors"
- >
- {t(I18nKey.DOWNLOAD$CANCEL)}
- </button>
- </div>
- </div>
- </div>
- );
-}
diff --git a/frontend/src/hooks/use-download-progress.ts b/frontend/src/hooks/use-download-progress.ts
deleted file mode 100644
index e4f400b6c1..0000000000
--- a/frontend/src/hooks/use-download-progress.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { useCallback, useEffect, useRef, useState } from "react";
-import { downloadFiles } from "#/utils/download-files";
-import { DownloadProgressState } from "#/components/shared/download-progress";
-import { useConversation } from "#/context/conversation-context";
-
-export const INITIAL_PROGRESS: DownloadProgressState = {
- filesTotal: 0,
- filesDownloaded: 0,
- currentFile: "",
- totalBytesDownloaded: 0,
- bytesDownloadedPerSecond: 0,
- isDiscoveringFiles: true,
-};
-
-export function useDownloadProgress(
- initialPath: string | undefined,
- onClose: () => void,
-) {
- const [isStarted, setIsStarted] = useState(false);
- const [progress, setProgress] =
- useState<DownloadProgressState>(INITIAL_PROGRESS);
- const progressRef = useRef<DownloadProgressState>(INITIAL_PROGRESS);
- const abortController = useRef<AbortController>(null);
- const { conversationId } = useConversation();
-
- // Create AbortController on mount
- useEffect(() => {
- const controller = new AbortController();
- abortController.current = controller;
- // Initialize progress ref with initial state
- progressRef.current = INITIAL_PROGRESS;
- return () => {
- controller.abort();
- abortController.current = null;
- };
- }, []); // Empty deps array - only run on mount/unmount
-
- // Start download when isStarted becomes true
- useEffect(() => {
- if (!isStarted) {
- setIsStarted(true);
- return;
- }
-
- if (!abortController.current) return;
-
- // Start download
- const download = async () => {
- try {
- await downloadFiles(conversationId, initialPath, {
- onProgress: (p) => {
- // Update both the ref and state
- progressRef.current = { ...p };
- setProgress((prev: DownloadProgressState) => ({ ...prev, ...p }));
- },
- signal: abortController.current!.signal,
- });
- onClose();
- } catch (error) {
- if (error instanceof Error && error.message === "Download cancelled") {
- onClose();
- } else {
- throw error;
- }
- }
- };
- download();
- }, [initialPath, onClose, isStarted]);
-
- // No longer need startDownload as it's handled in useEffect
-
- const cancelDownload = useCallback(() => {
- abortController.current?.abort();
- }, []);
-
- return {
- progress,
- cancelDownload,
- };
-}
diff --git a/frontend/src/utils/download-files.ts b/frontend/src/utils/download-files.ts
deleted file mode 100644
index 5e17c2b5c3..0000000000
--- a/frontend/src/utils/download-files.ts
+++ /dev/null
@@ -1,356 +0,0 @@
-import OpenHands from "#/api/open-hands";
-import { downloadWorkspace } from "./download-workspace";
-
-interface DownloadProgress {
- filesTotal: number;
- filesDownloaded: number;
- currentFile: string;
- totalBytesDownloaded: number;
- bytesDownloadedPerSecond: number;
- isDiscoveringFiles: boolean;
-}
-
-interface DownloadOptions {
- onProgress?: (progress: DownloadProgress) => void;
- signal?: AbortSignal;
-}
-
-/**
- * Checks if the File System Access API is supported
- */
-function isFileSystemAccessSupported(): boolean {
- return "showDirectoryPicker" in window;
-}
-
-/**
- * Checks if the Save File Picker API is supported
- */
-function isSaveFilePickerSupported(): boolean {
- return "showSaveFilePicker" in window;
-}
-
-/**
- * Creates subdirectories and returns the final directory handle
- */
-async function createSubdirectories(
- baseHandle: FileSystemDirectoryHandle,
- pathParts: string[],
-): Promise<FileSystemDirectoryHandle> {
- return pathParts.reduce(async (promise, part) => {
- const handle = await promise;
- return handle.getDirectoryHandle(part, { create: true });
- }, Promise.resolve(baseHandle));
-}
-
-/**
- * Recursively gets all files in a directory
- */
-async function getAllFiles(
- conversationID: string,
- path: string,
- progress: DownloadProgress,
- options?: DownloadOptions,
-): Promise<string[]> {
- const entries = await OpenHands.getFiles(conversationID, path);
-
- const processEntry = async (entry: string): Promise<string[]> => {
- if (options?.signal?.aborted) {
- throw new Error("Download cancelled");
- }
-
- const fullPath = path + entry;
- if (entry.endsWith("/")) {
- const subEntries = await OpenHands.getFiles(conversationID, fullPath);
- const subFilesPromises = subEntries.map((subEntry) =>
- processEntry(subEntry),
- );
- const subFilesArrays = await Promise.all(subFilesPromises);
- return subFilesArrays.flat();
- }
- const updatedProgress = {
- ...progress,
- filesTotal: progress.filesTotal + 1,
- currentFile: fullPath,
- };
- options?.onProgress?.(updatedProgress);
- return [fullPath];
- };
-
- const filePromises = entries.map((entry) => processEntry(entry));
- const fileArrays = await Promise.all(filePromises);
-
- const updatedProgress = {
- ...progress,
- isDiscoveringFiles: false,
- };
- options?.onProgress?.(updatedProgress);
-
- return fileArrays.flat();
-}
-
-/**
- * Process a batch of files
- */
-async function processBatch(
- conversationID: string,
- batch: string[],
- directoryHandle: FileSystemDirectoryHandle,
- progress: DownloadProgress,
- startTime: number,
- completedFiles: number,
- totalBytes: number,
- options?: DownloadOptions,
-): Promise<{ newCompleted: number; newBytes: number }> {
- if (options?.signal?.aborted) {
- throw new Error("Download cancelled");
- }
-
- // Process files in the batch in parallel
- const results = await Promise.all(
- batch.map(async (path) => {
- try {
- const newProgress = {
- ...progress,
- currentFile: path,
- isDiscoveringFiles: false,
- filesDownloaded: completedFiles,
- totalBytesDownloaded: totalBytes,
- bytesDownloadedPerSecond:
- totalBytes / ((Date.now() - startTime) / 1000),
- };
- options?.onProgress?.(newProgress);
-
- const content = await OpenHands.getFile(conversationID, path);
-
- // Save to the selected directory preserving structure
- const pathParts = path.split("/").filter(Boolean);
- const fileName = pathParts.pop() || "file";
- const dirHandle =
- pathParts.length > 0
- ? await createSubdirectories(directoryHandle, pathParts)
- : directoryHandle;
-
- // Create and write the file
- const fileHandle = await dirHandle.getFileHandle(fileName, {
- create: true,
- });
- const writable = await fileHandle.createWritable();
- await writable.write(content);
- await writable.close();
-
- // Return the size of this file
- return new Blob([content]).size;
- } catch (error) {
- // Silently handle file processing errors and return 0 bytes
- return 0;
- }
- }),
- );
-
- // Calculate batch totals
- const batchBytes = results.reduce((sum, size) => sum + size, 0);
- const newTotalBytes = totalBytes + batchBytes;
- const newCompleted =
- completedFiles + results.filter((size) => size > 0).length;
-
- // Update progress with batch results
- const updatedProgress = {
- ...progress,
- filesDownloaded: newCompleted,
- totalBytesDownloaded: newTotalBytes,
- bytesDownloadedPerSecond: newTotalBytes / ((Date.now() - startTime) / 1000),
- isDiscoveringFiles: false,
- };
- options?.onProgress?.(updatedProgress);
-
- return {
- newCompleted,
- newBytes: newTotalBytes,
- };
-}
-
-export async function downloadTrajectory(
- conversationId: string,
- data: unknown[] | null,
-): Promise<void> {
- try {
- if (!isSaveFilePickerSupported()) {
- throw new Error(
- "Your browser doesn't support downloading folders. Please use Chrome, Edge, or another browser that supports the File System Access API.",
- );
- }
- const options = {
- suggestedName: `trajectory-${conversationId}.json`,
- types: [
- {
- description: "JSON File",
- accept: {
- "application/json": [".json"],
- },
- },
- ],
- };
-
- const handle = await window.showSaveFilePicker(options);
- const writable = await handle.createWritable();
- await writable.write(JSON.stringify(data, null, 2));
- await writable.close();
- } catch (error) {
- throw new Error(
- `Failed to download file: ${error instanceof Error ? error.message : String(error)}`,
- );
- }
-}
-
-/**
- * Downloads files from the workspace one by one
- * @param initialPath Initial path to start downloading from. If not provided, downloads from root
- * @param options Download options including progress callback and abort signal
- */
-export async function downloadFiles(
- conversationID: string,
- initialPath?: string,
- options?: DownloadOptions,
-): Promise<void> {
- const startTime = Date.now();
- const progress: DownloadProgress = {
- filesTotal: 0, // Will be updated during file discovery
- filesDownloaded: 0,
- currentFile: "",
- totalBytesDownloaded: 0,
- bytesDownloadedPerSecond: 0,
- isDiscoveringFiles: true,
- };
-
- try {
- // Check if File System Access API is supported
- if (!isFileSystemAccessSupported()) {
- throw new Error(
- "Your browser doesn't support downloading folders. Please use Chrome, Edge, or another browser that supports the File System Access API.",
- );
- }
-
- // Show directory picker first
- let directoryHandle: FileSystemDirectoryHandle;
- try {
- directoryHandle = await window.showDirectoryPicker();
- } catch (error) {
- if (error instanceof Error && error.name === "AbortError") {
- throw new Error("Download cancelled");
- }
- if (error instanceof Error && error.name === "SecurityError") {
- throw new Error(
- "Permission denied. Please allow access to the download location when prompted.",
- );
- }
- throw new Error("Failed to select download location. Please try again.");
- }
-
- // Then recursively get all files
- const files = await getAllFiles(
- conversationID,
- initialPath || "",
- progress,
- options,
- );
-
- // Set isDiscoveringFiles to false now that we have the full list and preserve filesTotal
- const finalTotal = progress.filesTotal;
- options?.onProgress?.({
- ...progress,
- filesTotal: finalTotal,
- isDiscoveringFiles: false,
- });
-
- // Verify we still have permission after the potentially long file scan
- try {
- // Try to create and write to a test file to verify permissions
- const testHandle = await directoryHandle.getFileHandle(
- ".openhands-test",
- { create: true },
- );
- const writable = await testHandle.createWritable();
- await writable.close();
- } catch (error) {
- if (
- error instanceof Error &&
- error.message.includes("User activation is required")
- ) {
- // Ask for permission again
- try {
- directoryHandle = await window.showDirectoryPicker();
- } catch (permissionError) {
- if (
- permissionError instanceof Error &&
- permissionError.name === "AbortError"
- ) {
- throw new Error("Download cancelled");
- }
- if (
- permissionError instanceof Error &&
- permissionError.name === "SecurityError"
- ) {
- throw new Error(
- "Permission denied. Please allow access to the download location when prompted.",
- );
- }
- throw new Error(
- "Failed to select download location. Please try again.",
- );
- }
- } else {
- throw error;
- }
- }
-
- // Process files in parallel batches to avoid overwhelming the browser
- const BATCH_SIZE = 5;
- const batches = Array.from(
- { length: Math.ceil(files.length / BATCH_SIZE) },
- (_, i) => files.slice(i * BATCH_SIZE, (i + 1) * BATCH_SIZE),
- );
-
- // Keep track of completed files across all batches
- let completedFiles = 0;
- let totalBytesDownloaded = 0;
-
- // Process batches sequentially to maintain order and avoid overwhelming the browser
- await batches.reduce(
- (promise, batch) =>
- promise.then(async () => {
- const { newCompleted, newBytes } = await processBatch(
- conversationID,
- batch,
- directoryHandle,
- progress,
- startTime,
- completedFiles,
- totalBytesDownloaded,
- options,
- );
- completedFiles = newCompleted;
- totalBytesDownloaded = newBytes;
- }),
- Promise.resolve(),
- );
- } catch (error) {
- if (error instanceof Error && error.message === "Download cancelled") {
- throw error;
- }
- // Fallback to old style download
- if (
- error instanceof Error &&
- (error.message.includes("browser doesn't support") ||
- error.message.includes("Failed to select") ||
- error.message.includes("Permission denied"))
- ) {
- await downloadWorkspace(conversationID);
- return;
- }
-
- // Otherwise, wrap it with a generic message
- throw new Error(
- `Failed to download files: ${error instanceof Error ? error.message : String(error)}`,
- );
- }
-}
diff --git a/frontend/src/utils/download-trajectory.ts b/frontend/src/utils/download-trajectory.ts
new file mode 100644
index 0000000000..41878d7089
--- /dev/null
+++ b/frontend/src/utils/download-trajectory.ts
@@ -0,0 +1,30 @@
+function isSaveFilePickerSupported(): boolean {
+ return typeof window !== "undefined" && "showSaveFilePicker" in window;
+}
+
+export async function downloadTrajectory(
+ conversationId: string,
+ data: unknown[] | null,
+): Promise<void> {
+ if (!isSaveFilePickerSupported()) {
+ throw new Error(
+ "Your browser doesn't support downloading files. Please use Chrome, Edge, or another browser that supports the File System Access API.",
+ );
+ }
+ const options: SaveFilePickerOptions = {
+ suggestedName: `trajectory-${conversationId}.json`,
+ types: [
+ {
+ description: "JSON File",
+ accept: {
+ "application/json": [".json"],
+ },
+ },
+ ],
+ };
+
+ const fileHandle = await window.showSaveFilePicker(options);
+ const writable = await fileHandle.createWritable();
+ await writable.write(JSON.stringify(data, null, 2));
+ await writable.close();
+}
diff --git a/frontend/src/utils/download-workspace.ts b/frontend/src/utils/download-workspace.ts
deleted file mode 100644
index 324a5c26ac..0000000000
--- a/frontend/src/utils/download-workspace.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import OpenHands from "#/api/open-hands";
-
-/**
- * Downloads the current workspace as a .zip file.
- */
-export const downloadWorkspace = async (conversationId: string) => {
- const blob = await OpenHands.getWorkspaceZip(conversationId);
-
- const url = URL.createObjectURL(blob);
- const link = document.createElement("a");
- link.href = url;
- link.setAttribute("download", "workspace.zip");
- document.body.appendChild(link);
- link.click();
- link.parentNode?.removeChild(link);
-};