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
refactor: remove polling, add DownloadsProvider and reorganise
  • Loading branch information
iamEvanYT committed Apr 7, 2026
commit c240dd2db3453415c8a17a8827c201489872741f
6 changes: 6 additions & 0 deletions src/main/controllers/downloads-controller/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
upsertDownloadRecord
} from "@/saving/downloads";
import type { DownloadInsert, DownloadRow } from "@/saving/db/schema";
import { fireDownloadsChanged } from "@/ipc/browser/downloads";

type MacOSProgressModule = typeof import("./macos-progress");

Expand Down Expand Up @@ -146,6 +147,7 @@ class DownloadsController {
startTime: Math.floor(record.startTime / 1000)
});

fireDownloadsChanged();
debugPrint("DOWNLOADS", `Queued interrupted download restore for ${downloadId}`);
return true;
} catch (err) {
Expand Down Expand Up @@ -179,6 +181,7 @@ class DownloadsController {
canResume: false,
endTime: Date.now()
});
fireDownloadsChanged();
debugPrint("DOWNLOADS", `Marked inactive download ${downloadId} as cancelled`);
return true;
}
Expand Down Expand Up @@ -244,6 +247,7 @@ class DownloadsController {
this.activeDownloadsById.set(downloadId, activeDownload);

upsertDownloadRecord(this.buildDownloadInsert(item, metadata, existingRecord));
fireDownloadsChanged();

debugPrint("DOWNLOADS", `Download requested: ${suggestedFilename} (${downloadId})`);

Expand Down Expand Up @@ -378,6 +382,7 @@ class DownloadsController {
}

this.persistDownloadSnapshot(active, state, true);
fireDownloadsChanged();
debugPrint("DOWNLOADS", `Download ${state}: ${this.getSavePath(active.item) ?? active.item.getFilename()}`);
}

Expand Down Expand Up @@ -447,6 +452,7 @@ class DownloadsController {
});

meta.lastPersistedAt = now;
fireDownloadsChanged();
}

private getPersistedState(
Expand Down
12 changes: 11 additions & 1 deletion src/main/ipc/browser/downloads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@ import fs from "node:fs";
import { ipcMain, shell } from "electron";
import { downloadsController } from "@/controllers/downloads-controller";
import { deleteDownloadRecord, getDownloadRecord, listDownloads } from "@/saving/downloads";
import { sendMessageToListeners } from "@/ipc/listeners-manager";

export function fireDownloadsChanged() {
sendMessageToListeners("downloads:on-changed");
}

ipcMain.handle("downloads:list", () => {
return downloadsController.listDownloads();
Expand Down Expand Up @@ -38,16 +43,21 @@ ipcMain.handle("downloads:open-file", (_event, downloadId: string) => {
});
Comment on lines +38 to +43

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 shell.openPath result not awaited — errors silently swallowed

shell.openPath() returns a Promise<string> where an empty string means success and a non-empty string is the OS error message. Because the promise is not awaited, any failure (no associated application, permission denied, file moved/deleted since the record was saved) is silently dropped. The handler always returns true whenever it finds a completed record, so the renderer's if (!ok) toast.error("Could not open file") guard is never triggered — users get no feedback when the open fails.

Suggested change
ipcMain.handle("downloads:open-file", (_event, downloadId: string) => {
const record = getDownloadRecord(downloadId);
if (!record?.savePath || record.state !== "completed") return false;
shell.openPath(record.savePath);
return true;
});
ipcMain.handle("downloads:open-file", async (_event, downloadId: string) => {
const record = getDownloadRecord(downloadId);
if (!record?.savePath || record.state !== "completed") return false;
const err = await shell.openPath(record.savePath);
return err === "";
});

Comment on lines +38 to +43

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

shell.openPath result is not awaited, success always returned.

shell.openPath() returns Promise<string> where an empty string indicates success and a non-empty string contains an error message. The current code returns true immediately without checking the result, so failures are silently ignored and the renderer always receives success.

Await and check the result
-ipcMain.handle("downloads:open-file", (_event, downloadId: string) => {
+ipcMain.handle("downloads:open-file", async (_event, downloadId: string) => {
   const record = getDownloadRecord(downloadId);
   if (!record?.savePath || record.state !== "completed") return false;
-  shell.openPath(record.savePath);
-  return true;
+  const error = await shell.openPath(record.savePath);
+  return error === "";
 });
📝 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:open-file", (_event, downloadId: string) => {
const record = getDownloadRecord(downloadId);
if (!record?.savePath || record.state !== "completed") return false;
shell.openPath(record.savePath);
return true;
});
ipcMain.handle("downloads:open-file", async (_event, downloadId: string) => {
const record = getDownloadRecord(downloadId);
if (!record?.savePath || record.state !== "completed") return false;
const error = await shell.openPath(record.savePath);
return error === "";
});
🤖 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 38 - 43, The handler for
"downloads:open-file" currently calls shell.openPath(record.savePath) but
doesn’t await its Promise, so it always returns true; modify the ipcMain.handle
callback (the "downloads:open-file" handler that uses getDownloadRecord) to
await shell.openPath(record.savePath) and check its returned string (empty =
success, non-empty = error message) and return true only on success and false on
error (optionally log or process the error string before returning false).


ipcMain.handle("downloads:remove-record", (_event, downloadId: string) => {
return deleteDownloadRecord(downloadId);
const ok = deleteDownloadRecord(downloadId);
if (ok) fireDownloadsChanged();
return ok;
});

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();
});
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[]) => {
Expand Down
3 changes: 3 additions & 0 deletions src/preload/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,9 @@ const downloadsAPI: FlowDownloadsAPI = {
},
checkFilesExist: async (downloadIds: string[]) => {
return ipcRenderer.invoke("downloads:check-files-exist", downloadIds);
},
onChanged: (callback: () => void) => {
return listenOnIPCChannel("downloads:on-changed", callback);
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,11 @@ import { useSpaces } from "@/components/providers/spaces-provider";
import { Button } from "@/components/ui/button";
import { PopoverTrigger } from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { filenameFromRecord, isActive } from "@/components/downloads/manager/utils";
import type { DownloadRecord } from "~/types/downloads";
import { DownloadIcon, FileText } from "lucide-react";
import { useCallback, useEffect, useState } from "react";

const POLL_MS = 1500;

function filenameFromRecord(r: DownloadRecord): string {
if (r.savePath) {
const parts = r.savePath.split(/[/\\]/);
return parts[parts.length - 1] || r.suggestedFilename;
}
return r.suggestedFilename;
}

function relativeTime(ts: number): string {
const now = Date.now();
const diffSec = Math.floor((now - ts) / 1000);
Expand Down Expand Up @@ -44,7 +35,7 @@ function DownloadRow({
setOpen: (open: boolean) => void;
}) {
const filename = filenameFromRecord(dl);
const isActive = dl.state === "progressing" || dl.state === "paused";
const active = isActive(dl.state);

const handleClick = () => {
if (dl.state === "completed" && !fileMissing) {
Expand All @@ -60,12 +51,9 @@ function DownloadRow({
onClick={handleClick}
className="flex items-center gap-3 px-3 py-2.5 rounded-lg hover:bg-accent/50 cursor-pointer transition-colors"
>
{/* File icon */}
<div className="shrink-0 size-10 rounded-lg bg-muted/80 border border-border/30 flex items-center justify-center">
<FileText className="size-5 text-muted-foreground" />
</div>

{/* Text */}
<div className="min-w-0 flex-1">
<p
className={cn(
Expand All @@ -76,7 +64,7 @@ function DownloadRow({
{filename}
</p>
<p className="text-xs text-muted-foreground mt-0.5 truncate leading-snug">
{isActive
{active
? dl.state === "paused"
? "Paused"
: "Downloading…"
Expand All @@ -102,7 +90,7 @@ export function DownloadsPopover() {
const all = await flow.downloads.list();
setDownloads(all);
const idsToCheck = all
.filter((d) => d.state !== "progressing" && d.state !== "paused" && d.savePath)
.filter((d) => !isActive(d.state) && d.savePath)
.map((d) => d.id);
if (idsToCheck.length > 0) {
const existence = await flow.downloads.checkFilesExist(idsToCheck);
Expand All @@ -113,16 +101,18 @@ export function DownloadsPopover() {
}
}, []);
Comment on lines +147 to +159

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 | 🟡 Minor

Missing mount guard - potential setState after unmount.

Unlike the DownloadsProvider, this component's fetchDownloads doesn't guard against setting state after the component unmounts. If the popover closes while checkFilesExist is in flight, React will log a warning about setting state on an unmounted component.

Add mount guard
+  const mountedRef = useRef(true);
+
+  useEffect(() => {
+    mountedRef.current = true;
+    return () => {
+      mountedRef.current = false;
+    };
+  }, []);
+
   const fetchDownloads = useCallback(async () => {
     try {
       const all = await flow.downloads.list();
+      if (!mountedRef.current) return;
       setDownloads(all);
       const idsToCheck = all.filter((d) => !isActive(d.state) && d.savePath).map((d) => d.id);
       if (idsToCheck.length > 0) {
         const existence = await flow.downloads.checkFilesExist(idsToCheck);
-        setFileExistence(existence);
+        if (mountedRef.current) setFileExistence(existence);
       }
     } catch {
       // silently ignore
     }
   }, []);
📝 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
const fetchDownloads = useCallback(async () => {
try {
const all = await flow.downloads.list();
setDownloads(all);
const idsToCheck = all.filter((d) => !isActive(d.state) && d.savePath).map((d) => d.id);
if (idsToCheck.length > 0) {
const existence = await flow.downloads.checkFilesExist(idsToCheck);
setFileExistence(existence);
}
} catch {
// silently ignore
}
}, []);
const mountedRef = useRef(true);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
const fetchDownloads = useCallback(async () => {
try {
const all = await flow.downloads.list();
if (!mountedRef.current) return;
setDownloads(all);
const idsToCheck = all.filter((d) => !isActive(d.state) && d.savePath).map((d) => d.id);
if (idsToCheck.length > 0) {
const existence = await flow.downloads.checkFilesExist(idsToCheck);
if (mountedRef.current) setFileExistence(existence);
}
} catch {
// silently ignore
}
}, []);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@src/renderer/src/components/browser-ui/browser-sidebar/_components/bottom/downloads-popover.tsx`
around lines 147 - 159, fetchDownloads can call setDownloads/setFileExistence
after the component unmounts; add a mount guard to avoid setState-after-unmount
warnings. Inside the component create a ref like isMounted and set it true on
mount and false in a cleanup useEffect, then inside the useCallback
fetchDownloads check isMounted.current before calling setDownloads and
setFileExistence (and after awaiting flow.downloads.checkFilesExist) so no state
updates occur if the popover has closed; ensure the cleanup toggles the ref to
false to prevent updates from in-flight promises.


// Fetch on open + listen for changes while open
useEffect(() => {
if (!open) return;
void fetchDownloads();
const id = setInterval(() => void fetchDownloads(), POLL_MS);
return () => clearInterval(id);
const unsubscribe = flow.downloads.onChanged(() => {
void fetchDownloads();
});
return unsubscribe;
}, [open, fetchDownloads]);

// Show up to 5 most recent, prioritizing active downloads
const active = downloads.filter((d) => d.state === "progressing" || d.state === "paused");
const recent = downloads.filter((d) => d.state !== "progressing" && d.state !== "paused");
const active = downloads.filter((d) => isActive(d.state));
const recent = downloads.filter((d) => !isActive(d.state));
const shown = [...active, ...recent].slice(0, 5);
const hasActive = active.length > 0;

Expand Down
Loading