Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix: issues
  • Loading branch information
iamEvanYT committed Apr 7, 2026
commit 26df532f6edae92ae8890ee4ea25669dce0d4bf4
5 changes: 3 additions & 2 deletions drizzle/0004_add_download_manager.sql
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@ CREATE TABLE `downloads` (
`updated_at` integer NOT NULL
);
--> statement-breakpoint
CREATE INDEX `idx_downloads_state` ON `downloads` (`state`);--> statement-breakpoint
CREATE INDEX `idx_downloads_updated_at` ON `downloads` (`updated_at`);
CREATE INDEX `idx_downloads_state` ON `downloads` (`state`);
--> statement-breakpoint
CREATE INDEX `idx_downloads_updated_at` ON `downloads` (`updated_at`);
103 changes: 90 additions & 13 deletions src/main/controllers/downloads-controller/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ type MacOSProgressModule = typeof import("./macos-progress");

const PROFILES_DIR = path.join(FLOW_DATA_DIR, "Profiles");
const DOWNLOAD_PROGRESS_PERSIST_INTERVAL_MS = 1000;
const PENDING_RESUME_TIMEOUT_MS = 30_000;

interface DownloadMetadata {
downloadId: string;
Expand All @@ -41,6 +42,8 @@ interface PendingResumeRequest {
savePath: string;
lastUrl: string;
autoResume: boolean;
enqueuedAt: number;
timeoutId: ReturnType<typeof setTimeout>;
}

class DownloadsController {
Expand Down Expand Up @@ -136,16 +139,22 @@ class DownloadsController {
autoResume: true
});
Comment on lines +133 to +140

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Reject duplicate resume requests for the same download.

Until will-download arrives, this record stays paused/interrupted, so resumeDownload() can be called again and queue a second createInterruptedDownload() for the same downloadId. Once both events arrive, activeDownloadsById gets overwritten and updated/done from the first item can be applied to the second one.

💡 Suggested fix
       const targetSession = this.getSessionForDownload(record.originProfileId);
       this.registerSession(targetSession);
+      if ((this.pendingResumeRequests.get(targetSession) ?? []).some((r) => r.downloadId === downloadId)) {
+        return false;
+      }
       this.enqueuePendingResume(targetSession, {
         downloadId,
         savePath: record.savePath!,
         lastUrl: record.urlChain[record.urlChain.length - 1] ?? record.url,
         autoResume: true
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/controllers/downloads-controller/index.ts` around lines 133 - 140,
resumeDownload is queuing duplicate interrupted resumes for the same downloadId;
before calling getSessionForDownload/registerSession/enqueuePendingResume, check
for and reject duplicates by verifying if an in-flight or pending resume already
exists for the downloadId (consult activeDownloadsById and the pending-resume
queue inside enqueuePendingResume or a new pendingResumeById map), and return
early if found; alternatively deduplicate inside enqueuePendingResume by using
downloadId as the unique key so createInterruptedDownload cannot be queued twice
for the same downloadId (refer to functions/members: resumeDownload,
getSessionForDownload, enqueuePendingResume, createInterruptedDownload,
activeDownloadsById).


targetSession.createInterruptedDownload({
path: record.savePath!,
urlChain: record.urlChain,
mimeType: record.mimeType ?? undefined,
offset: record.receivedBytes,
length: record.totalBytes,
lastModified: record.lastModified ?? undefined,
eTag: record.eTag ?? undefined,
startTime: Math.floor(record.startTime / 1000)
});
try {
targetSession.createInterruptedDownload({
path: record.savePath!,
urlChain: record.urlChain,
mimeType: record.mimeType ?? undefined,
offset: record.receivedBytes,
length: record.totalBytes,
lastModified: record.lastModified ?? undefined,
eTag: record.eTag ?? undefined,
startTime: Math.floor(record.startTime / 1000)
});
} catch (createErr) {
// Clean up the pending request since createInterruptedDownload failed synchronously
this.removePendingResume(targetSession, downloadId);
throw createErr;
}

fireDownloadsChanged();
debugPrint("DOWNLOADS", `Queued interrupted download restore for ${downloadId}`);
Expand Down Expand Up @@ -493,15 +502,64 @@ class DownloadsController {
}

private canRestoreDownload(record: DownloadRow): boolean {
return !!record.canResume && !!record.savePath && record.urlChain.length > 0 && record.totalBytes > 0;
return (
!!record.canResume &&
!!record.savePath &&
record.urlChain.length > 0 &&
record.totalBytes > 0 &&
(record.state === "interrupted" || record.state === "paused")
);
}

private enqueuePendingResume(session: Session, request: PendingResumeRequest): void {
private enqueuePendingResume(
session: Session,
request: Omit<PendingResumeRequest, "enqueuedAt" | "timeoutId">
): void {
const queue = this.pendingResumeRequests.get(session) ?? [];
queue.push(request);

const timeoutId = setTimeout(() => {
this.expirePendingResume(session, request.downloadId);
}, PENDING_RESUME_TIMEOUT_MS);

const fullRequest: PendingResumeRequest = {
...request,
enqueuedAt: Date.now(),
timeoutId
};

queue.push(fullRequest);
this.pendingResumeRequests.set(session, queue);
}

private expirePendingResume(session: Session, downloadId: string): void {
const queue = this.pendingResumeRequests.get(session);
if (!queue) return;

const index = queue.findIndex((r) => r.downloadId === downloadId);
if (index < 0) return;

const [expired] = queue.splice(index, 1);
if (queue.length === 0) {
this.pendingResumeRequests.delete(session);
}

debugError(
"DOWNLOADS",
`Pending resume request for download ${expired.downloadId} timed out after ${PENDING_RESUME_TIMEOUT_MS}ms. ` +
`The will-download event was never fired. This may indicate that createInterruptedDownload failed silently.`
);

// Mark the download as failed so the user knows it didn't resume
const record = getDownloadRecord(downloadId);
if (record && (record.state === "interrupted" || record.state === "paused")) {
updateDownloadRecord(downloadId, {
canResume: false,
updatedAt: Date.now()
});
fireDownloadsChanged();
}
}

private consumePendingResume(session: Session, item: DownloadItem): PendingResumeRequest | undefined {
const queue = this.pendingResumeRequests.get(session);
if (!queue || queue.length === 0) return undefined;
Expand All @@ -517,6 +575,7 @@ class DownloadsController {

if (matchIndex >= 0) {
const [match] = queue.splice(matchIndex, 1);
clearTimeout(match.timeoutId);
if (queue.length === 0) {
this.pendingResumeRequests.delete(session);
}
Expand All @@ -525,13 +584,31 @@ class DownloadsController {

if (queue.length === 1 && item.getState() === "interrupted") {
const [fallback] = queue.splice(0, 1);
clearTimeout(fallback.timeoutId);
this.pendingResumeRequests.delete(session);
return fallback;
}

return undefined;
}

private removePendingResume(session: Session, downloadId: string): boolean {
const queue = this.pendingResumeRequests.get(session);
if (!queue) return false;

const index = queue.findIndex((r) => r.downloadId === downloadId);
if (index < 0) return false;

const [removed] = queue.splice(index, 1);
clearTimeout(removed.timeoutId);

if (queue.length === 0) {
this.pendingResumeRequests.delete(session);
}

return true;
}

private getUrlChain(item: DownloadItem): string[] {
const chain = item.getURLChain();
return chain.length > 0 ? chain : [item.getURL()];
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,29 @@
import { app as electronApp } from "electron";
import { HonoApp } from ".";
import { bufferToArrayBuffer } from "@/modules/utils";
import { FLOW_DATA_DIR } from "@/modules/paths";
import path from "path";

type FileIconSize = "small" | "normal" | "large";

const FILE_ICON_SIZES = new Set<FileIconSize>(["small", "normal", "large"]);

/**
* Validates that a given path is within one of the allowed directories.
* This prevents path traversal attacks and file existence probing.
*/
function isPathAllowed(targetPath: string): boolean {
const resolvedPath = path.resolve(targetPath);
const allowedDirs = [electronApp.getPath("downloads"), FLOW_DATA_DIR];

return allowedDirs.some((allowedDir) => {
const resolvedAllowedDir = path.resolve(allowedDir);
// Ensure the path starts with the allowed directory followed by a separator
// to prevent matching partial directory names (e.g., /downloads-evil)
return resolvedPath === resolvedAllowedDir || resolvedPath.startsWith(resolvedAllowedDir + path.sep);
});
}

export function registerFileIconRoutes(app: HonoApp) {
app.get("/file-icon", async (c) => {
try {
Expand All @@ -20,6 +37,12 @@ export function registerFileIconRoutes(app: HonoApp) {
return c.text("No file path or filename provided", 400);
}

// Validate the path is within allowed directories to prevent
// path traversal attacks and file existence probing
if (!isPathAllowed(targetPath)) {
return c.text("Access denied: path outside allowed directories", 403);
}

const size: FileIconSize =
requestedSize && FILE_ICON_SIZES.has(requestedSize as FileIconSize)
? (requestedSize as FileIconSize)
Expand Down
25 changes: 14 additions & 11 deletions src/main/ipc/browser/downloads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,18 @@ ipcMain.handle("downloads:clear-completed", () => {
if (changed) fireDownloadsChanged();
});
Comment on lines +51 to +61

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Consider checking deletion result in clear-completed loop.

deleteDownloadRecord returns a boolean, but the loop ignores individual deletion failures. If a deletion fails, changed is still set to true. This could lead to inconsistent state notifications.

Track actual deletions
 ipcMain.handle("downloads:clear-completed", () => {
   const downloads = listDownloads();
   let changed = false;
   for (const dl of downloads) {
     if (dl.state === "completed" || dl.state === "cancelled") {
-      deleteDownloadRecord(dl.id);
-      changed = true;
+      const deleted = deleteDownloadRecord(dl.id);
+      if (deleted) changed = true;
     }
   }
   if (changed) fireDownloadsChanged();
 });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
ipcMain.handle("downloads:clear-completed", () => {
const downloads = listDownloads();
let changed = false;
for (const dl of downloads) {
if (dl.state === "completed" || dl.state === "cancelled") {
deleteDownloadRecord(dl.id);
changed = true;
}
}
if (changed) fireDownloadsChanged();
});
ipcMain.handle("downloads:clear-completed", () => {
const downloads = listDownloads();
let changed = false;
for (const dl of downloads) {
if (dl.state === "completed" || dl.state === "cancelled") {
const deleted = deleteDownloadRecord(dl.id);
if (deleted) changed = true;
}
}
if (changed) fireDownloadsChanged();
});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/ipc/browser/downloads.ts` around lines 51 - 61, The clear-completed
handler currently sets changed = true regardless of whether
deleteDownloadRecord(dl.id) actually succeeded; update the loop in the
ipcMain.handle("downloads:clear-completed") callback to check the boolean result
of deleteDownloadRecord for each dl and only set changed = true when
deleteDownloadRecord(...) returns true, optionally collect/log failed deletions
and avoid firing fireDownloadsChanged() if no records were actually removed;
keep references to listDownloads(), deleteDownloadRecord(), and
fireDownloadsChanged() so the change is localized to that handler.


ipcMain.handle("downloads:check-files-exist", (_event, downloadIds: string[]) => {
const result: Record<string, boolean> = {};
for (const id of downloadIds) {
const record = getDownloadRecord(id);
if (!record?.savePath) {
result[id] = false;
} else {
result[id] = fs.existsSync(record.savePath);
}
}
return result;
ipcMain.handle("downloads:check-files-exist", async (_event, downloadIds: string[]) => {
const checks = await Promise.all(
downloadIds.map(async (id) => {
const record = getDownloadRecord(id);
if (!record?.savePath) return [id, false] as const;
try {
await fs.promises.access(record.savePath);
return [id, true] as const;
} catch {
return [id, false] as const;
}
})
);
return Object.fromEntries(checks);
});
7 changes: 2 additions & 5 deletions src/renderer/src/components/downloads/manager/provider.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { DownloadRecord, DownloadState } from "~/types/downloads";
import type { DownloadRecord } from "~/types/downloads";
import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from "react";
import { isActive } from "./utils";

interface DownloadsContextValue {
downloads: DownloadRecord[];
Expand All @@ -11,10 +12,6 @@ interface DownloadsContextValue {

const DownloadsContext = createContext<DownloadsContextValue | null>(null);

function isActive(state: DownloadState): boolean {
return state === "progressing" || state === "paused";
}

export function DownloadsProvider({ children }: { children: ReactNode }) {
const [downloads, setDownloads] = useState<DownloadRecord[]>([]);
const [fileExistence, setFileExistence] = useState<Record<string, boolean>>({});
Expand Down
Loading