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
Next Next commit
feat: new download controller with finder progress bar handling
  • Loading branch information
iamEvanYT committed Apr 7, 2026
commit 50a633fedad83dabd58443de44538b5f43510587
203 changes: 203 additions & 0 deletions src/main/controllers/downloads-controller/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
import { app, type DownloadItem, type Session } from "electron";
import path from "path";
import { debugError, debugPrint } from "@/modules/output";

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

interface DownloadMetadata {
progressId: string | null;
savePath: string | null;
lastUpdate: number;
lastBytes: number;
initialTotalBytes: number;
syncingProgress: boolean;
}

class DownloadsController {
private readonly activeDownloads = new WeakMap<DownloadItem, DownloadMetadata>();
private readonly registeredSessions = new WeakSet<Session>();
private macosProgress: MacOSProgressModule | null = null;
private macosProgressLoad: Promise<MacOSProgressModule | null> | null = null;

public registerSession(session: Session): void {
if (this.registeredSessions.has(session)) {
return;
}

session.on("will-download", (_event, item) => {
this.handleWillDownload(item);
});

this.registeredSessions.add(session);
debugPrint("DOWNLOADS", "Download handler registered for session");
}

private async ensureMacosProgressModule(): Promise<MacOSProgressModule | null> {
if (process.platform !== "darwin") return null;
if (this.macosProgress) return this.macosProgress;

if (!this.macosProgressLoad) {
this.macosProgressLoad = import("./macos-progress")
.then((module) => {
this.macosProgress = module;
return module;
})
.catch((err) => {
debugError("DOWNLOADS", "Failed to load macOS progress module:", err);
return null;
});
}

return this.macosProgressLoad;
}

private handleWillDownload(item: DownloadItem): void {
const suggestedFilename = item.getFilename();
const defaultPath = path.join(app.getPath("downloads"), suggestedFilename);

item.setSaveDialogOptions({
defaultPath,
properties: ["createDirectory", "showOverwriteConfirmation"]
});

const metadata: DownloadMetadata = {
progressId: null,
savePath: null,
lastUpdate: Date.now(),
lastBytes: 0,
initialTotalBytes: item.getTotalBytes(),
syncingProgress: false
};

this.activeDownloads.set(item, metadata);

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

this.queueProgressSync(item, metadata);

item.on("updated", (_event, state) => {
const current = this.activeDownloads.get(item);
if (!current) return;

this.queueProgressSync(item, current);

if (state === "progressing") {
this.updateMacProgress(current, item);
} else if (state === "interrupted") {
debugPrint("DOWNLOADS", `Download interrupted: ${item.getFilename()}`);
}
});

item.once("done", (_event, state) => {
const current = this.activeDownloads.get(item);
if (!current) return;

this.activeDownloads.delete(item);
void this.handleDone(item, current, state);
});
}

private queueProgressSync(item: DownloadItem, meta: DownloadMetadata): void {
if (meta.syncingProgress) return;

meta.syncingProgress = true;
void this.syncMacProgress(item, meta).finally(() => {
meta.syncingProgress = false;
});
}

private async syncMacProgress(item: DownloadItem, meta: DownloadMetadata): Promise<void> {
const mp = await this.ensureMacosProgressModule();
if (!mp) return;

const savePath = this.getSavePath(item);
if (!savePath) return;

if (!meta.progressId) {
meta.savePath = savePath;
meta.initialTotalBytes = item.getTotalBytes();
meta.progressId = mp.createFileProgress(savePath, meta.initialTotalBytes, () => {
debugPrint("DOWNLOADS", `Cancel requested from Finder for: ${item.getFilename()}`);
item.cancel();
});
return;
}

if (meta.savePath && meta.savePath !== savePath) {
const nextProgressId = mp.recreateFileProgressAtPath(meta.progressId, savePath, () => {
debugPrint("DOWNLOADS", `Cancel requested from Finder for: ${item.getFilename()}`);
item.cancel();
});

if (nextProgressId) {
meta.progressId = nextProgressId;
}
meta.savePath = savePath;
Comment on lines +336 to +345

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

Keep macOS progress recreation retryable on failure.

recreateFileProgressAtPath() can return null. This branch still advances meta.savePath, so later syncs stop retrying while meta.progressId still points at a removed progress entry.

💡 Suggested fix
       const nextProgressId = mp.recreateFileProgressAtPath(meta.progressId, savePath, () => {
         debugPrint("DOWNLOADS", `Cancel requested from Finder for: ${item.getFilename()}`);
         item.cancel();
       });
 
       if (nextProgressId) {
         meta.progressId = nextProgressId;
+        meta.savePath = savePath;
+      } else {
+        meta.progressId = null;
       }
-      meta.savePath = savePath;
     }
   }
📝 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
if (meta.savePath && meta.savePath !== savePath) {
const nextProgressId = mp.recreateFileProgressAtPath(meta.progressId, savePath, () => {
debugPrint("DOWNLOADS", `Cancel requested from Finder for: ${item.getFilename()}`);
item.cancel();
});
if (nextProgressId) {
meta.progressId = nextProgressId;
}
meta.savePath = savePath;
if (meta.savePath && meta.savePath !== savePath) {
const nextProgressId = mp.recreateFileProgressAtPath(meta.progressId, savePath, () => {
debugPrint("DOWNLOADS", `Cancel requested from Finder for: ${item.getFilename()}`);
item.cancel();
});
if (nextProgressId) {
meta.progressId = nextProgressId;
meta.savePath = savePath;
} else {
meta.progressId = null;
}
}
🤖 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 336 - 345,
The code updates meta.savePath even when mp.recreateFileProgressAtPath(...)
returns null, which stops future retries while meta.progressId may point to a
removed entry; change the logic in the block around recreateFileProgressAtPath
so that meta.savePath is only assigned when nextProgressId is truthy (i.e.,
recreate succeeded), and leave meta.savePath and meta.progressId unchanged when
nextProgressId is null (optionally add a debug/log line when recreation fails)
so the next sync can retry recreation.

}
}

private updateMacProgress(meta: DownloadMetadata, item: DownloadItem): void {
if (!this.macosProgress || !meta.progressId) return;

const receivedBytes = item.getReceivedBytes();
const totalBytes = item.getTotalBytes();

this.macosProgress.updateFileProgress(meta.progressId, receivedBytes);

if (totalBytes > 0 && totalBytes !== meta.initialTotalBytes) {
this.macosProgress.updateFileProgressTotal(meta.progressId, totalBytes);
meta.initialTotalBytes = totalBytes;
}

const now = Date.now();
const timeDelta = (now - meta.lastUpdate) / 1000;

if (timeDelta >= 0.5) {
const bytesDelta = receivedBytes - meta.lastBytes;
const bytesPerSecond = bytesDelta / timeDelta;

this.macosProgress.updateFileProgressThroughput(meta.progressId, bytesPerSecond);

if (bytesPerSecond > 0 && totalBytes > 0) {
const remainingBytes = totalBytes - receivedBytes;
const secondsRemaining = remainingBytes / bytesPerSecond;
this.macosProgress.updateFileProgressEstimatedTime(meta.progressId, secondsRemaining);
}

meta.lastUpdate = now;
meta.lastBytes = receivedBytes;
}
}

private async handleDone(
item: DownloadItem,
meta: DownloadMetadata,
state: "completed" | "cancelled" | "interrupted"
): Promise<void> {
await this.syncMacProgress(item, meta);

if (!this.macosProgress || !meta.progressId) {
debugPrint("DOWNLOADS", `Download ${state}: ${item.getFilename()}`);
return;
}

if (state === "completed") {
this.macosProgress.completeFileProgress(meta.progressId, item.getReceivedBytes());
} else {
this.macosProgress.cancelFileProgress(meta.progressId);
}

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

private getSavePath(item: DownloadItem): string | null {
try {
const savePath = item.getSavePath();
return savePath || null;
} catch {
return null;
}
}
}

export const downloadsController = new DownloadsController();
155 changes: 155 additions & 0 deletions src/main/controllers/downloads-controller/macos-progress.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
import { NSProgress, NSURL, NSNumber, type _NSProgress } from "objcjs-types/Foundation";
import { NSProgressFileOperationKind, NSProgressKind } from "objcjs-types/Foundation";
import { NSStringFromString } from "objcjs-types/helpers";
import { debugError, debugPrint } from "@/modules/output";

const activeProgressMap = new Map<string, _NSProgress>();
const cancelCallbackMap = new Map<string, () => void>();

export function createFileProgress(filePath: string, totalBytes: number, onCancel?: () => void): string | null {
try {
const progressId = `${filePath}-${Date.now()}`;
const progress = NSProgress.discreteProgressWithTotalUnitCount$(Math.max(totalBytes, 0));

progress.setKind$(NSStringFromString(NSProgressKind.File));
progress.setFileOperationKind$(NSStringFromString(NSProgressFileOperationKind.Downloading));
progress.setFileURL$(NSURL.fileURLWithPath$(NSStringFromString(filePath)));
progress.setCompletedUnitCount$(0);
progress.setCancellable$(true);
progress.setPausable$(false);

if (onCancel) {
cancelCallbackMap.set(progressId, onCancel);
progress.setCancellationHandler$(() => {
const callback = cancelCallbackMap.get(progressId);
if (callback) {
debugPrint("DOWNLOADS", `macOS: cancel requested from Finder for ${filePath}`);
callback();
}
});
}

progress.publish();
activeProgressMap.set(progressId, progress);

debugPrint("DOWNLOADS", `macOS: created progress for ${filePath}`);
return progressId;
} catch (err) {
debugError("DOWNLOADS", "macOS: createFileProgress failed:", err);
return null;
}
}

export function updateFileProgress(progressId: string, completedBytes: number): void {
try {
const progress = activeProgressMap.get(progressId);
if (!progress) return;
progress.setCompletedUnitCount$(Math.max(completedBytes, 0));
} catch (err) {
debugError("DOWNLOADS", "macOS: updateFileProgress failed:", err);
}
}

export function updateFileProgressTotal(progressId: string, totalBytes: number): void {
try {
const progress = activeProgressMap.get(progressId);
if (!progress) return;
progress.setTotalUnitCount$(Math.max(totalBytes, 0));
} catch (err) {
debugError("DOWNLOADS", "macOS: updateFileProgressTotal failed:", err);
}
}

export function updateFileProgressThroughput(progressId: string, bytesPerSecond: number): void {
try {
const progress = activeProgressMap.get(progressId);
if (!progress) return;
progress.setThroughput$(NSNumber.numberWithDouble$(Math.max(bytesPerSecond, 0)));
} catch (err) {
debugError("DOWNLOADS", "macOS: updateFileProgressThroughput failed:", err);
}
}

export function updateFileProgressEstimatedTime(progressId: string, seconds: number): void {
try {
const progress = activeProgressMap.get(progressId);
if (!progress) return;
progress.setEstimatedTimeRemaining$(NSNumber.numberWithDouble$(Math.max(seconds, 0)));
} catch (err) {
debugError("DOWNLOADS", "macOS: updateFileProgressEstimatedTime failed:", err);
}
}

export function completeFileProgress(progressId: string, completedBytes: number): void {
try {
const progress = activeProgressMap.get(progressId);
if (!progress) return;

const finalCount = Math.max(completedBytes, progress.totalUnitCount(), 0);
progress.setTotalUnitCount$(finalCount);
progress.setCompletedUnitCount$(finalCount);
progress.setCancellationHandler$(null);
cancelCallbackMap.delete(progressId);
progress.unpublish();
activeProgressMap.delete(progressId);

debugPrint("DOWNLOADS", `macOS: completed progress for ID ${progressId}`);
} catch (err) {
debugError("DOWNLOADS", "macOS: completeFileProgress failed:", err);
}
}

export function cancelFileProgress(progressId: string): void {
try {
const progress = activeProgressMap.get(progressId);
if (!progress) return;

progress.setCancellationHandler$(null);
cancelCallbackMap.delete(progressId);
progress.cancel();
progress.unpublish();
activeProgressMap.delete(progressId);

debugPrint("DOWNLOADS", `macOS: cancelled progress for ID ${progressId}`);
} catch (err) {
debugError("DOWNLOADS", "macOS: cancelFileProgress failed:", err);
}
}

export function recreateFileProgressAtPath(
progressId: string,
newFilePath: string,
onCancel?: () => void
): string | null {
try {
const oldProgress = activeProgressMap.get(progressId);
if (!oldProgress) return null;

const completedBytes = oldProgress.completedUnitCount();
const totalBytes = oldProgress.totalUnitCount();
const throughput = oldProgress.throughput();
const estimatedTime = oldProgress.estimatedTimeRemaining();

cancelFileProgress(progressId);

const newProgressId = createFileProgress(newFilePath, totalBytes, onCancel);
if (!newProgressId) return null;

const newProgress = activeProgressMap.get(newProgressId);
if (newProgress) {
newProgress.setCompletedUnitCount$(completedBytes);
if (throughput) {
newProgress.setThroughput$(throughput);
}
if (estimatedTime) {
newProgress.setEstimatedTimeRemaining$(estimatedTime);
}
}

debugPrint("DOWNLOADS", `macOS: recreated progress at ${newFilePath}`);
return newProgressId;
} catch (err) {
debugError("DOWNLOADS", "macOS: recreateFileProgressAtPath failed:", err);
return null;
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { sleep } from "@/modules/utils";
import { registerProtocolsWithSession } from "../protocols";
import { app, session } from "electron";
import { downloadsController } from "@/controllers/downloads-controller";
import { setupInterceptRules } from "@/controllers/sessions-controller/intercept-rules";
import { registerPreloadScripts } from "@/controllers/sessions-controller/preload-scripts";

Expand All @@ -11,6 +12,7 @@ function initializeDefaultSession() {

setupInterceptRules(defaultSession);
registerPreloadScripts(defaultSession);
downloadsController.registerSession(defaultSession);
}

export let isDefaultSessionReady = false;
Expand Down
3 changes: 3 additions & 0 deletions src/main/controllers/sessions-controller/handlers/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { downloadsController } from "@/controllers/downloads-controller";
import { debugPrint } from "@/modules/output";
import { setAlwaysOpenExternal, shouldAlwaysOpenExternal } from "@/saving/open-external";
import { app, dialog, OpenExternalPermissionRequest, type Session } from "electron";

export function registerHandlersWithSession(session: Session) {
downloadsController.registerSession(session);

session.setPermissionRequestHandler(async (webContents, permission, callback, details) => {
debugPrint("PERMISSIONS", "permission request", webContents?.getURL() || "unknown-url", permission);

Expand Down
3 changes: 2 additions & 1 deletion src/main/modules/output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ const DEBUG_AREAS = {
WEB_REQUESTS_INTERCEPTION: false, // @/browser/utility/web-requests.ts
WEB_REQUESTS: false, // @/browser/utility/web-requests.ts
MATCH_PATTERN: false, // @/browser/utility/match-pattern.ts
WINDOWS: true // @/controllers/windows-controller
WINDOWS: true, // @/controllers/windows-controller
DOWNLOADS: false // @/controllers/downloads-controller
} as const;

export type DEBUG_AREA = keyof typeof DEBUG_AREAS;
Expand Down