Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
Download refactor (#158)
Gabriel Steinf0493bb0ead9
diff --git a/src/components/TranscriptionModelPicker.tsx b/src/components/TranscriptionModelPicker.tsxindex 68d459ab5..ade12b2b2 100644--- a/src/components/TranscriptionModelPicker.tsx+++ b/src/components/TranscriptionModelPicker.tsx@@ -50,6 +50,100 @@ interface LocalModelCardProps {// Backwards compatibility aliastype WhisperModel = LocalModel;+function LocalModelCard({+ modelId,+ name,+ description,+ size,+ actualSizeMb,+ isSelected,+ isDownloaded,+ isDownloading,+ isCancelling,+ recommended,+ provider,+ languageLabel,+ onSelect,+ onDelete,+ onDownload,+ onCancel,+ styles: cardStyles,+}: LocalModelCardProps) {+ return (+ <div+ className={`p-3 rounded-lg border-2 transition-all ${+ isSelected ? cardStyles.modelCard.selected : cardStyles.modelCard.default+ }`}+ >+ <div className="flex items-center justify-between">+ <div className="flex-1">+ <div className="flex items-center gap-2">+ <ProviderIcon provider={provider} className="w-4 h-4" />+ <span className="font-medium text-gray-900">{name}</span>+ {isSelected && <span className={cardStyles.badges.selected}>✓ Selected</span>}+ {recommended && <span className={cardStyles.badges.recommended}>Recommended</span>}+ </div>+ <div className="flex items-center gap-2 mt-1">+ <span className="text-xs text-gray-600">{description}</span>+ <span className="text-xs text-gray-500">+ • {actualSizeMb ? `${actualSizeMb}MB` : size}+ </span>+ {languageLabel && <span className="text-xs text-blue-600">{languageLabel}</span>}+ {isDownloaded && (+ <span className={cardStyles.badges.downloaded}>+ <Check className="inline w-3 h-3 mr-1" />+ Downloaded+ </span>+ )}+ </div>+ </div>++ <div className="flex gap-2">+ {isDownloaded ? (+ <>+ {!isSelected && (+ <Button+ onClick={onSelect}+ size="sm"+ variant="outline"+ className={cardStyles.buttons.select}+ >+ Select+ </Button>+ )}+ <Button+ onClick={onDelete}+ size="sm"+ variant="outline"+ className={cardStyles.buttons.delete}+ >+ <Trash2 size={14} />+ <span className="ml-1">Delete</span>+ </Button>+ </>+ ) : isDownloading ? (+ <Button+ onClick={onCancel}+ disabled={isCancelling}+ size="sm"+ variant="outline"+ className="text-red-600 border-red-300 hover:bg-red-50"+ >+ <X size={14} />+ <span className="ml-1">{isCancelling ? "..." : "Cancel"}</span>+ </Button>+ ) : (+ <Button onClick={onDownload} size="sm" className={cardStyles.buttons.download}>+ <Download size={14} />+ <span className="ml-1">Download</span>+ </Button>+ )}+ </div>+ </div>+ </div>+ );+}+interface TranscriptionModelPickerProps {selectedCloudProvider: string;onCloudProviderSelect: (providerId: string) => void;@@ -258,6 +352,7 @@ export default function TranscriptionModelPicker({downloadModel,deleteModel,isDownloadingModel,+ isInstalling,cancelDownload,isCancelling,} = useModelDownload({@@ -271,6 +366,7 @@ export default function TranscriptionModelPicker({downloadModel: downloadParakeetModel,deleteModel: deleteParakeetModel,isDownloadingModel: isDownloadingParakeetModel,+ isInstalling: isInstallingParakeet,cancelDownload: cancelParakeetDownload,isCancelling: isCancellingParakeet,} = useModelDownload({@@ -418,6 +514,7 @@ export default function TranscriptionModelPicker({<DownloadProgressBarmodelName={modelInfo?.name || downloadingModel}progress={downloadProgress}+ isInstalling={isInstalling}styles={styles}/>);@@ -429,6 +526,7 @@ export default function TranscriptionModelPicker({<DownloadProgressBarmodelName={modelInfo?.name || downloadingParakeetModel}progress={parakeetDownloadProgress}+ isInstalling={isInstallingParakeet}styles={styles}/>);@@ -438,107 +536,15 @@ export default function TranscriptionModelPicker({}, [downloadingModel,downloadProgress,+ isInstalling,downloadingParakeetModel,parakeetDownloadProgress,+ isInstallingParakeet,useLocalWhisper,internalLocalProvider,styles,]);- // Shared component for rendering local model cards (Whisper and Parakeet)- const LocalModelCard = ({- modelId,- name,- description,- size,- actualSizeMb,- isSelected,- isDownloaded,- isDownloading,- isCancelling,- recommended,- provider,- languageLabel,- onSelect,- onDelete,- onDownload,- onCancel,- styles: cardStyles,- }: LocalModelCardProps) => (- <div- key={modelId}- className={`p-3 rounded-lg border-2 transition-all ${- isSelected ? cardStyles.modelCard.selected : cardStyles.modelCard.default- }`}- >- <div className="flex items-center justify-between">- <div className="flex-1">- <div className="flex items-center gap-2">- <ProviderIcon provider={provider} className="w-4 h-4" />- <span className="font-medium text-gray-900">{name}</span>- {isSelected && <span className={cardStyles.badges.selected}>✓ Selected</span>}- {recommended && <span className={cardStyles.badges.recommended}>Recommended</span>}- </div>- <div className="flex items-center gap-2 mt-1">- <span className="text-xs text-gray-600">{description}</span>- <span className="text-xs text-gray-500">- • {actualSizeMb ? `${actualSizeMb}MB` : size}- </span>- {languageLabel && <span className="text-xs text-blue-600">{languageLabel}</span>}- {isDownloaded && (- <span className={cardStyles.badges.downloaded}>- <Check className="inline w-3 h-3 mr-1" />- Downloaded- </span>- )}- </div>- </div>-- <div className="flex gap-2">- {isDownloaded ? (- <>- {!isSelected && (- <Button- onClick={onSelect}- size="sm"- variant="outline"- className={cardStyles.buttons.select}- >- Select- </Button>- )}- <Button- onClick={onDelete}- size="sm"- variant="outline"- className={cardStyles.buttons.delete}- >- <Trash2 size={14} />- <span className="ml-1">Delete</span>- </Button>- </>- ) : isDownloading ? (- <Button- onClick={onCancel}- disabled={isCancelling}- size="sm"- variant="outline"- className="text-red-600 border-red-300 hover:bg-red-50"- >- <X size={14} />- <span className="ml-1">{isCancelling ? "..." : "Cancel"}</span>- </Button>- ) : (- <Button onClick={onDownload} size="sm" className={cardStyles.buttons.download}>- <Download size={14} />- <span className="ml-1">Download</span>- </Button>- )}- </div>- </div>- </div>- );-const renderLocalModels = () => (<div className="space-y-2">{localModels.map((model) => {diff --git a/src/components/ui/DownloadProgressBar.tsx b/src/components/ui/DownloadProgressBar.tsxindex 74de7e4a4..fcb3847c0 100644--- a/src/components/ui/DownloadProgressBar.tsx+++ b/src/components/ui/DownloadProgressBar.tsx@@ -5,30 +5,38 @@ interface DownloadProgressBarProps {modelName: string;progress: DownloadProgress;styles: ModelPickerStyles;+ isInstalling?: boolean;}-export function DownloadProgressBar({ modelName, progress, styles }: DownloadProgressBarProps) {+export function DownloadProgressBar({+ modelName,+ progress,+ styles,+ isInstalling,+}: DownloadProgressBarProps) {const { percentage, speed, eta } = progress;const progressText = `${Math.round(percentage)}%`;const speedText = speed ? ` • ${speed.toFixed(1)} MB/s` : "";const etaText = eta ? ` • ETA: ${formatETA(eta)}` : "";+ const label = isInstalling ? `Installing ${modelName}...` : `Downloading ${modelName}...`;+return (<div className={`${styles.progress} p-3`}><div className="flex items-center justify-between mb-2">- <span className={`text-sm font-medium ${styles.progressText}`}>- Downloading {modelName}...- </span>- <span className={`text-xs ${styles.progressText}`}>- {progressText}- {speedText}- {etaText}- </span>+ <span className={`text-sm font-medium ${styles.progressText}`}>{label}</span>+ {!isInstalling && (+ <span className={`text-xs ${styles.progressText}`}>+ {progressText}+ {speedText}+ {etaText}+ </span>+ )}</div><div className={`w-full ${styles.progressBar} rounded-full h-2`}><div- className={`${styles.progressFill} h-2 rounded-full transition-all duration-300 ease-out`}- style={{ width: `${Math.min(percentage, 100)}%` }}+ className={`${styles.progressFill} h-2 rounded-full transition-all duration-300 ease-out ${isInstalling ? "animate-pulse" : ""}`}+ style={{ width: `${isInstalling ? 100 : Math.min(percentage, 100)}%` }}/></div></div>diff --git a/src/helpers/downloadUtils.js b/src/helpers/downloadUtils.jsnew file mode 100644index 000000000..9a4f87771--- /dev/null+++ b/src/helpers/downloadUtils.js@@ -0,0 +1,319 @@+const fs = require("fs");+const { promises: fsPromises } = require("fs");+const https = require("https");+const http = require("http");+const { pipeline } = require("stream");+const debugLogger = require("./debugLogger");++const USER_AGENT = "OpenWhispr/1.0";+const PROGRESS_THROTTLE_MS = 100;+const MAX_REDIRECTS = 5;+const DEFAULT_TIMEOUT = 60000;+const DEFAULT_MAX_RETRIES = 3;+const MAX_BACKOFF_MS = 30000;++const RETRYABLE_CODES = new Set([+ "ECONNRESET",+ "ETIMEDOUT",+ "EPIPE",+ "EAI_AGAIN",+ "ECONNREFUSED",+ "ENOTFOUND",+ "ERR_STREAM_PREMATURE_CLOSE",+]);++function isRetryable(error) {+ if (error.isAbort || error.isHttpError) return false;+ return RETRYABLE_CODES.has(error.code);+}++function backoffDelay(attempt) {+ return Math.min(1000 * Math.pow(2, attempt), MAX_BACKOFF_MS);+}++function sleep(ms) {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++function resolveRedirects(url, timeout) {+ return new Promise((resolve, reject) => {+ let redirectCount = 0;++ const follow = (currentUrl) => {+ if (redirectCount > MAX_REDIRECTS) {+ reject(Object.assign(new Error("Too many redirects"), { isHttpError: true }));+ return;+ }++ const client = currentUrl.startsWith("https") ? https : http;+ const parsed = new URL(currentUrl);+ const req = client.request({+ method: "HEAD",+ hostname: parsed.hostname,+ port: parsed.port,+ path: parsed.pathname + parsed.search,+ timeout,+ headers: { "User-Agent": USER_AGENT },+ });++ req.on("response", (res) => {+ res.resume();+ if (+ res.statusCode === 301 ||+ res.statusCode === 302 ||+ res.statusCode === 303 ||+ res.statusCode === 307 ||+ res.statusCode === 308+ ) {+ const location = res.headers.location;+ if (!location) {+ reject(+ Object.assign(new Error("Redirect without location header"), { isHttpError: true })+ );+ return;+ }+ redirectCount++;+ follow(location);+ return;+ }+ resolve({ finalUrl: currentUrl, statusCode: res.statusCode });+ });++ req.on("error", reject);+ req.on("timeout", () => {+ req.destroy();+ reject(Object.assign(new Error("Timeout resolving redirects"), { code: "ETIMEDOUT" }));+ });++ req.end();+ };++ follow(url);+ });+}++function downloadAttempt(url, tempPath, { timeout, onProgress, signal, startOffset }) {+ return new Promise((resolve, reject) => {+ if (signal?.aborted) {+ reject(Object.assign(new Error("Download cancelled"), { isAbort: true }));+ return;+ }++ const headers = { "User-Agent": USER_AGENT };+ if (startOffset > 0) {+ headers["Range"] = `bytes=${startOffset}-`;+ }++ const client = url.startsWith("https") ? https : http;+ let activeFile = fs.createWriteStream(tempPath, { flags: startOffset > 0 ? "a" : "w" });++ let downloadedSize = startOffset;+ let totalSize = 0;+ let lastProgressUpdate = 0;+ let request = null;++ const cleanup = () => {+ if (request) {+ request.destroy();+ request = null;+ }+ activeFile.destroy();+ };++ const onAbort = () => {+ cleanup();+ reject(Object.assign(new Error("Download cancelled"), { isAbort: true }));+ };++ if (signal) {+ signal.onAbort = onAbort;+ }++ request = client.get(url, { headers, timeout }, (response) => {+ if (signal?.aborted) {+ cleanup();+ reject(Object.assign(new Error("Download cancelled"), { isAbort: true }));+ return;+ }++ const statusCode = response.statusCode;++ if (statusCode === 200 && startOffset > 0) {+ // Server doesn't support Range — restart from beginning+ downloadedSize = 0;+ activeFile.destroy();+ activeFile = fs.createWriteStream(tempPath, { flags: "w" });+ totalSize = parseInt(response.headers["content-length"], 10) || 0;+ } else if (statusCode === 206) {+ const contentRange = response.headers["content-range"];+ if (contentRange) {+ const match = contentRange.match(/\/(\d+)$/);+ if (match) totalSize = parseInt(match[1], 10);+ }+ if (!totalSize) {+ const contentLength = parseInt(response.headers["content-length"], 10) || 0;+ totalSize = startOffset + contentLength;+ }+ } else if (statusCode === 200) {+ totalSize = parseInt(response.headers["content-length"], 10) || 0;+ } else {+ cleanup();+ const err = new Error(`HTTP ${statusCode}`);+ err.isHttpError = true;+ err.statusCode = statusCode;+ reject(err);+ return;+ }++ response.on("data", (chunk) => {+ if (signal?.aborted) {+ cleanup();+ return;+ }+ downloadedSize += chunk.length;+ emitProgress();+ });++ pipeline(response, activeFile, (err) => {+ if (signal) signal.onAbort = null;+ if (err) {+ if (signal?.aborted) {+ reject(Object.assign(new Error("Download cancelled"), { isAbort: true }));+ } else {+ reject(err);+ }+ } else {+ resolve({ downloadedSize, totalSize });+ }+ });+ });++ request.on("error", (err) => {+ if (signal) signal.onAbort = null;+ cleanup();+ if (signal?.aborted) {+ reject(Object.assign(new Error("Download cancelled"), { isAbort: true }));+ } else {+ reject(err);+ }+ });++ request.on("timeout", () => {+ if (signal) signal.onAbort = null;+ cleanup();+ reject(Object.assign(new Error("Socket timeout"), { code: "ETIMEDOUT" }));+ });++ function emitProgress() {+ if (!onProgress || totalSize <= 0) return;+ const now = Date.now();+ if (now - lastProgressUpdate >= PROGRESS_THROTTLE_MS || downloadedSize >= totalSize) {+ lastProgressUpdate = now;+ onProgress(downloadedSize, totalSize);+ }+ }+ });+}++async function downloadFile(url, destPath, options = {}) {+ const {+ onProgress,+ timeout = DEFAULT_TIMEOUT,+ maxRetries = DEFAULT_MAX_RETRIES,+ signal,+ } = options;++ const tempPath = `${destPath}.tmp`;++ debugLogger.info("Download starting", { url: url.substring(0, 80), destPath });++ let startOffset = 0;+ try {+ const stats = await fsPromises.stat(tempPath);+ if (stats.size > 0) {+ startOffset = stats.size;+ debugLogger.info("Resuming download", { startOffset });+ }+ } catch {+ // No existing temp file+ }++ const { finalUrl } = await resolveRedirects(url, timeout);++ let lastError = null;++ for (let attempt = 0; attempt <= maxRetries; attempt++) {+ if (signal?.aborted) {+ throw Object.assign(new Error("Download cancelled"), { isAbort: true });+ }++ if (attempt > 0) {+ const delay = backoffDelay(attempt - 1);+ debugLogger.info("Retrying download", { attempt, delay, startOffset });+ await sleep(delay);++ // Update startOffset from temp file in case partial data was written+ try {+ const stats = await fsPromises.stat(tempPath);+ if (stats.size > 0) startOffset = stats.size;+ } catch {+ startOffset = 0;+ }+ }++ try {+ await downloadAttempt(finalUrl, tempPath, { timeout, onProgress, signal, startOffset });++ // Atomic move to final path+ try {+ await fsPromises.rename(tempPath, destPath);+ } catch (renameError) {+ if (renameError.code === "EXDEV") {+ await fsPromises.copyFile(tempPath, destPath);+ await fsPromises.unlink(tempPath).catch(() => {});+ } else {+ throw renameError;+ }+ }++ debugLogger.info("Download complete", { destPath });+ return destPath;+ } catch (error) {+ lastError = error;++ if (error.isAbort) {+ await fsPromises.unlink(tempPath).catch(() => {});+ throw error;+ }++ if (!isRetryable(error) || attempt >= maxRetries) {+ await fsPromises.unlink(tempPath).catch(() => {});+ throw error;+ }++ debugLogger.warn("Download attempt failed", {+ attempt: attempt + 1,+ error: error.message,+ code: error.code,+ });+ }+ }++ await fsPromises.unlink(tempPath).catch(() => {});+ throw lastError;+}++function createDownloadSignal() {+ const signal = { aborted: false, onAbort: null };+ return {+ signal,+ abort() {+ signal.aborted = true;+ if (typeof signal.onAbort === "function") {+ signal.onAbort();+ }+ },+ };+}++module.exports = { downloadFile, createDownloadSignal };diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 4cde850f9..3ec358901 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -245,30 +245,9 @@ class IPCHandlers {});ipcMain.handle("download-whisper-model", async (event, modelName) => {- try {- const result = await this.whisperManager.downloadWhisperModel(modelName, (progressData) => {- // Forward progress updates to the renderer- event.sender.send("whisper-download-progress", progressData);- });-- // Send completion event- event.sender.send("whisper-download-progress", {- type: "complete",- model: modelName,- result: result,- });-- return result;- } catch (error) {- // Send error event- event.sender.send("whisper-download-progress", {- type: "error",- model: modelName,- error: error.message,- });-- throw error;- }+ return this.whisperManager.downloadWhisperModel(modelName, (progressData) => {+ event.sender.send("whisper-download-progress", progressData);+ });});ipcMain.handle("check-model-status", async (event, modelName) => {@@ -360,30 +339,9 @@ class IPCHandlers {});ipcMain.handle("download-parakeet-model", async (event, modelName) => {- try {- const result = await this.parakeetManager.downloadParakeetModel(- modelName,- (progressData) => {- event.sender.send("parakeet-download-progress", progressData);- }- );-- event.sender.send("parakeet-download-progress", {- type: "complete",- model: modelName,- result: result,- });-- return result;- } catch (error) {- event.sender.send("parakeet-download-progress", {- type: "error",- model: modelName,- error: error.message,- });-- throw error;- }+ return this.parakeetManager.downloadParakeetModel(modelName, (progressData) => {+ event.sender.send("parakeet-download-progress", progressData);+ });});ipcMain.handle("check-parakeet-model-status", async (_event, modelName) => {diff --git a/src/helpers/modelManagerBridge.js b/src/helpers/modelManagerBridge.jsindex d5ed39fd1..7f52b67ad 100644--- a/src/helpers/modelManagerBridge.js+++ b/src/helpers/modelManagerBridge.js@@ -1,9 +1,8 @@const path = require("path");const fs = require("fs");const { promises: fsPromises } = require("fs");-const https = require("https");-const { pipeline } = require("stream");const { app } = require("electron");+const { downloadFile: sharedDownloadFile, createDownloadSignal } = require("./downloadUtils");const modelRegistryData = require("../models/modelRegistryData.json");const LlamaServerManager = require("./llamaServer");@@ -171,7 +170,6 @@ class ModelManager {const { model, provider } = modelInfo;const modelPath = path.join(this.modelsDir, model.fileName);- const tempPath = `${modelPath}.tmp`;if (await this.checkModelValid(modelPath)) {return modelPath;@@ -184,30 +182,32 @@ class ModelManager {}this.activeDownloads.set(modelId, true);+ const { signal, abort } = createDownloadSignal();+ this.activeRequests.set(modelId, { abort });try {await this.ensureModelsDirExists();const downloadUrl = this.getDownloadUrl(provider, model);- await this.downloadFile(- downloadUrl,- tempPath,- (progress, downloadedSize, totalSize) => {+ await sharedDownloadFile(downloadUrl, modelPath, {+ signal,+ onProgress: (downloadedBytes, totalBytes) => {+ const progress = totalBytes > 0 ? (downloadedBytes / totalBytes) * 100 : 0;this.downloadProgress.set(modelId, {modelId,progress,- downloadedSize,- totalSize,+ downloadedSize: downloadedBytes,+ totalSize: totalBytes,});if (onProgress) {- onProgress(progress, downloadedSize, totalSize);+ onProgress(progress, downloadedBytes, totalBytes);}},- modelId- );+ });- const stats = await fsPromises.stat(tempPath);+ const stats = await fsPromises.stat(modelPath);if (stats.size < MIN_FILE_SIZE) {+ await fsPromises.unlink(modelPath).catch(() => {});throw new ModelError("Downloaded file appears to be corrupted or incomplete","DOWNLOAD_CORRUPTED",@@ -215,25 +215,25 @@ class ModelManager {);}- // Atomic rename to final path (handles cross-device moves on Windows)- try {- await fsPromises.rename(tempPath, modelPath);- } catch (renameError) {- if (renameError.code === "EXDEV") {- await fsPromises.copyFile(tempPath, modelPath);- await fsPromises.unlink(tempPath).catch(() => {});- } else {- throw renameError;- }- }-return modelPath;} catch (error) {- // Clean up partial download on failure- await fsPromises.unlink(tempPath).catch(() => {});+ if (error.isAbort) {+ throw new ModelError("Download cancelled by user", "DOWNLOAD_CANCELLED", { modelId });+ }+ if (error.isHttpError) {+ throw new ModelError(`Download failed with status ${error.statusCode}`, "DOWNLOAD_FAILED", {+ statusCode: error.statusCode,+ });+ }+ if (!(error instanceof ModelError)) {+ throw new ModelError(`Network error: ${error.message}`, "NETWORK_ERROR", {+ error: error.message,+ });+ }throw error;} finally {this.activeDownloads.delete(modelId);+ this.activeRequests.delete(modelId);this.downloadProgress.delete(modelId);}}@@ -243,168 +243,13 @@ class ModelManager {return `${baseUrl}/${model.hfRepo}/resolve/main/${model.fileName}`;}- async downloadFile(url, destPath, onProgress, modelId) {- return new Promise((resolve, reject) => {- const file = fs.createWriteStream(destPath);- let downloadedSize = 0;- let totalSize = 0;- let lastProgressUpdate = 0;- const PROGRESS_THROTTLE_MS = 100; // Throttle progress updates to prevent UI flashing-- const cleanup = (callback) => {- file.close(() => {- fsPromises- .unlink(destPath)- .catch(() => {})- .finally(callback);- });- };-- const request = https- .get(- url,- {- headers: { "User-Agent": "OpenWhispr/1.0" },- timeout: 30000,- },- (response) => {- if (- response.statusCode === 301 ||- response.statusCode === 302 ||- response.statusCode === 303 ||- response.statusCode === 307 ||- response.statusCode === 308- ) {- const redirectUrl = response.headers.location;- if (!redirectUrl) {- cleanup(() => {- reject(- new ModelError("Redirect without location header", "DOWNLOAD_REDIRECT_ERROR")- );- });- return;- }- cleanup(() => {- this.downloadFile(redirectUrl, destPath, onProgress, modelId)- .then(resolve)- .catch(reject);- });- return;- }-- if (response.statusCode !== 200 && response.statusCode !== 206) {- cleanup(() => {- reject(- new ModelError(- `Download failed with status ${response.statusCode}`,- "DOWNLOAD_FAILED",- { statusCode: response.statusCode }- )- );- });- return;- }-- totalSize = parseInt(response.headers["content-length"], 10);-- response.on("data", (chunk) => {- downloadedSize += chunk.length;-- // Throttle progress updates to prevent UI flashing- const now = Date.now();- if (- onProgress &&- totalSize > 0 &&- (now - lastProgressUpdate >= PROGRESS_THROTTLE_MS || downloadedSize >= totalSize)- ) {- lastProgressUpdate = now;- const progress = (downloadedSize / totalSize) * 100;- onProgress(progress, downloadedSize, totalSize);- }- });-- pipeline(response, file, (error) => {- // Clean up request tracking- if (modelId) {- this.activeRequests.delete(modelId);- }-- if (error) {- // Check if this was a cancellation- if (- error.code === "ERR_STREAM_PREMATURE_CLOSE" &&- modelId &&- !this.activeDownloads.has(modelId)- ) {- cleanup(() => {- reject(- new ModelError("Download cancelled by user", "DOWNLOAD_CANCELLED", {- modelId,- })- );- });- return;- }- cleanup(() => {- reject(- new ModelError(`Download error: ${error.message}`, "DOWNLOAD_ERROR", {- error: error.message,- })- );- });- return;- }- resolve(destPath);- });- }- )- .on("error", (error) => {- // Clean up request tracking- if (modelId) {- this.activeRequests.delete(modelId);- }-- cleanup(() => {- // Check if this was a cancellation- if (error.code === "ECONNRESET" && modelId && !this.activeDownloads.has(modelId)) {- reject(- new ModelError("Download cancelled by user", "DOWNLOAD_CANCELLED", {- modelId,- })- );- return;- }- reject(- new ModelError(`Network error: ${error.message}`, "NETWORK_ERROR", {- error: error.message,- })- );- });- });-- // Store the request for potential cancellation- if (modelId) {- this.activeRequests.set(modelId, { request, file, destPath });- }- });- }-cancelDownload(modelId) {- const activeRequest = this.activeRequests.get(modelId);- if (activeRequest) {- const { request, file, destPath } = activeRequest;-- // Mark as no longer active before destroying+ const entry = this.activeRequests.get(modelId);+ if (entry) {this.activeDownloads.delete(modelId);this.activeRequests.delete(modelId);this.downloadProgress.delete(modelId);-- // Destroy the request and close the file- request.destroy();- file.close(() => {- fsPromises.unlink(destPath).catch(() => {});- });-+ entry.abort();return true;}return false;diff --git a/src/helpers/parakeet.js b/src/helpers/parakeet.jsindex 58b18917c..d720cff74 100644--- a/src/helpers/parakeet.js+++ b/src/helpers/parakeet.js@@ -1,9 +1,9 @@const fs = require("fs");const fsPromises = require("fs").promises;const path = require("path");-const https = require("https");const { spawn } = require("child_process");const debugLogger = require("./debugLogger");+const { downloadFile, createDownloadSignal } = require("./downloadUtils");const ParakeetServerManager = require("./parakeetServer");const { getModelsDirForService } = require("./modelDirUtils");@@ -253,7 +253,6 @@ class ParakeetManager {return { success: true, text };}- // Model management methodsasync downloadParakeetModel(modelName, progressCallback = null) {this.validateModelName(modelName);const modelConfig = getParakeetModelConfig(modelName);@@ -261,176 +260,54 @@ class ParakeetManager {const modelPath = this.getModelPath(modelName);const modelsDir = this.getModelsDir();- // Create models directoryawait fsPromises.mkdir(modelsDir, { recursive: true });- // Check if already downloadedif (this.serverManager.isModelDownloaded(modelName)) {- return {- model: modelName,- downloaded: true,- path: modelPath,- success: true,- };+ return { model: modelName, downloaded: true, path: modelPath, success: true };}- const tempPath = path.join(modelsDir, `${modelName}.tar.bz2.tmp`);const archivePath = path.join(modelsDir, `${modelName}.tar.bz2`);+ const { signal, abort } = createDownloadSignal();+ this.currentDownloadProcess = { abort };- let activeRequest = null;- let activeFile = null;- let isCancelled = false;-- const cleanup = () => {- if (activeRequest) {- activeRequest.destroy();- activeRequest = null;- }- if (activeFile) {- activeFile.close();- activeFile = null;- }- try {- fs.unlinkSync(tempPath);- } catch {}- try {- fs.unlinkSync(archivePath);- } catch {}- };-- this.currentDownloadProcess = {- abort: () => {- isCancelled = true;- cleanup();- },- };-- return new Promise((resolve, reject) => {- const downloadWithRedirect = (url, redirectCount = 0) => {- if (isCancelled) {- reject(new Error("Download cancelled by user"));- return;- }-- if (redirectCount > 5) {- cleanup();- reject(new Error("Too many redirects"));- return;- }-- activeRequest = https.get(url, (response) => {- if (isCancelled) {- cleanup();- reject(new Error("Download cancelled by user"));- return;- }-- if (response.statusCode === 302 || response.statusCode === 301) {- const redirectUrl = response.headers.location;- if (!redirectUrl) {- cleanup();- reject(new Error("Redirect without location header"));- return;- }- downloadWithRedirect(redirectUrl, redirectCount + 1);- return;- }-- if (response.statusCode !== 200) {- cleanup();- reject(new Error(`Failed to download model: HTTP ${response.statusCode}`));- return;+ try {+ await downloadFile(modelConfig.url, archivePath, {+ timeout: 600000,+ signal,+ onProgress: (downloadedBytes, totalBytes) => {+ if (progressCallback) {+ progressCallback({+ type: "progress",+ model: modelName,+ downloaded_bytes: downloadedBytes,+ total_bytes: totalBytes,+ percentage: totalBytes > 0 ? Math.round((downloadedBytes / totalBytes) * 100) : 0,+ });}+ },+ });- const totalSize = parseInt(response.headers["content-length"], 10) || modelConfig.size;- let downloadedSize = 0;-- activeFile = fs.createWriteStream(tempPath);-- response.on("data", (chunk) => {- if (isCancelled) {- cleanup();- return;- }-- downloadedSize += chunk.length;- const percentage = Math.round((downloadedSize / totalSize) * 100);-- if (progressCallback) {- progressCallback({- type: "progress",- model: modelName,- downloaded_bytes: downloadedSize,- total_bytes: totalSize,- percentage,- });- }- });-- response.pipe(activeFile);-- activeFile.on("finish", async () => {- if (isCancelled) {- cleanup();- reject(new Error("Download cancelled by user"));- return;- }-- activeFile.close();- activeFile = null;- this.currentDownloadProcess = null;-- try {- await fsPromises.rename(tempPath, archivePath);-- await this._extractModel(archivePath, modelName);-- await fsPromises.unlink(archivePath);-- if (progressCallback) {- progressCallback({- type: "complete",- model: modelName,- percentage: 100,- });- }-- resolve({- model: modelName,- downloaded: true,- path: modelPath,- success: true,- });- } catch (extractError) {- cleanup();- reject(new Error(`Failed to extract model: ${extractError.message}`));- }- });-- activeFile.on("error", (err) => {- cleanup();- reject(err);- });-- response.on("error", (err) => {- cleanup();- reject(err);- });- });+ if (progressCallback) {+ progressCallback({ type: "installing", model: modelName, percentage: 100 });+ }- activeRequest.on("error", (err) => {- cleanup();- reject(err);- });+ await this._extractModel(archivePath, modelName);+ await fsPromises.unlink(archivePath).catch(() => {});- activeRequest.setTimeout(600000, () => {- cleanup();- reject(new Error("Download request timed out"));- });- };+ if (progressCallback) {+ progressCallback({ type: "complete", model: modelName, percentage: 100 });+ }- downloadWithRedirect(modelConfig.url);- });+ return { model: modelName, downloaded: true, path: modelPath, success: true };+ } catch (error) {+ await fsPromises.unlink(archivePath).catch(() => {});+ if (error.isAbort) {+ throw new Error("Download interrupted by user");+ }+ throw error;+ } finally {+ this.currentDownloadProcess = null;+ }}async _extractModel(archivePath, modelName) {diff --git a/src/helpers/whisper.js b/src/helpers/whisper.jsindex 8dc76f17a..859535d77 100644--- a/src/helpers/whisper.js+++ b/src/helpers/whisper.js@@ -1,8 +1,8 @@const fs = require("fs");const fsPromises = require("fs").promises;const path = require("path");-const https = require("https");const debugLogger = require("./debugLogger");+const { downloadFile, createDownloadSignal } = require("./downloadUtils");const WhisperServerManager = require("./whisperServer");const { getModelsDirForService } = require("./modelDirUtils");@@ -356,7 +356,6 @@ class WhisperManager {return normalized === "[blank_audio]" || normalized === "[ blank_audio ]";}- // Model management methodsasync downloadWhisperModel(modelName, progressCallback = null) {this.validateModelName(modelName);const modelConfig = getWhisperModelConfig(modelName);@@ -364,10 +363,8 @@ class WhisperManager {const modelPath = this.getModelPath(modelName);const modelsDir = this.getModelsDir();- // Create models directoryawait fsPromises.mkdir(modelsDir, { recursive: true });- // Check if already downloadedif (fs.existsSync(modelPath)) {const stats = await fsPromises.stat(modelPath);return {@@ -380,161 +377,48 @@ class WhisperManager {};}- const tempPath = `${modelPath}.tmp`;+ const { signal, abort } = createDownloadSignal();+ this.currentDownloadProcess = { abort };- let activeRequest = null;- let activeFile = null;- let isCancelled = false;-- const cleanup = () => {- if (activeRequest) {- activeRequest.destroy();- activeRequest = null;- }- if (activeFile) {- activeFile.close();- activeFile = null;- }- fs.unlink(tempPath, () => {});- };-- this.currentDownloadProcess = {- abort: () => {- isCancelled = true;- cleanup();- },- };-- return new Promise((resolve, reject) => {- const downloadWithRedirect = (url, redirectCount = 0) => {- if (isCancelled) {- reject(new Error("Download cancelled by user"));- return;- }-- // Prevent infinite redirects- if (redirectCount > 5) {- cleanup();- reject(new Error("Too many redirects"));- return;- }-- activeRequest = https.get(url, (response) => {- if (isCancelled) {- cleanup();- reject(new Error("Download cancelled by user"));- return;- }-- // Handle redirects- if (response.statusCode === 302 || response.statusCode === 301) {- const redirectUrl = response.headers.location;- if (!redirectUrl) {- cleanup();- reject(new Error("Redirect without location header"));- return;- }- downloadWithRedirect(redirectUrl, redirectCount + 1);- return;- }-- if (response.statusCode !== 200) {- cleanup();- reject(new Error(`Failed to download model: HTTP ${response.statusCode}`));- return;- }-- const totalSize = parseInt(response.headers["content-length"], 10) || modelConfig.size;- let downloadedSize = 0;-- activeFile = fs.createWriteStream(tempPath);-- response.on("data", (chunk) => {- if (isCancelled) {- cleanup();- return;- }-- downloadedSize += chunk.length;- const percentage = Math.round((downloadedSize / totalSize) * 100);-- if (progressCallback) {- progressCallback({- type: "progress",- model: modelName,- downloaded_bytes: downloadedSize,- total_bytes: totalSize,- percentage,- });- }- });-- response.pipe(activeFile);-- activeFile.on("finish", async () => {- if (isCancelled) {- cleanup();- reject(new Error("Download cancelled by user"));- return;- }-- activeFile.close();- activeFile = null;- this.currentDownloadProcess = null;-- // Rename temp to final- try {- await fsPromises.rename(tempPath, modelPath);- } catch {- // Cross-device move fallback- await fsPromises.copyFile(tempPath, modelPath);- await fsPromises.unlink(tempPath);- }-- const stats = await fsPromises.stat(modelPath);-- if (progressCallback) {- progressCallback({- type: "complete",- model: modelName,- percentage: 100,- });- }-- resolve({+ try {+ await downloadFile(modelConfig.url, modelPath, {+ timeout: 600000,+ signal,+ onProgress: (downloadedBytes, totalBytes) => {+ if (progressCallback) {+ progressCallback({+ type: "progress",model: modelName,- downloaded: true,- path: modelPath,- size_bytes: stats.size,- size_mb: Math.round(stats.size / (1024 * 1024)),- success: true,+ downloaded_bytes: downloadedBytes,+ total_bytes: totalBytes,+ percentage: totalBytes > 0 ? Math.round((downloadedBytes / totalBytes) * 100) : 0,});- });-- activeFile.on("error", (err) => {- cleanup();- reject(err);- });+ }+ },+ });- response.on("error", (err) => {- cleanup();- reject(err);- });- });+ const stats = await fsPromises.stat(modelPath);- activeRequest.on("error", (err) => {- cleanup();- reject(err);- });+ if (progressCallback) {+ progressCallback({ type: "complete", model: modelName, percentage: 100 });+ }- activeRequest.setTimeout(600000, () => {- cleanup();- reject(new Error("Download request timed out"));- });+ return {+ model: modelName,+ downloaded: true,+ path: modelPath,+ size_bytes: stats.size,+ size_mb: Math.round(stats.size / (1024 * 1024)),+ success: true,};-- downloadWithRedirect(modelConfig.url);- });+ } catch (error) {+ if (error.isAbort) {+ throw new Error("Download interrupted by user");+ }+ throw error;+ } finally {+ this.currentDownloadProcess = null;+ }}async cancelDownload() {diff --git a/src/hooks/useModelDownload.ts b/src/hooks/useModelDownload.tsindex 32e415521..bcd70407d 100644--- a/src/hooks/useModelDownload.ts+++ b/src/hooks/useModelDownload.ts@@ -48,6 +48,7 @@ export function useModelDownload({totalBytes: 0,});const [isCancelling, setIsCancelling] = useState(false);+ const [isInstalling, setIsInstalling] = useState(false);const isCancellingRef = useRef(false);const lastProgressUpdateRef = useRef(0);@@ -73,14 +74,21 @@ export function useModelDownload({const handleWhisperProgress = useCallback((_event: unknown, data: WhisperDownloadProgressData) => {if (data.type === "progress") {+ const now = Date.now();+ if (now - lastProgressUpdateRef.current < PROGRESS_THROTTLE_MS) return;+ lastProgressUpdateRef.current = now;setDownloadProgress({percentage: data.percentage || 0,downloadedBytes: data.downloaded_bytes || 0,totalBytes: data.total_bytes || 0,});- } else if (data.type === "complete" || data.type === "error") {- // Skip if cancellation is handling cleanup+ } else if (data.type === "installing") {+ setIsInstalling(true);+ } else if (data.type === "complete") {+ // Cleanup is handled by the finally block in downloadModel;+ // this handles the IPC progress event for completionif (isCancellingRef.current) return;+ setIsInstalling(false);setDownloadingModel(null);setDownloadProgress({ percentage: 0, downloadedBytes: 0, totalBytes: 0 });onDownloadCompleteRef.current?.();@@ -197,6 +205,7 @@ export function useModelDownload({});}} finally {+ setIsInstalling(false);setDownloadingModel(null);setDownloadProgress({ percentage: 0, downloadedBytes: 0, totalBytes: 0 });}@@ -281,6 +290,7 @@ export function useModelDownload({downloadProgress,isDownloading,isDownloadingModel,+ isInstalling,isCancelling,downloadModel,deleteModel,