Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(models): persist download state across picker remounts

Chadpiha38f57bb159ad
diff --git a/src/components/LocalModelPicker.tsx b/src/components/LocalModelPicker.tsx
index 1f982802b..144c158bc 100644
--- a/src/components/LocalModelPicker.tsx
+++ b/src/components/LocalModelPicker.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useCallback, useMemo } from "react";
+import { useState, useEffect, useCallback, useMemo, useRef } from "react";
import { useTranslation } from "react-i18next";
import { ProviderTabs } from "./ui/ProviderTabs";
import { DownloadProgressBar } from "./ui/DownloadProgressBar";
@@ -53,11 +53,14 @@ export default function LocalModelPicker({
}: LocalModelPickerProps) {
const { t } = useTranslation();
const [downloadedModels, setDownloadedModels] = useState<Set<string>>(new Set());
+ const loadDownloadedModelsRequestRef = useRef(0);
const { confirmDialog, showConfirmDialog, hideConfirmDialog } = useDialogs();
const styles = useMemo(() => MODEL_PICKER_COLORS[colorScheme], [colorScheme]);
const loadDownloadedModels = useCallback(async () => {
+ const requestId = ++loadDownloadedModelsRequestRef.current;
+
try {
let downloaded = new Set<string>();
if (modelType === "whisper") {
@@ -88,27 +91,30 @@ export default function LocalModelPicker({
);
}
}
- setDownloadedModels(downloaded);
- return downloaded;
+ if (requestId === loadDownloadedModelsRequestRef.current) {
+ setDownloadedModels(downloaded);
+ return downloaded;
+ }
+ return null;
} catch (error) {
console.error("Failed to load downloaded models:", error);
- return new Set<string>();
+ return null;
}
}, [modelType]);
useEffect(() => {
const initAndValidate = async () => {
const downloaded = await loadDownloadedModels();
- if (selectedModel && !downloaded.has(selectedModel)) {
+ if (downloaded && selectedModel && !downloaded.has(selectedModel)) {
onModelSelect("");
}
};
initAndValidate();
}, [loadDownloadedModels, selectedModel, onModelSelect]);
- const handleDownloadComplete = useCallback(() => {
- loadDownloadedModels();
- onDownloadComplete?.();
+ const handleDownloadComplete = useCallback(async () => {
+ await loadDownloadedModels();
+ await onDownloadComplete?.();
}, [loadDownloadedModels, onDownloadComplete]);
const {
@@ -119,6 +125,7 @@ export default function LocalModelPicker({
isDownloadingModel,
cancelDownload,
isCancelling,
+ isInstalling,
} = useModelDownload({
modelType,
onDownloadComplete: handleDownloadComplete,
@@ -152,8 +159,14 @@ export default function LocalModelPicker({
const modelName = models.find((m) => m.id === downloadingModel)?.name || downloadingModel;
- return <DownloadProgressBar modelName={modelName} progress={downloadProgress} />;
- }, [downloadingModel, downloadProgress, models]);
+ return (
+ <DownloadProgressBar
+ modelName={modelName}
+ progress={downloadProgress}
+ isInstalling={isInstalling}
+ />
+ );
+ }, [downloadingModel, downloadProgress, isInstalling, models]);
return (
<div className={className}>
@@ -188,6 +201,7 @@ export default function LocalModelPicker({
onDelete={handleDelete}
onCancelDownload={cancelDownload}
isCancelling={isCancelling}
+ isInstalling={isInstalling}
colorScheme={colorScheme}
/>
</div>
diff --git a/src/components/ReasoningModelSelector.tsx b/src/components/ReasoningModelSelector.tsx
index 6f46e4d6c..f374d5e42 100644
--- a/src/components/ReasoningModelSelector.tsx
+++ b/src/components/ReasoningModelSelector.tsx
@@ -424,8 +424,6 @@ export default function ReasoningModelSelector({
}
}, [localProviders, localReasoningProvider]);
- const [downloadedModels, setDownloadedModels] = useState<Set<string>>(new Set());
-
const loadDownloadedModels = useCallback(async () => {
try {
const result = await window.electronAPI?.modelGetAll?.();
@@ -435,7 +433,6 @@ export default function ReasoningModelSelector({
.filter((m: { isDownloaded?: boolean }) => m.isDownloaded)
.map((m: { id: string }) => m.id)
);
- setDownloadedModels(downloaded);
return downloaded;
}
} catch (error) {
@@ -444,10 +441,6 @@ export default function ReasoningModelSelector({
return new Set<string>();
}, []);
- useEffect(() => {
- loadDownloadedModels();
- }, [loadDownloadedModels]);
-
const selectDefaultModelForProvider = (provider: string) => {
// Custom/OpenRouter fetch their model list dynamically — clear instead of
// presetting so another provider's model id can't persist under this one.
@@ -711,7 +704,6 @@ export default function ReasoningModelSelector({
onProviderSelect={handleLocalProviderChange}
modelType="llm"
colorScheme="purple"
- onDownloadComplete={loadDownloadedModels}
/>
<GpuStatusBadge />
</>
diff --git a/src/components/TranscriptionModelPicker.tsx b/src/components/TranscriptionModelPicker.tsx
index 1d9095a4c..aa25cd29d 100644
--- a/src/components/TranscriptionModelPicker.tsx
+++ b/src/components/TranscriptionModelPicker.tsx
@@ -49,6 +49,7 @@ interface LocalModelCardProps {
isDownloaded: boolean;
isDownloading: boolean;
isCancelling: boolean;
+ isInstalling: boolean;
recommended?: boolean;
provider: string;
languageLabel?: string;
@@ -69,6 +70,7 @@ function LocalModelCard({
isDownloaded,
isDownloading,
isCancelling,
+ isInstalling,
recommended,
provider,
languageLabel,
@@ -153,7 +155,7 @@ function LocalModelCard({
e.stopPropagation();
onCancel();
}}
- disabled={isCancelling}
+ disabled={isCancelling || isInstalling}
size="sm"
variant="outline"
className="h-6 px-2.5 text-xs text-destructive border-destructive/25 hover:bg-destructive/8"
@@ -380,8 +382,8 @@ export default function TranscriptionModelPicker({
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- sync prop→state: only re-run when the prop changes
}, [selectedLocalProvider]);
- const isLoadingRef = useRef(false);
- const isLoadingParakeetRef = useRef(false);
+ const localModelsLoadQueueRef = useRef<Promise<void>>(Promise.resolve());
+ const parakeetModelsLoadQueueRef = useRef<Promise<void>>(Promise.resolve());
const loadLocalModelsRef = useRef<(() => Promise<void>) | null>(null);
const loadParakeetModelsRef = useRef<(() => Promise<void>) | null>(null);
const ensureValidCloudSelectionRef = useRef<(() => void) | null>(null);
@@ -423,39 +425,41 @@ export default function TranscriptionModelPicker({
}
}, []);
- const loadLocalModels = useCallback(async () => {
- if (isLoadingRef.current) return;
- isLoadingRef.current = true;
-
- try {
- const result = await window.electronAPI?.listWhisperModels();
- if (result?.success) {
- setLocalModels(result.models);
- validateAndSelectModel(result.models);
+ const loadLocalModels = useCallback(() => {
+ const load = async () => {
+ try {
+ const result = await window.electronAPI?.listWhisperModels();
+ if (result?.success) {
+ setLocalModels(result.models);
+ validateAndSelectModel(result.models);
+ }
+ } catch (error) {
+ logger.error("Failed to load models", { error }, "models");
+ setLocalModels([]);
}
- } catch (error) {
- logger.error("Failed to load models", { error }, "models");
- setLocalModels([]);
- } finally {
- isLoadingRef.current = false;
- }
- }, [validateAndSelectModel]);
+ };
- const loadParakeetModels = useCallback(async () => {
- if (isLoadingParakeetRef.current) return;
- isLoadingParakeetRef.current = true;
+ const queuedLoad = localModelsLoadQueueRef.current.then(load);
+ localModelsLoadQueueRef.current = queuedLoad;
+ return queuedLoad;
+ }, [validateAndSelectModel]);
- try {
- const result = await window.electronAPI?.listParakeetModels();
- if (result?.success) {
- setParakeetModels(result.models);
+ const loadParakeetModels = useCallback(() => {
+ const load = async () => {
+ try {
+ const result = await window.electronAPI?.listParakeetModels();
+ if (result?.success) {
+ setParakeetModels(result.models);
+ }
+ } catch (error) {
+ logger.error("Failed to load Parakeet models", { error }, "models");
+ setParakeetModels([]);
}
- } catch (error) {
- logger.error("Failed to load Parakeet models", { error }, "models");
- setParakeetModels([]);
- } finally {
- isLoadingParakeetRef.current = false;
- }
+ };
+
+ const queuedLoad = parakeetModelsLoadQueueRef.current.then(load);
+ parakeetModelsLoadQueueRef.current = queuedLoad;
+ return queuedLoad;
}, []);
const ensureValidCloudSelection = useCallback(() => {
@@ -823,6 +827,7 @@ export default function TranscriptionModelPicker({
isDownloaded={model.downloaded ?? false}
isDownloading={isDownloadingModel(modelId)}
isCancelling={isCancelling}
+ isInstalling={isInstalling}
recommended={info.recommended}
provider="whisper"
onSelect={() => handleWhisperModelSelect(modelId)}
@@ -897,6 +902,7 @@ export default function TranscriptionModelPicker({
isDownloaded={model.downloaded ?? false}
isDownloading={isDownloadingParakeetModel(modelId)}
isCancelling={isCancellingParakeet}
+ isInstalling={isInstallingParakeet}
recommended={info.recommended}
provider="nvidia"
onSelect={() => handleParakeetModelSelect(modelId)}
diff --git a/src/components/ui/ModelCardList.tsx b/src/components/ui/ModelCardList.tsx
index be64f5d79..2f1abb3b2 100644
--- a/src/components/ui/ModelCardList.tsx
+++ b/src/components/ui/ModelCardList.tsx
@@ -55,6 +55,7 @@ interface ModelCardProps {
onDelete?: (modelId: string) => void;
onCancelDownload?: () => void;
isCancelling?: boolean;
+ isInstalling?: boolean;
}
export function ModelCard({
@@ -67,6 +68,7 @@ export function ModelCard({
onDelete,
onCancelDownload,
isCancelling = false,
+ isInstalling = false,
}: ModelCardProps) {
const { t } = useTranslation();
const styles = COLOR_CONFIG[colorScheme];
@@ -194,7 +196,7 @@ export function ModelCard({
e.stopPropagation();
onCancelDownload?.();
}}
- disabled={isCancelling}
+ disabled={isCancelling || isInstalling}
size="sm"
variant="outline"
className="h-6 px-2.5 text-xs text-destructive border-destructive/25 hover:bg-destructive/8"
@@ -236,6 +238,7 @@ interface ModelCardListProps {
onDelete?: (modelId: string) => void;
onCancelDownload?: () => void;
isCancelling?: boolean;
+ isInstalling?: boolean;
}
export default function ModelCardList({
@@ -249,6 +252,7 @@ export default function ModelCardList({
onDelete,
onCancelDownload,
isCancelling = false,
+ isInstalling = false,
}: ModelCardListProps) {
const { t } = useTranslation();
@@ -270,6 +274,7 @@ export default function ModelCardList({
onDelete={onDelete}
onCancelDownload={onCancelDownload}
isCancelling={isCancelling}
+ isInstalling={isInstalling}
/>
))}
</div>
diff --git a/src/helpers/ModelManager.ts b/src/helpers/ModelManager.ts
index 5bd50cff0..20125e11f 100644
--- a/src/helpers/ModelManager.ts
+++ b/src/helpers/ModelManager.ts
@@ -272,18 +272,12 @@ class ModelManager {
const allModels = modelRegistry.getAllModels();
return Promise.all(
- allModels.map(async (model) => {
- const progress = this.downloadProgress.get(model.id);
-
- return {
- ...model,
- isDownloaded: await this.isModelDownloaded(model.id),
- downloadProgress: progress?.progress || 0,
- downloadedSize: progress?.downloadedSize || 0,
- totalSize: progress?.totalSize || 0,
- isDownloading: this.activeDownloads.has(model.id),
- };
- })
+ allModels.map(async (model) => ({
+ ...model,
+ isDownloaded: await this.isModelDownloaded(model.id),
+ downloadProgress: this.downloadProgress.get(model.id)?.progress || 0,
+ isDownloading: this.activeDownloads.has(model.id),
+ }))
);
}
}
diff --git a/src/helpers/downloadUtils.js b/src/helpers/downloadUtils.js
index 6166aefa4..374091dd4 100644
--- a/src/helpers/downloadUtils.js
+++ b/src/helpers/downloadUtils.js
@@ -359,6 +359,13 @@ function createDownloadSignal() {
};
}
+function createDownloadInProgressError(model, activeModel) {
+ return Object.assign(new Error("A model is already being downloaded"), {
+ code: "DOWNLOAD_IN_PROGRESS",
+ details: { model, activeModel },
+ });
+}
+
async function validateFileSize(filePath, expectedSizeBytes, tolerancePercent = 10) {
const stats = await fsPromises.stat(filePath);
const minSize = expectedSizeBytes * (1 - tolerancePercent / 100);
@@ -498,6 +505,7 @@ module.exports = {
downloadFile,
fetchJson,
createDownloadSignal,
+ createDownloadInProgressError,
validateFileSize,
cleanupStaleDownloads,
checkDiskSpace,
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 6617c66c9..d6f7001b7 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -1850,7 +1850,11 @@ class IPCHandlers {
});
return result;
} catch (error) {
- if (!event.sender.isDestroyed()) {
+ if (
+ error.code !== "DOWNLOAD_IN_PROGRESS" &&
+ error.code !== "DOWNLOAD_CANCELLED" &&
+ !event.sender.isDestroyed()
+ ) {
event.sender.send("whisper-download-progress", {
type: "error",
model: modelName,
@@ -2099,7 +2103,11 @@ class IPCHandlers {
);
return result;
} catch (error) {
- if (!event.sender.isDestroyed()) {
+ if (
+ error.code !== "DOWNLOAD_IN_PROGRESS" &&
+ error.code !== "DOWNLOAD_CANCELLED" &&
+ !event.sender.isDestroyed()
+ ) {
event.sender.send("parakeet-download-progress", {
type: "error",
model: modelName,
@@ -2611,7 +2619,11 @@ class IPCHandlers {
}
return { success: true, path: result };
} catch (error) {
- if (error.code !== "DOWNLOAD_IN_PROGRESS" && !event.sender.isDestroyed()) {
+ if (
+ error.code !== "DOWNLOAD_IN_PROGRESS" &&
+ error.code !== "DOWNLOAD_CANCELLED" &&
+ !event.sender.isDestroyed()
+ ) {
event.sender.send("model-download-progress", {
type: "error",
modelId,
diff --git a/src/helpers/modelManagerBridge.js b/src/helpers/modelManagerBridge.js
index 778928580..6efbad953 100644
--- a/src/helpers/modelManagerBridge.js
+++ b/src/helpers/modelManagerBridge.js
@@ -40,6 +40,7 @@ class ModelManager {
this.downloadProgress = new Map();
this.activeDownloads = new Map();
this.activeRequests = new Map(); // Track HTTP requests for cancellation
+ this.downloadLifecycleVersion = 0;
this.serverManager = new LlamaServerManager();
this.currentServerModelId = null;
this._initialized = false;
@@ -102,29 +103,46 @@ class ModelManager {
async getAllModels() {
this.ensureInitialized();
try {
- const models = [];
+ const modelEntries = [];
for (const provider of getLocalProviders()) {
for (const model of provider.models) {
const modelPath = path.join(this.modelsDir, model.fileName);
- const isDownloaded = await this.checkModelValid(modelPath);
- const progress = this.downloadProgress.get(model.id);
-
- models.push({
- ...model,
- providerId: provider.id,
- providerName: provider.name,
- isDownloaded,
- isDownloading: this.activeDownloads.has(model.id),
- downloadProgress: progress?.progress || 0,
- downloadedSize: progress?.downloadedSize || 0,
- totalSize: progress?.totalSize || 0,
- path: isDownloaded ? modelPath : null,
- });
+ modelEntries.push({ model, provider, modelPath });
}
}
- return models;
+ let downloadedStates = [];
+
+ // A download can finish between checking the final file and reading the
+ // in-memory active state. Retry when that lifecycle changes so callers
+ // never receive the impossible "not downloaded and not downloading" gap.
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ const lifecycleVersion = this.downloadLifecycleVersion;
+ downloadedStates = await Promise.all(
+ modelEntries.map(({ modelPath }) => this.checkModelValid(modelPath))
+ );
+ if (lifecycleVersion === this.downloadLifecycleVersion) break;
+ }
+
+ // Read volatile download state only after all asynchronous filesystem checks
+ // finish so every model belongs to the same main-process snapshot.
+ return modelEntries.map(({ model, provider, modelPath }, index) => {
+ const progress = this.downloadProgress.get(model.id);
+ const isDownloaded = downloadedStates[index];
+
+ return {
+ ...model,
+ providerId: provider.id,
+ providerName: provider.name,
+ isDownloaded,
+ isDownloading: this.activeDownloads.has(model.id),
+ downloadProgress: progress?.progress || 0,
+ downloadedSize: progress?.downloadedSize || 0,
+ totalSize: progress?.totalSize || 0,
+ path: isDownloaded ? modelPath : null,
+ };
+ });
} catch (error) {
console.error("[ModelManager] Error getting all models:", error);
throw error;
@@ -186,13 +204,16 @@ class ModelManager {
return modelPath;
}
- if (this.activeDownloads.get(modelId)) {
- throw new ModelError("Model is already being downloaded", "DOWNLOAD_IN_PROGRESS", {
+ if (this.activeDownloads.size > 0) {
+ const activeModelId = this.activeDownloads.keys().next().value;
+ throw new ModelError("A model is already being downloaded", "DOWNLOAD_IN_PROGRESS", {
modelId,
+ activeModelId,
});
}
this.activeDownloads.set(modelId, true);
+ this.downloadLifecycleVersion += 1;
const { signal, abort } = createDownloadSignal();
this.activeRequests.set(modelId, { abort });
@@ -257,7 +278,9 @@ class ModelManager {
}
throw error;
} finally {
- this.activeDownloads.delete(modelId);
+ if (this.activeDownloads.delete(modelId)) {
+ this.downloadLifecycleVersion += 1;
+ }
this.activeRequests.delete(modelId);
this.downloadProgress.delete(modelId);
}
@@ -271,9 +294,8 @@ class ModelManager {
cancelDownload(modelId) {
const entry = this.activeRequests.get(modelId);
if (entry) {
- this.activeDownloads.delete(modelId);
- this.activeRequests.delete(modelId);
- this.downloadProgress.delete(modelId);
+ // Keep the guard and status visible until downloadModel's finally block
+ // has finished cleaning up the writer and its temporary file.
entry.abort();
return true;
}
diff --git a/src/helpers/parakeet.js b/src/helpers/parakeet.js
index e01a0c59b..48e079747 100644
--- a/src/helpers/parakeet.js
+++ b/src/helpers/parakeet.js
@@ -7,6 +7,7 @@ const debugLogger = require("./debugLogger");
const {
downloadFile,
createDownloadSignal,
+ createDownloadInProgressError,
cleanupStaleDownloads,
checkDiskSpace,
} = require("./downloadUtils");
@@ -264,25 +265,37 @@ class ParakeetManager {
const modelPath = this.getModelPath(modelName);
const modelsDir = this.getModelsDir();
- await fsPromises.mkdir(modelsDir, { recursive: true });
-
if (this.serverManager.isModelDownloaded(modelName)) {
return { model: modelName, downloaded: true, path: modelPath, success: true };
}
- const spaceCheck = await checkDiskSpace(modelsDir, modelConfig.size * 2.5);
- if (!spaceCheck.ok) {
- throw new Error(
- `Not enough disk space to download and extract model. Need ~${Math.round((modelConfig.size * 2.5) / 1_000_000)}MB, ` +
- `only ${Math.round(spaceCheck.availableBytes / 1_000_000)}MB available.`
- );
+ if (this.currentDownloadProcess) {
+ throw createDownloadInProgressError(modelName, this.currentDownloadProcess.model);
}
const archivePath = path.join(modelsDir, `${modelName}.tar.bz2`);
const { signal, abort } = createDownloadSignal();
- this.currentDownloadProcess = { abort };
+ const downloadProcess = {
+ abort,
+ model: modelName,
+ phase: "progress",
+ percentage: 0,
+ downloadedBytes: 0,
+ totalBytes: 0,
+ };
+ this.currentDownloadProcess = downloadProcess;
try {
+ await fsPromises.mkdir(modelsDir, { recursive: true });
+
+ const spaceCheck = await checkDiskSpace(modelsDir, modelConfig.size * 2.5);
+ if (!spaceCheck.ok) {
+ throw new Error(
+ `Not enough disk space to download and extract model. Need ~${Math.round((modelConfig.size * 2.5) / 1_000_000)}MB, ` +
+ `only ${Math.round(spaceCheck.availableBytes / 1_000_000)}MB available.`
+ );
+ }
+
let archiveReady = false;
try {
const stats = await fsPromises.stat(archivePath);
@@ -300,6 +313,10 @@ class ParakeetManager {
timeout: 600000,
signal,
onProgress: (downloadedBytes, totalBytes) => {
+ downloadProcess.percentage =
+ totalBytes > 0 ? Math.round((downloadedBytes / totalBytes) * 100) : 0;
+ downloadProcess.downloadedBytes = downloadedBytes;
+ downloadProcess.totalBytes = totalBytes;
if (progressCallback) {
progressCallback({
type: "progress",
@@ -313,6 +330,8 @@ class ParakeetManager {
});
}
+ downloadProcess.phase = "installing";
+ downloadProcess.percentage = 100;
if (progressCallback) {
progressCallback({ type: "installing", model: modelName, percentage: 100 });
}
@@ -354,11 +373,15 @@ class ParakeetManager {
} catch (error) {
if (error.isAbort) {
await fsPromises.unlink(archivePath).catch(() => {});
- throw new Error("Download interrupted by user");
+ throw Object.assign(new Error("Download interrupted by user"), {
+ code: "DOWNLOAD_CANCELLED",
+ });
}
throw error;
} finally {
- this.currentDownloadProcess = null;
+ if (this.currentDownloadProcess === downloadProcess) {
+ this.currentDownloadProcess = null;
+ }
}
}
@@ -476,8 +499,14 @@ class ParakeetManager {
async cancelDownload() {
if (this.currentDownloadProcess) {
+ if (this.currentDownloadProcess.phase === "installing") {
+ return {
+ success: false,
+ error: "Model installation cannot be cancelled once extraction has started",
+ code: "INSTALLATION_IN_PROGRESS",
+ };
+ }
this.currentDownloadProcess.abort();
- this.currentDownloadProcess = null;
return { success: true, message: "Download cancelled" };
}
return { success: false, error: "No active download to cancel" };
@@ -485,6 +514,14 @@ class ParakeetManager {
async checkModelStatus(modelName) {
const modelPath = this.getModelPath(modelName);
+ const activeDownload = this.currentDownloadProcess?.model === modelName;
+ const downloadStatus = {
+ isDownloading: activeDownload,
+ isInstalling: activeDownload && this.currentDownloadProcess.phase === "installing",
+ downloadProgress: activeDownload ? this.currentDownloadProcess.percentage : 0,
+ downloadedBytes: activeDownload ? this.currentDownloadProcess.downloadedBytes : 0,
+ totalBytes: activeDownload ? this.currentDownloadProcess.totalBytes : 0,
+ };
if (this.serverManager.isModelDownloaded(modelName)) {
try {
@@ -497,13 +534,14 @@ class ParakeetManager {
size_bytes: stats.size,
size_mb: Math.round(stats.size / (1024 * 1024)),
success: true,
+ ...downloadStatus,
};
} catch {
- return { model: modelName, downloaded: false, success: true };
+ return { model: modelName, downloaded: false, success: true, ...downloadStatus };
}
}
- return { model: modelName, downloaded: false, success: true };
+ return { model: modelName, downloaded: false, success: true, ...downloadStatus };
}
async listParakeetModels() {
diff --git a/src/helpers/whisper.js b/src/helpers/whisper.js
index dd7d8de54..de5b5c087 100644
--- a/src/helpers/whisper.js
+++ b/src/helpers/whisper.js
@@ -5,6 +5,7 @@ const debugLogger = require("./debugLogger");
const {
downloadFile,
createDownloadSignal,
+ createDownloadInProgressError,
validateFileSize,
cleanupStaleDownloads,
checkDiskSpace,
@@ -503,8 +504,6 @@ class WhisperManager {
const modelPath = this.getModelPath(modelName);
const modelsDir = this.getModelsDir();
- await fsPromises.mkdir(modelsDir, { recursive: true });
-
if (fs.existsSync(modelPath)) {
const stats = await fsPromises.stat(modelPath);
return {
@@ -517,23 +516,41 @@ class WhisperManager {
};
}
- const spaceCheck = await checkDiskSpace(modelsDir, modelConfig.size * 1.2);
- if (!spaceCheck.ok) {
- throw new Error(
- `Not enough disk space to download model. Need ~${Math.round((modelConfig.size * 1.2) / 1_000_000)}MB, ` +
- `only ${Math.round(spaceCheck.availableBytes / 1_000_000)}MB available.`
- );
+ if (this.currentDownloadProcess) {
+ throw createDownloadInProgressError(modelName, this.currentDownloadProcess.model);
}
const { signal, abort } = createDownloadSignal();
- this.currentDownloadProcess = { abort };
+ const downloadProcess = {
+ abort,
+ model: modelName,
+ phase: "progress",
+ percentage: 0,
+ downloadedBytes: 0,
+ totalBytes: 0,
+ };
+ this.currentDownloadProcess = downloadProcess;
try {
+ await fsPromises.mkdir(modelsDir, { recursive: true });
+
+ const spaceCheck = await checkDiskSpace(modelsDir, modelConfig.size * 1.2);
+ if (!spaceCheck.ok) {
+ throw new Error(
+ `Not enough disk space to download model. Need ~${Math.round((modelConfig.size * 1.2) / 1_000_000)}MB, ` +
+ `only ${Math.round(spaceCheck.availableBytes / 1_000_000)}MB available.`
+ );
+ }
+
await downloadFile(modelConfig.url, modelPath, {
timeout: 600000,
signal,
expectedSize: modelConfig.size,
onProgress: (downloadedBytes, totalBytes) => {
+ downloadProcess.percentage =
+ totalBytes > 0 ? Math.round((downloadedBytes / totalBytes) * 100) : 0;
+ downloadProcess.downloadedBytes = downloadedBytes;
+ downloadProcess.totalBytes = totalBytes;
if (progressCallback) {
progressCallback({
type: "progress",
@@ -564,18 +581,21 @@ class WhisperManager {
};
} catch (error) {
if (error.isAbort) {
- throw new Error("Download interrupted by user");
+ throw Object.assign(new Error("Download interrupted by user"), {
+ code: "DOWNLOAD_CANCELLED",
+ });
}
throw error;
} finally {
- this.currentDownloadProcess = null;
+ if (this.currentDownloadProcess === downloadProcess) {
+ this.currentDownloadProcess = null;
+ }
}
}
async cancelDownload() {
if (this.currentDownloadProcess) {
this.currentDownloadProcess.abort();
- this.currentDownloadProcess = null;
return { success: true, message: "Download cancelled" };
}
return { success: false, error: "No active download to cancel" };
@@ -583,6 +603,14 @@ class WhisperManager {
async checkModelStatus(modelName) {
const modelPath = this.getModelPath(modelName);
+ const activeDownload = this.currentDownloadProcess?.model === modelName;
+ const downloadStatus = {
+ isDownloading: activeDownload,
+ isInstalling: false,
+ downloadProgress: activeDownload ? this.currentDownloadProcess.percentage : 0,
+ downloadedBytes: activeDownload ? this.currentDownloadProcess.downloadedBytes : 0,
+ totalBytes: activeDownload ? this.currentDownloadProcess.totalBytes : 0,
+ };
if (fs.existsSync(modelPath)) {
const stats = await fsPromises.stat(modelPath);
@@ -593,10 +621,11 @@ class WhisperManager {
size_bytes: stats.size,
size_mb: Math.round(stats.size / (1024 * 1024)),
success: true,
+ ...downloadStatus,
};
}
- return { model: modelName, downloaded: false, success: true };
+ return { model: modelName, downloaded: false, success: true, ...downloadStatus };
}
async listWhisperModels() {
diff --git a/src/hooks/useLocalModels.ts b/src/hooks/useLocalModels.ts
index 9358d1bce..cf39a904f 100644
--- a/src/hooks/useLocalModels.ts
+++ b/src/hooks/useLocalModels.ts
@@ -1,6 +1,5 @@
import { useState, useEffect, useCallback } from "react";
import { ModelDefinition } from "../models/ModelRegistry";
-import type { LocalLLMDownloadProgressEvent } from "../types/electron";
import "../types/electron";
interface ModelWithStatus extends ModelDefinition {
@@ -9,13 +8,18 @@ interface ModelWithStatus extends ModelDefinition {
downloadProgress: number;
}
+interface LLMDownloadProgressEvent {
+ modelId: string;
+ progress: number;
+ downloadedSize: number;
+ totalSize: number;
+}
+
export function useLocalModels() {
const [models, setModels] = useState<ModelWithStatus[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
- const [progressMap, setProgressMap] = useState<Map<string, LocalLLMDownloadProgressEvent>>(
- new Map()
- );
+ const [progressMap, setProgressMap] = useState<Map<string, LLMDownloadProgressEvent>>(new Map());
const loadModels = useCallback(async () => {
try {
@@ -34,28 +38,7 @@ export function useLocalModels() {
useEffect(() => {
loadModels();
- const handleProgress = (_event: any, data: LocalLLMDownloadProgressEvent) => {
- if (data.type === "complete") {
- setProgressMap((prev) => {
- const next = new Map(prev);
- next.delete(data.modelId);
- return next;
- });
- void loadModels();
- return;
- }
-
- if (data.type === "error") {
- setProgressMap((prev) => {
- const next = new Map(prev);
- next.delete(data.modelId);
- return next;
- });
- setError(data.error || "Failed to download model");
- void loadModels();
- return;
- }
-
+ const handleProgress = (_event: any, data: LLMDownloadProgressEvent) => {
setProgressMap((prev) => new Map(prev).set(data.modelId, data));
};
diff --git a/src/hooks/useModelDownload.ts b/src/hooks/useModelDownload.ts
index 4807a9ac6..58fb53628 100644
--- a/src/hooks/useModelDownload.ts
+++ b/src/hooks/useModelDownload.ts
@@ -6,7 +6,9 @@ import { useToast } from "../components/ui/useToast";
import type {
LocalLLMDownloadProgressEvent,
LocalLLMModelStatus,
+ ParakeetModelResult,
WhisperDownloadProgressData,
+ WhisperModelResult,
} from "../types/electron";
import "../types/electron";
@@ -28,6 +30,20 @@ interface UseModelDownloadOptions {
onModelsCleared?: () => void;
}
+interface ModelDownloadTerminalEvent {
+ type: "complete" | "error";
+ modelId: string;
+ error?: string;
+ code?: string;
+}
+
+interface PendingModelDownloadRequest {
+ modelId: string;
+ terminalEvent?: ModelDownloadTerminalEvent;
+}
+
+type TranscriptionModelStatus = WhisperModelResult | ParakeetModelResult;
+
export function formatETA(seconds: number): string {
if (seconds < 60) return `${Math.round(seconds)}s`;
const minutes = Math.floor(seconds / 60);
@@ -71,7 +87,9 @@ export function useModelDownload({
const [downloadError, setDownloadError] = useState<string | null>(null);
const isCancellingRef = useRef(false);
const lastProgressUpdateRef = useRef(0);
- const activeDownloadRequestRef = useRef<string | null>(null);
+ const downloadingModelRef = useRef<string | null>(null);
+ const downloadStateVersionRef = useRef(0);
+ const activeDownloadRequestRef = useRef<PendingModelDownloadRequest | null>(null);
const { showAlertDialog } = useDialogs();
const { toast } = useToast();
@@ -91,46 +109,172 @@ export function useModelDownload({
onModelsClearedRef.current = onModelsCleared;
}, [onModelsCleared]);
+ useEffect(() => {
+ downloadingModelRef.current = downloadingModel;
+ }, [downloadingModel]);
+
useEffect(() => {
const handleModelsCleared = () => onModelsClearedRef.current?.();
window.addEventListener("openwhispr-models-cleared", handleModelsCleared);
return () => window.removeEventListener("openwhispr-models-cleared", handleModelsCleared);
}, []);
- const hydrateActiveLLMDownload = useCallback(
- async (preferredModelId?: string) => {
- if (modelType !== "llm") return false;
-
- let models: LocalLLMModelStatus[] | undefined;
+ const hydrateActiveDownload = useCallback(
+ async (preferredModelId?: string, shouldApply: () => boolean = () => true) => {
+ const stateVersion = downloadStateVersionRef.current;
+
+ let activeModel:
+ | {
+ id: string;
+ downloadProgress?: number;
+ downloadedBytes?: number;
+ totalBytes?: number;
+ isInstalling?: boolean;
+ }
+ | undefined;
try {
- models = await window.electronAPI?.modelGetAll?.();
+ if (modelType === "llm") {
+ const models: LocalLLMModelStatus[] | undefined =
+ await window.electronAPI?.modelGetAll?.();
+ const active =
+ models?.find((model) => model.isDownloading && model.id === preferredModelId) ??
+ models?.find((model) => model.isDownloading);
+ if (active) {
+ activeModel = {
+ id: active.id,
+ downloadProgress: active.downloadProgress,
+ downloadedBytes: active.downloadedSize,
+ totalBytes: active.totalSize,
+ };
+ }
+ } else {
+ const result =
+ modelType === "whisper"
+ ? await window.electronAPI?.listWhisperModels?.()
+ : await window.electronAPI?.listParakeetModels?.();
+ const models = result?.models as TranscriptionModelStatus[] | undefined;
+ const active =
+ models?.find((model) => model.isDownloading && model.model === preferredModelId) ??
+ models?.find((model) => model.isDownloading);
+ if (active) {
+ activeModel = {
+ id: active.model,
+ downloadProgress: active.downloadProgress,
+ downloadedBytes: active.downloadedBytes,
+ totalBytes: active.totalBytes,
+ isInstalling: active.isInstalling,
+ };
+ }
+ }
} catch {
return false;
}
- const activeModel =
- models?.find((model) => model.isDownloading && model.id === preferredModelId) ??
- models?.find((model) => model.isDownloading);
+ if (!shouldApply()) return false;
+
+ // A progress/terminal event or a new request supersedes this snapshot.
+ if (downloadStateVersionRef.current !== stateVersion) {
+ return downloadingModelRef.current !== null;
+ }
+
if (!activeModel) return false;
+ downloadStateVersionRef.current += 1;
+ downloadingModelRef.current = activeModel.id;
setDownloadingModel(activeModel.id);
+ setIsInstalling(activeModel.isInstalling ?? false);
setDownloadError(null);
setDownloadProgress({
percentage: activeModel.downloadProgress || 0,
- downloadedBytes: activeModel.downloadedSize || 0,
- totalBytes: activeModel.totalSize || 0,
+ downloadedBytes: activeModel.downloadedBytes || 0,
+ totalBytes: activeModel.totalBytes || 0,
});
return true;
},
[modelType]
);
- const handleWhisperProgress = useCallback(
+ const applyTerminalEvent = useCallback(
+ (data: ModelDownloadTerminalEvent) => {
+ const trackedModel = downloadingModelRef.current;
+ if (trackedModel && trackedModel !== data.modelId) return;
+
+ const terminalVersion = ++downloadStateVersionRef.current;
+
+ if (data.type === "complete") {
+ void (async () => {
+ try {
+ await onDownloadCompleteRef.current?.();
+ } catch {
+ // The model is already on disk; a refresh failure is non-fatal.
+ } finally {
+ if (downloadStateVersionRef.current !== terminalVersion) return;
+ downloadingModelRef.current = null;
+ setIsInstalling(false);
+ setDownloadingModel(null);
+ setDownloadProgress({ percentage: 0, downloadedBytes: 0, totalBytes: 0 });
+ }
+ })();
+ return;
+ }
+
+ const msg = getDownloadErrorMessage(
+ t,
+ data.error || t("hooks.modelDownload.errors.unknown"),
+ data.code
+ );
+ setDownloadError(msg);
+ showAlertDialogRef.current({
+ title:
+ data.code === "EXTRACTION_FAILED"
+ ? t("hooks.modelDownload.installationFailed.title")
+ : t("hooks.modelDownload.downloadFailed.title"),
+ description: msg,
+ });
+ downloadingModelRef.current = null;
+ setIsInstalling(false);
+ setDownloadingModel(null);
+ setDownloadProgress({ percentage: 0, downloadedBytes: 0, totalBytes: 0 });
+ },
+ [t]
+ );
+
+ const handleTranscriptionProgress = useCallback(
(_event: unknown, data: WhisperDownloadProgressData) => {
+ if (isCancellingRef.current) return;
+
+ const trackedModel = downloadingModelRef.current;
+ if (trackedModel && trackedModel !== data.model) return;
+
+ if (data.type === "complete" || data.type === "error") {
+ if (data.code === "DOWNLOAD_CANCELLED") return;
+
+ const terminalEvent: ModelDownloadTerminalEvent = {
+ type: data.type,
+ modelId: data.model,
+ error: data.error,
+ code: data.code,
+ };
+ const activeRequest = activeDownloadRequestRef.current;
+ if (activeRequest?.modelId === data.model) {
+ downloadStateVersionRef.current += 1;
+ activeRequest.terminalEvent = terminalEvent;
+ return;
+ }
+ applyTerminalEvent(terminalEvent);
+ return;
+ }
+
+ downloadStateVersionRef.current += 1;
+ downloadingModelRef.current = data.model;
+ setDownloadingModel(data.model);
+ setDownloadError(null);
+
if (data.type === "progress") {
const now = Date.now();
if (now - lastProgressUpdateRef.current < PROGRESS_THROTTLE_MS) return;
lastProgressUpdateRef.current = now;
+ setIsInstalling(false);
setDownloadProgress({
percentage: data.percentage || 0,
downloadedBytes: data.downloaded_bytes || 0,
@@ -138,31 +282,13 @@ export function useModelDownload({
});
} else if (data.type === "installing") {
setIsInstalling(true);
- } else if (data.type === "complete") {
- if (isCancellingRef.current) return;
- setIsInstalling(false);
- // Don't clear downloadingModel/downloadProgress here — let downloadModel's
- // finally block handle it after the model list has been refreshed.
- // This prevents a flash where the model appears "not downloaded".
- } else if (data.type === "error") {
- if (isCancellingRef.current) return;
- const msg = getDownloadErrorMessage(
- t,
- data.error || t("hooks.modelDownload.errors.unknown"),
- data.code
- );
- const title =
- data.code === "EXTRACTION_FAILED"
- ? t("hooks.modelDownload.installationFailed.title")
- : t("hooks.modelDownload.downloadFailed.title");
- setDownloadError(msg);
- showAlertDialogRef.current({ title, description: msg });
- setIsInstalling(false);
- setDownloadingModel(null);
- setDownloadProgress({ percentage: 0, downloadedBytes: 0, totalBytes: 0 });
+ setDownloadProgress((current) => ({
+ ...current,
+ percentage: data.percentage ?? 100,
+ }));
}
},
- [t]
+ [applyTerminalEvent]
);
const handleLLMProgress = useCallback(
@@ -170,32 +296,32 @@ export function useModelDownload({
if (isCancellingRef.current) return;
if (data.type === "complete") {
- if (activeDownloadRequestRef.current === data.modelId) return;
- setIsInstalling(false);
- setDownloadingModel(null);
- setDownloadProgress({ percentage: 0, downloadedBytes: 0, totalBytes: 0 });
- void onDownloadCompleteRef.current?.();
+ const activeRequest = activeDownloadRequestRef.current;
+ if (activeRequest?.modelId === data.modelId) {
+ downloadStateVersionRef.current += 1;
+ activeRequest.terminalEvent = data;
+ return;
+ }
+ applyTerminalEvent({ ...data, modelId: data.modelId });
return;
}
if (data.type === "error") {
- if (activeDownloadRequestRef.current === data.modelId) return;
- const msg = getDownloadErrorMessage(
- t,
- data.error || t("hooks.modelDownload.errors.unknown"),
- data.code
- );
- setDownloadError(msg);
- showAlertDialogRef.current({
- title: t("hooks.modelDownload.downloadFailed.title"),
- description: msg,
- });
- setIsInstalling(false);
- setDownloadingModel(null);
- setDownloadProgress({ percentage: 0, downloadedBytes: 0, totalBytes: 0 });
+ const activeRequest = activeDownloadRequestRef.current;
+ if (activeRequest?.modelId === data.modelId) {
+ downloadStateVersionRef.current += 1;
+ activeRequest.terminalEvent = data;
+ return;
+ }
+ applyTerminalEvent({ ...data, modelId: data.modelId });
return;
}
+ const trackedModel = downloadingModelRef.current;
+ if (trackedModel && trackedModel !== data.modelId) return;
+
+ downloadStateVersionRef.current += 1;
+
const now = Date.now();
const isComplete = (data.progress || 0) >= 100;
if (!isComplete && now - lastProgressUpdateRef.current < PROGRESS_THROTTLE_MS) {
@@ -203,6 +329,7 @@ export function useModelDownload({
}
lastProgressUpdateRef.current = now;
+ downloadingModelRef.current = data.modelId;
setDownloadingModel(data.modelId);
setDownloadProgress({
percentage: data.progress || 0,
@@ -210,16 +337,16 @@ export function useModelDownload({
totalBytes: data.totalSize || 0,
});
},
- [t]
+ [applyTerminalEvent]
);
useEffect(() => {
let dispose: (() => void) | undefined;
if (modelType === "whisper") {
- dispose = window.electronAPI?.onWhisperDownloadProgress(handleWhisperProgress);
+ dispose = window.electronAPI?.onWhisperDownloadProgress(handleTranscriptionProgress);
} else if (modelType === "parakeet") {
- dispose = window.electronAPI?.onParakeetDownloadProgress(handleWhisperProgress);
+ dispose = window.electronAPI?.onParakeetDownloadProgress(handleTranscriptionProgress);
} else {
dispose = window.electronAPI?.onModelDownloadProgress(handleLLMProgress);
}
@@ -227,15 +354,34 @@ export function useModelDownload({
return () => {
dispose?.();
};
- }, [handleWhisperProgress, handleLLMProgress, modelType]);
+ }, [handleTranscriptionProgress, handleLLMProgress, modelType]);
useEffect(() => {
- void hydrateActiveLLMDownload();
- }, [hydrateActiveLLMDownload]);
+ let cancelled = false;
+
+ const hydrateAfterMount = async () => {
+ // A remount can overlap a download starting or its final atomic file move.
+ // Retry briefly so a single transitional snapshot cannot restore the idle UI.
+ for (const delay of [0, 200, 600]) {
+ if (delay > 0) {
+ await new Promise((resolve) => setTimeout(resolve, delay));
+ }
+ if (cancelled) return;
+
+ const hydrated = await hydrateActiveDownload(undefined, () => !cancelled);
+ if (cancelled || hydrated || downloadingModelRef.current) return;
+ }
+ };
+
+ void hydrateAfterMount();
+ return () => {
+ cancelled = true;
+ };
+ }, [hydrateActiveDownload]);
const downloadModel = useCallback(
async (modelId: string, onSelectAfterDownload?: (id: string) => void) => {
- if (downloadingModel) {
+ if (downloadingModelRef.current) {
toast({
title: t("hooks.modelDownload.downloadInProgress.title"),
description: t("hooks.modelDownload.downloadInProgress.description"),
@@ -244,78 +390,73 @@ export function useModelDownload({
}
let keepActiveDownloadState = false;
+ let terminalEventApplied = false;
+ const downloadRequest: PendingModelDownloadRequest = { modelId };
try {
+ downloadStateVersionRef.current += 1;
+ downloadingModelRef.current = modelId;
setDownloadingModel(modelId);
+ setIsInstalling(false);
setDownloadError(null);
setDownloadProgress({ percentage: 0, downloadedBytes: 0, totalBytes: 0 });
lastProgressUpdateRef.current = 0; // Reset throttle timer
- activeDownloadRequestRef.current = modelId;
+ activeDownloadRequestRef.current = downloadRequest;
- let success = false;
+ let result: { success?: boolean; error?: string; code?: string } | undefined;
if (modelType === "whisper") {
- const result = await window.electronAPI?.downloadWhisperModel(modelId);
- if (!result?.success && !result?.error?.includes("interrupted by user")) {
- const msg = getDownloadErrorMessage(
- t,
- result?.error || t("hooks.modelDownload.errors.unknown"),
- result?.code
- );
- setDownloadError(msg);
- showAlertDialog({
- title: t("hooks.modelDownload.downloadFailed.title"),
- description: msg,
- });
- } else {
- success = result?.success ?? false;
- }
+ result = await window.electronAPI?.downloadWhisperModel(modelId);
} else if (modelType === "parakeet") {
- const result = await window.electronAPI?.downloadParakeetModel(modelId);
- if (!result?.success && !result?.error?.includes("interrupted by user")) {
- const msg = getDownloadErrorMessage(
- t,
- result?.error || t("hooks.modelDownload.errors.unknown"),
- result?.code
- );
- const title =
- result?.code === "EXTRACTION_FAILED"
- ? t("hooks.modelDownload.installationFailed.title")
- : t("hooks.modelDownload.downloadFailed.title");
- setDownloadError(msg);
- showAlertDialog({ title, description: msg });
- } else {
- success = result?.success ?? false;
- }
+ result = await window.electronAPI?.downloadParakeetModel(modelId);
} else {
- const result = (await window.electronAPI?.modelDownload?.(modelId)) as unknown as
+ result = (await window.electronAPI?.modelDownload?.(modelId)) as unknown as
{ success: boolean; error?: string; code?: string } | undefined;
- if (result && !result.success && result.error) {
- if (result.code === "DOWNLOAD_IN_PROGRESS") {
+ }
+
+ if (!result?.success) {
+ const wasCancelled =
+ result?.code === "DOWNLOAD_CANCELLED" ||
+ result?.error?.includes("interrupted by user") ||
+ result?.error?.includes("cancelled by user");
+ if (wasCancelled) return;
+
+ if (result?.code === "DOWNLOAD_IN_PROGRESS") {
+ const hydrated = await hydrateActiveDownload(modelId);
+ const terminalEvent = downloadRequest.terminalEvent;
+
+ if (terminalEvent) {
+ activeDownloadRequestRef.current = null;
+ terminalEventApplied = true;
+ applyTerminalEvent(terminalEvent);
+ } else if (hydrated) {
keepActiveDownloadState = true;
- const hydrated = await hydrateActiveLLMDownload(modelId);
- if (!hydrated) {
- setDownloadProgress({ percentage: 0, downloadedBytes: 0, totalBytes: 0 });
+ } else {
+ try {
+ await onDownloadCompleteRef.current?.();
+ } catch {
+ // The active download ended while the duplicate request was resolving.
}
- toast({
- title: t("hooks.modelDownload.downloadInProgress.title"),
- description: t("hooks.modelDownload.downloadInProgress.description"),
- });
- return;
}
+ toast({
+ title: t("hooks.modelDownload.downloadInProgress.title"),
+ description: t("hooks.modelDownload.downloadInProgress.description"),
+ });
+ return;
+ }
+ if (result?.error) {
const msg = getDownloadErrorMessage(t, result.error, result.code);
setDownloadError(msg);
showAlertDialog({
- title: t("hooks.modelDownload.downloadFailed.title"),
+ title:
+ result.code === "EXTRACTION_FAILED"
+ ? t("hooks.modelDownload.installationFailed.title")
+ : t("hooks.modelDownload.downloadFailed.title"),
description: msg,
});
- } else {
- success = result?.success ?? false;
}
- }
-
- if (success) {
+ } else {
onSelectAfterDownload?.(modelId);
}
@@ -344,14 +485,18 @@ export function useModelDownload({
});
}
} finally {
- activeDownloadRequestRef.current = null;
+ if (activeDownloadRequestRef.current === downloadRequest) {
+ activeDownloadRequestRef.current = null;
+ }
if (keepActiveDownloadState) return;
+ if (terminalEventApplied) return;
+ downloadingModelRef.current = null;
setIsInstalling(false);
setDownloadingModel(null);
setDownloadProgress({ percentage: 0, downloadedBytes: 0, totalBytes: 0 });
}
},
- [downloadingModel, hydrateActiveLLMDownload, modelType, showAlertDialog, toast, t]
+ [applyTerminalEvent, hydrateActiveDownload, modelType, showAlertDialog, toast, t]
);
const deleteModel = useCallback(
@@ -397,18 +542,23 @@ export function useModelDownload({
);
const cancelDownload = useCallback(async () => {
- if (!downloadingModel || isCancelling) return;
+ if (!downloadingModel || isCancelling || isInstalling) return;
setIsCancelling(true);
isCancellingRef.current = true;
+ let cancelled = false;
try {
+ let result: { success: boolean; error?: string; code?: string } | undefined;
if (modelType === "whisper") {
- await window.electronAPI?.cancelWhisperDownload();
+ result = await window.electronAPI?.cancelWhisperDownload();
} else if (modelType === "parakeet") {
- await window.electronAPI?.cancelParakeetDownload();
+ result = await window.electronAPI?.cancelParakeetDownload();
} else {
- await window.electronAPI?.modelCancelDownload?.(downloadingModel);
+ result = await window.electronAPI?.modelCancelDownload?.(downloadingModel);
}
+ if (!result?.success) return;
+
+ cancelled = true;
toast({
title: t("hooks.modelDownload.downloadCancelled.title"),
description: t("hooks.modelDownload.downloadCancelled.description"),
@@ -418,11 +568,16 @@ export function useModelDownload({
} finally {
setIsCancelling(false);
isCancellingRef.current = false;
+ if (!cancelled) return;
+
+ downloadStateVersionRef.current += 1;
+ downloadingModelRef.current = null;
+ setIsInstalling(false);
setDownloadingModel(null);
setDownloadProgress({ percentage: 0, downloadedBytes: 0, totalBytes: 0 });
onDownloadCompleteRef.current?.();
}
- }, [downloadingModel, isCancelling, modelType, toast, t]);
+ }, [downloadingModel, isCancelling, isInstalling, modelType, toast, t]);
const isDownloading = downloadingModel !== null;
const isDownloadingModel = useCallback(
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 8350c7bf1..ebb5b46a9 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -264,6 +264,11 @@ export interface WhisperModelResult {
size_mb?: number;
error?: string;
code?: string;
+ isDownloading?: boolean;
+ isInstalling?: boolean;
+ downloadProgress?: number;
+ downloadedBytes?: number;
+ totalBytes?: number;
}
export interface WhisperModelDeleteResult {
@@ -276,7 +281,7 @@ export interface WhisperModelDeleteResult {
export interface WhisperModelsListResult {
success: boolean;
- models: Array<{ model: string; downloaded: boolean; size_mb?: number }>;
+ models: WhisperModelResult[];
cache_dir: string;
}
@@ -300,11 +305,7 @@ export interface AudioDiagnosticsResult {
export type SystemAudioMode = "native" | "loopback" | "portal" | "unsupported";
export type SystemAudioStrategy =
- | "native"
- | "loopback"
- | "pipewire-loopback"
- | "wasapi-loopback"
- | "unsupported";
+ "native" | "loopback" | "pipewire-loopback" | "wasapi-loopback" | "unsupported";
export interface SystemAudioAccessResult {
granted: boolean;
@@ -378,6 +379,11 @@ export interface ParakeetModelResult {
size_mb?: number;
error?: string;
code?: string;
+ isDownloading?: boolean;
+ isInstalling?: boolean;
+ downloadProgress?: number;
+ downloadedBytes?: number;
+ totalBytes?: number;
}
export interface ParakeetModelDeleteResult {
@@ -391,7 +397,7 @@ export interface ParakeetModelDeleteResult {
export interface ParakeetModelsListResult {
success: boolean;
- models: Array<{ model: string; downloaded: boolean; size_mb?: number }>;
+ models: ParakeetModelResult[];
cache_dir: string;
}
@@ -856,6 +862,7 @@ declare global {
success: boolean;
message?: string;
error?: string;
+ code?: string;
}>;
getParakeetDiagnostics: () => Promise<ParakeetDiagnosticsResult>;
diff --git a/test/helpers/modelManagerBridgeDownloadStatus.test.js b/test/helpers/modelManagerBridgeDownloadStatus.test.js
index 101f94be4..38ad4935b 100644
--- a/test/helpers/modelManagerBridgeDownloadStatus.test.js
+++ b/test/helpers/modelManagerBridgeDownloadStatus.test.js
@@ -66,3 +66,108 @@ test("getAllModels surfaces in-flight local model download state", async (t) =>
assert.equal(activeModel.totalSize, 1000);
assert.equal(activeModel.path, null);
});
+
+test("getAllModels retries when a download completes during filesystem checks", async (t) => {
+ const tmpHome = await fs.mkdtemp(path.join(os.tmpdir(), "openwhispr-model-snapshot-"));
+ electronHome = tmpHome;
+ t.after(() => fs.rm(tmpHome, { recursive: true, force: true }));
+
+ const modelManager = loadModelManager();
+ const model = modelRegistryData.localProviders[0].models[0];
+ const originalCheckModelValid = modelManager.checkModelValid;
+ let checkCount = 0;
+ let downloadCompleted = false;
+
+ modelManager.activeDownloads.set(model.id, true);
+ modelManager.downloadLifecycleVersion += 1;
+ modelManager.downloadProgress.set(model.id, {
+ modelId: model.id,
+ progress: 42,
+ downloadedSize: 420,
+ totalSize: 1000,
+ });
+ modelManager.checkModelValid = async (modelPath) => {
+ checkCount += 1;
+ if (checkCount === 2) {
+ modelManager.activeDownloads.delete(model.id);
+ modelManager.downloadProgress.delete(model.id);
+ modelManager.downloadLifecycleVersion += 1;
+ downloadCompleted = true;
+ }
+ return downloadCompleted && modelPath.endsWith(model.fileName);
+ };
+ t.after(() => {
+ modelManager.checkModelValid = originalCheckModelValid;
+ modelManager.activeDownloads.clear();
+ modelManager.downloadProgress.clear();
+ });
+
+ const models = await modelManager.getAllModels();
+ const completedModel = models.find((candidate) => candidate.id === model.id);
+
+ assert.ok(
+ checkCount > modelRegistryData.localProviders.flatMap((provider) => provider.models).length
+ );
+ assert.equal(completedModel.isDownloaded, true);
+ assert.equal(completedModel.isDownloading, false);
+ assert.equal(completedModel.downloadProgress, 0);
+ assert.equal(completedModel.downloadedSize, 0);
+ assert.equal(completedModel.totalSize, 0);
+});
+
+test("downloadModel rejects a second local model while another model is active", async (t) => {
+ const tmpHome = await fs.mkdtemp(path.join(os.tmpdir(), "openwhispr-single-download-"));
+ electronHome = tmpHome;
+ t.after(() => fs.rm(tmpHome, { recursive: true, force: true }));
+
+ const modelManager = loadModelManager();
+ const [activeModel, requestedModel] = modelRegistryData.localProviders[0].models;
+
+ modelManager.activeDownloads.set(activeModel.id, true);
+ t.after(() => {
+ modelManager.activeDownloads.clear();
+ modelManager.downloadProgress.clear();
+ });
+
+ await assert.rejects(
+ modelManager.downloadModel(requestedModel.id),
+ (error) =>
+ error.code === "DOWNLOAD_IN_PROGRESS" &&
+ error.details.modelId === requestedModel.id &&
+ error.details.activeModelId === activeModel.id
+ );
+});
+
+test("cancelDownload keeps the local LLM guard until the request unwinds", async (t) => {
+ const tmpHome = await fs.mkdtemp(path.join(os.tmpdir(), "openwhispr-cancel-guard-"));
+ electronHome = tmpHome;
+ t.after(() => fs.rm(tmpHome, { recursive: true, force: true }));
+
+ const modelManager = loadModelManager();
+ const model = modelRegistryData.localProviders[0].models[0];
+ let aborted = false;
+
+ modelManager.activeDownloads.set(model.id, true);
+ modelManager.activeRequests.set(model.id, {
+ abort() {
+ aborted = true;
+ },
+ });
+ modelManager.downloadProgress.set(model.id, {
+ modelId: model.id,
+ progress: 42,
+ downloadedSize: 420,
+ totalSize: 1000,
+ });
+ t.after(() => {
+ modelManager.activeDownloads.clear();
+ modelManager.activeRequests.clear();
+ modelManager.downloadProgress.clear();
+ });
+
+ assert.equal(modelManager.cancelDownload(model.id), true);
+ assert.equal(aborted, true);
+ assert.equal(modelManager.activeDownloads.has(model.id), true);
+ assert.equal(modelManager.activeRequests.has(model.id), true);
+ assert.equal(modelManager.downloadProgress.has(model.id), true);
+});
diff --git a/test/helpers/transcriptionModelDownloadStatus.test.js b/test/helpers/transcriptionModelDownloadStatus.test.js
new file mode 100644
index 000000000..6fc276abc
--- /dev/null
+++ b/test/helpers/transcriptionModelDownloadStatus.test.js
@@ -0,0 +1,174 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs/promises");
+const Module = require("node:module");
+const os = require("node:os");
+const path = require("node:path");
+
+const ParakeetManager = require("../../src/helpers/parakeet");
+const WhisperManager = require("../../src/helpers/whisper");
+const modelRegistryData = require("../../src/models/modelRegistryData.json");
+const downloadUtils = require("../../src/helpers/downloadUtils");
+const whisperModulePath = require.resolve("../../src/helpers/whisper");
+
+function activeDownload(model, overrides = {}) {
+ return {
+ abort() {},
+ model,
+ phase: "progress",
+ percentage: 42,
+ downloadedBytes: 420,
+ totalBytes: 1000,
+ ...overrides,
+ };
+}
+
+test("listParakeetModels surfaces active installation state", async () => {
+ const manager = new ParakeetManager();
+ const model = Object.keys(modelRegistryData.parakeetModels)[0];
+ manager.serverManager.isModelDownloaded = () => false;
+ manager.currentDownloadProcess = activeDownload(model, {
+ phase: "installing",
+ percentage: 100,
+ });
+
+ const result = await manager.listParakeetModels();
+ const status = result.models.find((candidate) => candidate.model === model);
+
+ assert.equal(status.downloaded, false);
+ assert.equal(status.isDownloading, true);
+ assert.equal(status.isInstalling, true);
+ assert.equal(status.downloadProgress, 100);
+ assert.equal(status.downloadedBytes, 420);
+ assert.equal(status.totalBytes, 1000);
+});
+
+test("Parakeet rejects a duplicate download without replacing the active request", async () => {
+ const manager = new ParakeetManager();
+ const model = Object.keys(modelRegistryData.parakeetModels)[0];
+ const active = activeDownload(model);
+ manager.serverManager.isModelDownloaded = () => false;
+ manager.currentDownloadProcess = active;
+
+ await assert.rejects(
+ manager.downloadParakeetModel(model),
+ (error) => error.code === "DOWNLOAD_IN_PROGRESS" && error.details.activeModel === model
+ );
+ assert.equal(manager.currentDownloadProcess, active);
+});
+
+test("listWhisperModels surfaces active download state", async (t) => {
+ const modelsDir = await fs.mkdtemp(path.join(os.tmpdir(), "openwhispr-whisper-status-"));
+ t.after(() => fs.rm(modelsDir, { recursive: true, force: true }));
+
+ const manager = new WhisperManager();
+ const model = Object.keys(modelRegistryData.whisperModels)[0];
+ manager.getModelsDir = () => modelsDir;
+ manager.currentDownloadProcess = activeDownload(model);
+
+ const result = await manager.listWhisperModels();
+ const status = result.models.find((candidate) => candidate.model === model);
+
+ assert.equal(status.downloaded, false);
+ assert.equal(status.isDownloading, true);
+ assert.equal(status.downloadProgress, 42);
+ assert.equal(status.downloadedBytes, 420);
+ assert.equal(status.totalBytes, 1000);
+});
+
+test("Whisper rejects a duplicate download without replacing the active request", async (t) => {
+ const modelsDir = await fs.mkdtemp(path.join(os.tmpdir(), "openwhispr-whisper-guard-"));
+ t.after(() => fs.rm(modelsDir, { recursive: true, force: true }));
+
+ const manager = new WhisperManager();
+ const model = Object.keys(modelRegistryData.whisperModels)[0];
+ const active = activeDownload(model);
+ manager.getModelsDir = () => modelsDir;
+ manager.currentDownloadProcess = active;
+
+ await assert.rejects(
+ manager.downloadWhisperModel(model),
+ (error) => error.code === "DOWNLOAD_IN_PROGRESS" && error.details.activeModel === model
+ );
+ assert.equal(manager.currentDownloadProcess, active);
+});
+
+test("Whisper emits a complete event after validating the downloaded model", async (t) => {
+ const modelsDir = await fs.mkdtemp(path.join(os.tmpdir(), "openwhispr-whisper-complete-"));
+ t.after(() => fs.rm(modelsDir, { recursive: true, force: true }));
+
+ const originalLoad = Module._load;
+ delete require.cache[whisperModulePath];
+ Module._load = function loadWithDownloadMock(request, parent, isMain) {
+ if (request === "./downloadUtils" && parent?.filename === whisperModulePath) {
+ return {
+ ...downloadUtils,
+ checkDiskSpace: async () => ({ ok: true, availableBytes: Infinity }),
+ downloadFile: async (_url, destination, options) => {
+ await fs.writeFile(destination, Buffer.alloc(16));
+ options.onProgress?.(16, 16);
+ return destination;
+ },
+ validateFileSize: async () => 16,
+ };
+ }
+ return originalLoad.call(this, request, parent, isMain);
+ };
+
+ let TestWhisperManager;
+ try {
+ TestWhisperManager = require("../../src/helpers/whisper");
+ } finally {
+ Module._load = originalLoad;
+ delete require.cache[whisperModulePath];
+ }
+
+ const manager = new TestWhisperManager();
+ const model = Object.keys(modelRegistryData.whisperModels)[0];
+ const events = [];
+ manager.getModelsDir = () => modelsDir;
+
+ await manager.downloadWhisperModel(model, (event) => events.push(event));
+
+ assert.equal(events.at(-1)?.type, "complete");
+ assert.equal(events.at(-1)?.model, model);
+ assert.equal(events.at(-1)?.percentage, 100);
+});
+
+test("cancellation keeps the download guard until the active request unwinds", async () => {
+ const manager = new ParakeetManager();
+ const model = Object.keys(modelRegistryData.parakeetModels)[0];
+ let aborted = false;
+ const active = activeDownload(model, {
+ abort() {
+ aborted = true;
+ },
+ });
+ manager.currentDownloadProcess = active;
+
+ const result = await manager.cancelDownload();
+
+ assert.equal(result.success, true);
+ assert.equal(aborted, true);
+ assert.equal(manager.currentDownloadProcess, active);
+});
+
+test("Parakeet refuses cancellation after installation starts", async () => {
+ const manager = new ParakeetManager();
+ const model = Object.keys(modelRegistryData.parakeetModels)[0];
+ let aborted = false;
+ const active = activeDownload(model, {
+ phase: "installing",
+ abort() {
+ aborted = true;
+ },
+ });
+ manager.currentDownloadProcess = active;
+
+ const result = await manager.cancelDownload();
+
+ assert.equal(result.success, false);
+ assert.equal(result.code, "INSTALLATION_IN_PROGRESS");
+ assert.equal(aborted, false);
+ assert.equal(manager.currentDownloadProcess, active);
+});