File size: 9,794 Bytes
246d201 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 |
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;
}
/**
* 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,
};
}
/**
* 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)}`,
);
}
}
|