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 local download progress in main process and allow parallel downloads (#1267)

Idris Gadi9c5c28de65bf
diff --git a/preload.js b/preload.js
index 823532268..95157ad1e 100644
--- a/preload.js
+++ b/preload.js
@@ -562,6 +562,7 @@ contextBridge.exposeInMainWorld("electronAPI", {
// Model management functions
modelGetAll: () => ipcRenderer.invoke("model-get-all"),
+ modelGetActiveDownloads: () => ipcRenderer.invoke("model-get-active-downloads"),
modelCheck: (modelId) => ipcRenderer.invoke("model-check", modelId),
modelDownload: (modelId) => ipcRenderer.invoke("model-download", modelId),
modelDelete: (modelId) => ipcRenderer.invoke("model-delete", modelId),
diff --git a/src/components/LocalModelPicker.tsx b/src/components/LocalModelPicker.tsx
index 05f8d9f64..85bec9d98 100644
--- a/src/components/LocalModelPicker.tsx
+++ b/src/components/LocalModelPicker.tsx
@@ -130,35 +130,37 @@ export default function LocalModelPicker({
}, [loadDownloadedModels, onDownloadComplete]);
const {
- downloadingModel,
- downloadProgress,
+ downloads,
downloadModel,
deleteModel,
isDownloadingModel,
cancelDownload,
- isCancelling,
- isInstalling,
+ isCancellingModel,
} = useModelDownload({
modelType,
onDownloadComplete: handleDownloadComplete,
onModelsCleared: loadDownloadedModels,
});
+ const allModels = useMemo(() => providers.flatMap((provider) => provider.models), [providers]);
const selectionStateRef = useRef({ selectedModel, downloadedModels, knownModelIds });
+
useEffect(() => {
selectionStateRef.current = { selectedModel, downloadedModels, knownModelIds };
}, [selectedModel, downloadedModels, knownModelIds]);
const handleDownload = useCallback(
(modelId: string) => {
- // Bootstrap auto-select, decided against current state when the download
- // finishes so a model picked while it ran is never stolen.
+ const selectedWhenStarted = selectionStateRef.current.selectedModel;
+
downloadModel(modelId, (downloadedId) => {
const {
selectedModel: current,
downloadedModels: downloaded,
knownModelIds: known,
} = selectionStateRef.current;
+ if (current !== selectedWhenStarted) return;
+
const selectionGone = known.has(current) && !downloaded.has(current);
if (!current || selectionGone) {
onModelSelect(downloadedId);
@@ -182,20 +184,7 @@ export default function LocalModelPicker({
const currentProvider = providers.find((p) => p.id === selectedProvider);
const models = useMemo(() => currentProvider?.models || [], [currentProvider?.models]);
-
- const progressDisplay = useMemo(() => {
- if (!downloadingModel) return null;
-
- const modelName = models.find((m) => m.id === downloadingModel)?.name || downloadingModel;
-
- return (
- <DownloadProgressBar
- modelName={modelName}
- progress={downloadProgress}
- isInstalling={isInstalling}
- />
- );
- }, [downloadingModel, downloadProgress, isInstalling, models]);
+ const activeModels = allModels.filter((model) => downloads[model.id]);
return (
<div className={className}>
@@ -207,7 +196,25 @@ export default function LocalModelPicker({
wrap
/>
- {progressDisplay}
+ {activeModels.length > 0 && (
+ <div className="space-y-2">
+ {activeModels.map((model) => {
+ const status = downloads[model.id];
+ return (
+ <DownloadProgressBar
+ key={model.id}
+ modelName={model.name}
+ progress={{
+ percentage: status.progress,
+ downloadedBytes: status.downloadedBytes,
+ totalBytes: status.totalBytes,
+ }}
+ isInstalling={status.phase === "installing"}
+ />
+ );
+ })}
+ </div>
+ )}
<div className="mt-2">
<h5 className={`${styles.header} mb-2`}>{t("common.availableModels")}</h5>
@@ -223,14 +230,13 @@ export default function LocalModelPicker({
recommended: model.recommended,
isDownloaded: downloadedModels.has(model.id) || model.isDownloaded || model.downloaded,
isDownloading: isDownloadingModel(model.id),
+ isCancelling: isCancellingModel(model.id),
}))}
selectedModel={selectedModel}
onModelSelect={onModelSelect}
onDownload={handleDownload}
onDelete={handleDelete}
onCancelDownload={cancelDownload}
- isCancelling={isCancelling}
- isInstalling={isInstalling}
colorScheme={colorScheme}
/>
</div>
diff --git a/src/components/LocalWhisperPicker.tsx b/src/components/LocalWhisperPicker.tsx
index bd9b002ff..81387d2d6 100644
--- a/src/components/LocalWhisperPicker.tsx
+++ b/src/components/LocalWhisperPicker.tsx
@@ -94,13 +94,12 @@ export default function LocalWhisperPicker({
}, [validateAndSelectModel]);
const {
- downloadingModel,
- downloadProgress,
+ downloads,
downloadModel,
deleteModel,
isDownloadingModel,
cancelDownload,
- isCancelling,
+ isCancellingModel,
} = useModelDownload({
modelType: "whisper",
onDownloadComplete: () => {
@@ -112,6 +111,9 @@ export default function LocalWhisperPicker({
onModelsCleared: loadModels,
});
+ const downloadingModel = Object.keys(downloads)[0] || null;
+ const activeDownload = downloadingModel ? downloads[downloadingModel] : null;
+
useEffect(() => {
downloadingModelRef.current = downloadingModel;
}, [downloadingModel]);
@@ -149,10 +151,14 @@ export default function LocalWhisperPicker({
return (
<DownloadProgressBar
modelName={modelInfo?.name || downloadingModel}
- progress={downloadProgress}
+ progress={{
+ percentage: activeDownload?.progress || 0,
+ downloadedBytes: activeDownload?.downloadedBytes || 0,
+ totalBytes: activeDownload?.totalBytes || 0,
+ }}
/>
);
- }, [downloadingModel, downloadProgress]);
+ }, [activeDownload, downloadingModel]);
const whisperIcon = getProviderIcon("whisper");
@@ -181,6 +187,7 @@ export default function LocalWhisperPicker({
recommended: info.recommended,
isDownloaded: model.downloaded,
isDownloading: isDownloadingModel(modelId),
+ isCancelling: isCancellingModel(modelId),
};
})}
selectedModel={selectedModel}
@@ -188,7 +195,6 @@ export default function LocalWhisperPicker({
onDownload={handleDownload}
onDelete={handleDelete}
onCancelDownload={cancelDownload}
- isCancelling={isCancelling}
colorScheme={colorScheme}
/>
</div>
diff --git a/src/components/TranscriptionModelPicker.tsx b/src/components/TranscriptionModelPicker.tsx
index 6473d02cd..226f0f915 100644
--- a/src/components/TranscriptionModelPicker.tsx
+++ b/src/components/TranscriptionModelPicker.tsx
@@ -786,28 +786,24 @@ export default function TranscriptionModelPicker({
};
const {
- downloadingModel,
- downloadProgress,
+ downloads: whisperDownloads,
downloadModel,
deleteModel,
isDownloadingModel,
- isInstalling,
cancelDownload,
- isCancelling,
+ isCancellingModel,
} = useModelDownload({
modelType: "whisper",
onDownloadComplete: loadLocalModels,
});
const {
- downloadingModel: downloadingParakeetModel,
- downloadProgress: parakeetDownloadProgress,
+ downloads: parakeetDownloads,
downloadModel: downloadParakeetModel,
deleteModel: deleteParakeetModel,
isDownloadingModel: isDownloadingParakeetModel,
- isInstalling: isInstallingParakeet,
cancelDownload: cancelParakeetDownload,
- isCancelling: isCancellingParakeet,
+ isCancellingModel: isCancellingParakeetModel,
} = useModelDownload({
modelType: "parakeet",
onDownloadComplete: loadParakeetModels,
@@ -971,39 +967,35 @@ export default function TranscriptionModelPicker({
const progressDisplay = useMemo(() => {
if (!effectiveLocal) return null;
- if (downloadingModel && internalLocalProvider === "whisper") {
- const modelInfo = WHISPER_MODEL_INFO[downloadingModel];
- return (
- <DownloadProgressBar
- modelName={modelInfo?.name || downloadingModel}
- progress={downloadProgress}
- isInstalling={isInstalling}
- />
- );
- }
-
- if (downloadingParakeetModel && isSherpaLocalProvider(internalLocalProvider)) {
- const modelInfo = PARAKEET_MODEL_INFO[downloadingParakeetModel];
- return (
- <DownloadProgressBar
- modelName={modelInfo?.name || downloadingParakeetModel}
- progress={parakeetDownloadProgress}
- isInstalling={isInstallingParakeet}
- />
- );
- }
+ const activeDownloads = [
+ ...Object.values(whisperDownloads),
+ ...Object.values(parakeetDownloads),
+ ];
+ if (activeDownloads.length === 0) return null;
- return null;
- }, [
- downloadingModel,
- downloadProgress,
- isInstalling,
- downloadingParakeetModel,
- parakeetDownloadProgress,
- isInstallingParakeet,
- effectiveLocal,
- internalLocalProvider,
- ]);
+ return (
+ <div className="space-y-2">
+ {activeDownloads.map((status) => {
+ const modelInfo =
+ status.modelType === "whisper"
+ ? WHISPER_MODEL_INFO[status.modelId]
+ : PARAKEET_MODEL_INFO[status.modelId];
+ return (
+ <DownloadProgressBar
+ key={`${status.modelType}:${status.modelId}`}
+ modelName={modelInfo?.name || status.modelId}
+ progress={{
+ percentage: status.progress,
+ downloadedBytes: status.downloadedBytes,
+ totalBytes: status.totalBytes,
+ }}
+ isInstalling={status.phase === "installing"}
+ />
+ );
+ })}
+ </div>
+ );
+ }, [effectiveLocal, whisperDownloads, parakeetDownloads]);
const renderLocalModels = () => {
const modelsToRender =
@@ -1037,8 +1029,8 @@ export default function TranscriptionModelPicker({
isSelected={modelId === selectedLocalModel}
isDownloaded={model.downloaded ?? false}
isDownloading={isDownloadingModel(modelId)}
- isCancelling={isCancelling}
- isInstalling={isInstalling}
+ isCancelling={isCancellingModel(modelId)}
+ isInstalling={whisperDownloads[modelId]?.phase === "installing"}
recommended={info.recommended}
provider="whisper"
onSelect={() => handleWhisperModelSelect(modelId)}
@@ -1051,7 +1043,7 @@ export default function TranscriptionModelPicker({
handleWhisperModelSelect(downloadedId);
})
}
- onCancel={cancelDownload}
+ onCancel={() => cancelDownload(modelId)}
styles={styles}
/>
);
@@ -1115,8 +1107,8 @@ export default function TranscriptionModelPicker({
isSelected={modelId === selectedLocalModel}
isDownloaded={model.downloaded ?? false}
isDownloading={isDownloadingParakeetModel(modelId)}
- isCancelling={isCancellingParakeet}
- isInstalling={isInstallingParakeet}
+ isCancelling={isCancellingParakeetModel(modelId)}
+ isInstalling={parakeetDownloads[modelId]?.phase === "installing"}
recommended={info.recommended}
provider={provider}
onSelect={() => handleParakeetModelSelect(modelId)}
@@ -1129,7 +1121,7 @@ export default function TranscriptionModelPicker({
handleParakeetModelSelect(downloadedId);
})
}
- onCancel={cancelParakeetDownload}
+ onCancel={() => cancelParakeetDownload(modelId)}
styles={styles}
/>
);
diff --git a/src/components/onboarding/ProviderSetupStep.tsx b/src/components/onboarding/ProviderSetupStep.tsx
index 4327521b9..97b4ec922 100644
--- a/src/components/onboarding/ProviderSetupStep.tsx
+++ b/src/components/onboarding/ProviderSetupStep.tsx
@@ -25,7 +25,12 @@ import {
} from "../../models/ModelRegistry";
import { pickDefaultModelId } from "../../models/providerDefaultModel";
import type { OnboardingStepId } from "./flow";
-import { forgetPendingLocalModel, rememberPendingLocalModel } from "./pendingLocalModels";
+import {
+ forgetPendingLocalModel,
+ isPendingLocalModel,
+ readPendingLocalModels,
+ rememberPendingLocalModel,
+} from "./pendingLocalModels";
import { isLocalStageDownloadActive } from "./localDownloadState";
export function SetupStageStepper({ stepId }: { stepId: OnboardingStepId }) {
@@ -112,10 +117,12 @@ function StepPrimaryAction({
function StepSecondaryAction({
onClick,
+ disabled = false,
className = "",
children,
}: {
onClick: () => void;
+ disabled?: boolean;
className?: string;
children: ReactNode;
}) {
@@ -124,6 +131,7 @@ function StepSecondaryAction({
type="button"
variant="outline-flat"
onClick={onClick}
+ disabled={disabled}
className={`h-9 rounded-[38px]! border! border-[var(--onboarding-control-border)]! bg-transparent! px-5 text-sm font-medium leading-[1.4] text-[var(--onboarding-text-primary)] shadow-none! hover:bg-[var(--onboarding-surface-hover)]! ${className}`}
>
{children}
@@ -701,7 +709,8 @@ export function LocalModelSetupStep({
}, [onReadinessChange, selectedReady]);
const selectInstalledModel = useCallback(
- (modelId: string) => {
+ (modelId: string): void => {
+ const kind = assistant ? "assistant" : "dictation";
setSelectedModel(modelId);
if (assistant) {
store.setChatAgentMode("local");
@@ -715,23 +724,49 @@ export function LocalModelSetupStep({
store.setWhisperModel(modelId);
}
if (localStorage.getItem("localSetupPending") !== "true") {
- forgetPendingLocalModel(assistant ? "assistant" : "dictation", modelId);
+ forgetPendingLocalModel(kind, modelId);
}
},
[assistant, selectedProvider, store]
);
- const downloadModel = (modelId: string) => {
- // downloadModel refuses (toast only) while another download of this kind
- // runs; recording the pending selection for a refused download leaves a
- // stale entry that a much later download would silently activate.
- if (!activeDownload.isDownloading) {
- rememberPendingLocalModel(assistant ? "assistant" : "dictation", {
+ const chooseInstalledModel = (modelId: string): void => {
+ forgetPendingLocalModel(assistant ? "assistant" : "dictation");
+ selectInstalledModel(modelId);
+ };
+
+ const downloadModel = (modelId: string): void => {
+ const kind = assistant ? "assistant" : "dictation";
+ // LLMs can download concurrently; a refused duplicate or native transfer
+ // must not replace the selection waiting for an accepted download.
+ if (
+ !activeDownload.isDownloadingModel(modelId) &&
+ (assistant || !activeDownload.isDownloading)
+ ) {
+ rememberPendingLocalModel(kind, {
provider: selectedProvider,
modelId,
});
}
- void activeDownload.downloadModel(modelId, selectInstalledModel);
+ void activeDownload.downloadModel(modelId, (downloadedId): void => {
+ if (isPendingLocalModel(kind, { provider: selectedProvider, modelId: downloadedId })) {
+ selectInstalledModel(downloadedId);
+ return;
+ }
+ if (readPendingLocalModels()[kind]) return;
+
+ // The tray can activate and consume this selection before the initiating
+ // IPC resolves. Reflect that activation without replacing a newer choice.
+ const saved = useSettingsStore.getState();
+ const alreadySelected = assistant
+ ? saved.chatAgentMode === "local" &&
+ saved.chatAgentProvider === selectedProvider &&
+ saved.chatAgentModel === downloadedId
+ : saved.localTranscriptionProvider === selectedProvider &&
+ (selectedProvider === "nvidia" ? saved.parakeetModel : saved.whisperModel) ===
+ downloadedId;
+ if (alreadySelected) setSelectedModel(downloadedId);
+ });
};
const chooseProvider = (providerId: string) => {
@@ -745,18 +780,24 @@ export function LocalModelSetupStep({
parakeet: parakeetDownload.isDownloading,
llm: llmDownload.isDownloading,
});
- // A running download is enough to move on: it lives in the main process, the
- // model is already remembered as pending (downloadModel above), and
- // BackgroundModelDownloadTray keeps the progress on screen and applies the
- // selection when it lands. Waiting for 100% would pin the user to this step
- // for a multi-gigabyte download.
- const canProceed = selectedReady || anyDownloadActive;
+ const pendingSelection = readPendingLocalModels()[assistant ? "assistant" : "dictation"];
+ const pendingDownload = assistant
+ ? llmDownload
+ : pendingSelection?.provider === "nvidia"
+ ? parakeetDownload
+ : whisperDownload;
+ // Only the pending selection will activate in the background. Other transfers
+ // can outlive it when the user cancels the newest of several downloads.
+ const hasPendingDownload = Boolean(
+ pendingSelection && pendingDownload.isDownloadingModel(pendingSelection.modelId)
+ );
+ const canProceed = selectedReady || hasPendingDownload;
const proceed = () => {
// Leaving mid-download is the same situation as "download in background":
// this step unmounts, so the tray is what finishes the job, and it only
// applies the pending selection while localSetupPending is set.
- if (anyDownloadActive && !selectedReady) {
+ if (hasPendingDownload && !selectedReady) {
localStorage.setItem("localSetupPending", "true");
}
onProceed();
@@ -810,9 +851,10 @@ export function LocalModelSetupStep({
<div className="onboarding-scroll-hidden mt-3 h-56 overflow-y-auto rounded-2xl border border-[var(--onboarding-control-border)] bg-[var(--onboarding-surface-secondary)] px-3">
{models.map((model) => {
const isDownloaded = downloadedModels.has(model.id);
- const isDownloading = activeDownload.isDownloadingModel(model.id);
+ const download = activeDownload.downloads[model.id];
+ const isDownloading = Boolean(download);
const isSelected = selectedModel === model.id && isDownloaded;
- const percentage = Math.round(activeDownload.downloadProgress.percentage);
+ const percentage = Math.round(download?.progress ?? 0);
return (
<div
key={model.id}
@@ -828,7 +870,7 @@ export function LocalModelSetupStep({
<button
type="button"
disabled={!isDownloaded}
- onClick={() => selectInstalledModel(model.id)}
+ onClick={() => chooseInstalledModel(model.id)}
className="min-w-0 flex-1 text-left disabled:cursor-default"
>
<span className="block truncate text-sm font-medium text-[var(--onboarding-text-primary)]">
@@ -856,7 +898,7 @@ export function LocalModelSetupStep({
/>
<span className="relative">{percentage}%</span>
<span className="relative whitespace-nowrap">
- {activeDownload.isInstalling
+ {download?.phase === "installing"
? t("onboarding.rehaul.local.installing")
: t("onboarding.rehaul.local.downloadingShort")}
</span>
@@ -874,7 +916,7 @@ export function LocalModelSetupStep({
// primary in onboarding does, and Download stays neutral below it.
<Button
type="button"
- onClick={() => selectInstalledModel(model.id)}
+ onClick={() => chooseInstalledModel(model.id)}
className="-mr-2 h-7 gap-1.5 rounded-full border-0! bg-[var(--onboarding-accent)] px-2.5 text-xs font-normal text-[var(--onboarding-accent-foreground)] shadow-none! hover:bg-[var(--onboarding-accent-hover)] hover:shadow-none!"
>
{t("onboarding.rehaul.local.use")}
@@ -896,7 +938,9 @@ export function LocalModelSetupStep({
<div className={`mt-4 grid gap-2 ${anyDownloadActive ? "grid-cols-2" : "grid-cols-1"}`}>
{anyDownloadActive && (
- <StepSecondaryAction onClick={onSkip}>{t("common.skip")}</StepSecondaryAction>
+ <StepSecondaryAction onClick={onSkip} disabled={!canProceed}>
+ {t("common.skip")}
+ </StepSecondaryAction>
)}
<StepPrimaryAction onClick={proceed} disabled={!canProceed}>
{t("onboarding.rehaul.provider.proceed")}
diff --git a/src/components/onboarding/RequiredModelDownloadStep.tsx b/src/components/onboarding/RequiredModelDownloadStep.tsx
index 148e95d9e..b65c1b86d 100644
--- a/src/components/onboarding/RequiredModelDownloadStep.tsx
+++ b/src/components/onboarding/RequiredModelDownloadStep.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef } from "react";
import { AlertCircle, Check } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "../ui/button";
@@ -40,8 +40,13 @@ export function RequiredModelDownloadStep({
const whisperDownload = useModelDownload({ modelType: "whisper", onDownloadComplete: refresh });
const parakeetDownload = useModelDownload({ modelType: "parakeet", onDownloadComplete: refresh });
- const [failedModels, setFailedModels] = useState<Record<string, string>>({});
- const lastStartedRef = useRef<{ family: ModelFamily; id: string } | null>(null);
+ const failedModels = useMemo(
+ (): Record<string, string> => ({
+ ...whisperDownload.downloadErrors,
+ ...parakeetDownload.downloadErrors,
+ }),
+ [whisperDownload.downloadErrors, parakeetDownload.downloadErrors]
+ );
const startedAnyRef = useRef(false);
const autoAdvancedRef = useRef(false);
@@ -52,30 +57,10 @@ export function RequiredModelDownloadStep({
const missingSet = useMemo(() => new Set(missing), [missing]);
const anyDownloadActive = whisperDownload.isDownloading || parakeetDownload.isDownloading;
- // useModelDownload clears its downloading state on error, so the failing
- // model id has to be remembered here to pin the error to its row.
- useEffect(() => {
- const last = lastStartedRef.current;
- if (!last) return;
- const error =
- last.family === "whisper" ? whisperDownload.downloadError : parakeetDownload.downloadError;
- if (!error) return;
- setFailedModels((current) =>
- current[last.id] === error ? current : { ...current, [last.id]: error }
- );
- }, [whisperDownload.downloadError, parakeetDownload.downloadError]);
-
const startDownload = useCallback(
- (modelId: string) => {
+ (modelId: string): void => {
startedAnyRef.current = true;
- setFailedModels((current) => {
- if (!(modelId in current)) return current;
- const next = { ...current };
- delete next[modelId];
- return next;
- });
const family = familyOf(modelId);
- lastStartedRef.current = { family, id: modelId };
const download = family === "parakeet" ? parakeetDownload : whisperDownload;
void download.downloadModel(modelId);
},
@@ -102,7 +87,7 @@ export function RequiredModelDownloadStep({
}
}, [loading, missing, onProceed]);
- const hasFailures = Object.keys(failedModels).length > 0;
+ const hasFailures = required.some((modelId): boolean => !!failedModels[modelId]);
return (
<section className={`mt-5 ${SETUP_CARD_CLASS}`}>
diff --git a/src/components/onboarding/pendingLocalModels.ts b/src/components/onboarding/pendingLocalModels.ts
index 9797e4c01..a73befd70 100644
--- a/src/components/onboarding/pendingLocalModels.ts
+++ b/src/components/onboarding/pendingLocalModels.ts
@@ -51,6 +51,14 @@ export function rememberPendingLocalModel(
writePendingLocalModels({ ...readPendingLocalModels(), [kind]: selection });
}
+export function isPendingLocalModel(
+ kind: PendingLocalModelKind,
+ selection: PendingLocalModelSelection
+) {
+ const pending = readPendingLocalModels()[kind];
+ return pending?.provider === selection.provider && pending.modelId === selection.modelId;
+}
+
export function consumePendingLocalModel(
kind: PendingLocalModelKind,
modelId: string
diff --git a/src/components/ui/ModelCardList.tsx b/src/components/ui/ModelCardList.tsx
index 2f1abb3b2..e14641a63 100644
--- a/src/components/ui/ModelCardList.tsx
+++ b/src/components/ui/ModelCardList.tsx
@@ -18,6 +18,7 @@ export interface ModelCardOption {
// Local model properties (optional)
isDownloaded?: boolean;
isDownloading?: boolean;
+ isCancelling?: boolean;
recommended?: boolean;
}
@@ -53,9 +54,7 @@ interface ModelCardProps {
// Local model actions (optional - when provided, enables local model UI)
onDownload?: (modelId: string) => void;
onDelete?: (modelId: string) => void;
- onCancelDownload?: () => void;
- isCancelling?: boolean;
- isInstalling?: boolean;
+ onCancelDownload?: (modelId: string) => void;
}
export function ModelCard({
@@ -67,14 +66,13 @@ export function ModelCard({
onDownload,
onDelete,
onCancelDownload,
- isCancelling = false,
- isInstalling = false,
}: ModelCardProps) {
const { t } = useTranslation();
const styles = COLOR_CONFIG[colorScheme];
const isLocalMode = Boolean(onDownload);
const isDownloaded = model.isDownloaded;
const isDownloading = model.isDownloading;
+ const modelIsCancelling = model.isCancelling ?? false;
const specHref = model.specUrl ? withUtm(model.specUrl, "model_spec") : undefined;
const handleCardClick = () => {
@@ -194,15 +192,15 @@ export function ModelCard({
<Button
onClick={(e) => {
e.stopPropagation();
- onCancelDownload?.();
+ onCancelDownload?.(model.value);
}}
- disabled={isCancelling || isInstalling}
+ disabled={modelIsCancelling}
size="sm"
variant="outline"
className="h-6 px-2.5 text-xs text-destructive border-destructive/25 hover:bg-destructive/8"
>
<X size={11} className="mr-0.5" />
- {isCancelling ? "..." : t("common.cancel")}
+ {modelIsCancelling ? "..." : t("common.cancel")}
</Button>
) : (
<Button
@@ -236,9 +234,7 @@ interface ModelCardListProps {
// Local model actions (optional - when provided, enables local model UI)
onDownload?: (modelId: string) => void;
onDelete?: (modelId: string) => void;
- onCancelDownload?: () => void;
- isCancelling?: boolean;
- isInstalling?: boolean;
+ onCancelDownload?: (modelId: string) => void;
}
export default function ModelCardList({
@@ -251,8 +247,6 @@ export default function ModelCardList({
onDownload,
onDelete,
onCancelDownload,
- isCancelling = false,
- isInstalling = false,
}: ModelCardListProps) {
const { t } = useTranslation();
@@ -273,8 +267,6 @@ export default function ModelCardList({
onDownload={onDownload}
onDelete={onDelete}
onCancelDownload={onCancelDownload}
- isCancelling={isCancelling}
- isInstalling={isInstalling}
/>
))}
</div>
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 379646526..fc90fc059 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -71,6 +71,7 @@ const { getTinfoilChatModels } = require("./tinfoilCatalog");
const { transcribeWithTinfoil } = require("./tinfoilTranscription");
const { transcribeWithGemini } = require("./geminiTranscription");
const AudioStorageManager = require("./audioStorage");
+const LocalModelDownloadStatus = require("./localModelDownloadStatus");
const AgentStreamRequestRegistry = require("./agentStreamRequestRegistry");
const createMeetingTranscriptionLifecycle = require("./meetingTranscriptionLifecycle");
const { registerMeetingAutoEndLifecycleHandlers } = require("./meetingAutoEndLifecycle");
@@ -621,6 +622,7 @@ class IPCHandlers {
this._activeRecordingPipeline = null;
this._onboardingDemoSession = null;
this.audioStorageManager = new AudioStorageManager();
+ this.localModelDownloadStatus = new LocalModelDownloadStatus();
this._retentionCleanupInterval = null;
this._retentionSettings = { ...DEFAULT_RETENTION_SETTINGS }; // Synced from renderer
this._retentionSettingsSynced = false;
@@ -701,6 +703,26 @@ class IPCHandlers {
};
}
+ _updateNativeModelDownloadStatus(modelType, modelId, progressData) {
+ if (progressData.type === "complete") {
+ return this.localModelDownloadStatus.finish(modelType, modelId);
+ }
+
+ if (progressData.type === "installing") {
+ return this.localModelDownloadStatus.update(modelType, modelId, {
+ phase: "installing",
+ progress: progressData.percentage || 100,
+ });
+ }
+
+ return this.localModelDownloadStatus.update(modelType, modelId, {
+ phase: "downloading",
+ progress: progressData.percentage || 0,
+ downloadedBytes: progressData.downloaded_bytes || 0,
+ totalBytes: progressData.total_bytes || 0,
+ });
+ }
+
_setWhisperVadSettings(update = {}) {
const ALLOWED_KEYS = new Set([
"dictationSileroEnabled",
@@ -3039,24 +3061,39 @@ class IPCHandlers {
});
ipcMain.handle("download-whisper-model", async (event, modelName) => {
+ const hadActiveDownload = this.localModelDownloadStatus.has("whisper", modelName);
+ this.localModelDownloadStatus.start("whisper", modelName);
try {
const result = await this.whisperManager.downloadWhisperModel(modelName, (progressData) => {
- if (!event.sender.isDestroyed()) {
- event.sender.send("whisper-download-progress", progressData);
- }
+ const status = this._updateNativeModelDownloadStatus("whisper", modelName, progressData);
+ this.windowManager.sendToControlPanel("whisper-download-progress", {
+ ...progressData,
+ sequence: status?.sequence,
+ });
});
+ const status = this.localModelDownloadStatus.has("whisper", modelName)
+ ? this.localModelDownloadStatus.finish("whisper", modelName)
+ : null;
+ if (status) {
+ this.windowManager.sendToControlPanel("whisper-download-progress", {
+ type: "complete",
+ model: modelName,
+ percentage: 100,
+ sequence: status.sequence,
+ });
+ }
return result;
} catch (error) {
- if (
- error.code !== "DOWNLOAD_IN_PROGRESS" &&
- error.code !== "DOWNLOAD_CANCELLED" &&
- !event.sender.isDestroyed()
- ) {
- event.sender.send("whisper-download-progress", {
+ const status = hadActiveDownload
+ ? null
+ : this.localModelDownloadStatus.finish("whisper", modelName);
+ if (!hadActiveDownload && error.code !== "DOWNLOAD_IN_PROGRESS") {
+ this.windowManager.sendToControlPanel("whisper-download-progress", {
type: "error",
model: modelName,
error: error.message,
code: error.code || "DOWNLOAD_FAILED",
+ sequence: status?.sequence,
});
}
return {
@@ -3373,27 +3410,46 @@ class IPCHandlers {
});
ipcMain.handle("download-parakeet-model", async (event, modelName) => {
+ const hadActiveDownload = this.localModelDownloadStatus.has("parakeet", modelName);
+ this.localModelDownloadStatus.start("parakeet", modelName);
try {
const result = await this.parakeetManager.downloadParakeetModel(
modelName,
(progressData) => {
- if (!event.sender.isDestroyed()) {
- event.sender.send("parakeet-download-progress", progressData);
- }
+ const status = this._updateNativeModelDownloadStatus(
+ "parakeet",
+ modelName,
+ progressData
+ );
+ this.windowManager.sendToControlPanel("parakeet-download-progress", {
+ ...progressData,
+ sequence: status?.sequence,
+ });
}
);
+ const status = this.localModelDownloadStatus.has("parakeet", modelName)
+ ? this.localModelDownloadStatus.finish("parakeet", modelName)
+ : null;
+ if (status) {
+ this.windowManager.sendToControlPanel("parakeet-download-progress", {
+ type: "complete",
+ model: modelName,
+ percentage: 100,
+ sequence: status.sequence,
+ });
+ }
return result;
} catch (error) {
- if (
- error.code !== "DOWNLOAD_IN_PROGRESS" &&
- error.code !== "DOWNLOAD_CANCELLED" &&
- !event.sender.isDestroyed()
- ) {
- event.sender.send("parakeet-download-progress", {
+ const status = hadActiveDownload
+ ? null
+ : this.localModelDownloadStatus.finish("parakeet", modelName);
+ if (!hadActiveDownload && error.code !== "DOWNLOAD_IN_PROGRESS") {
+ this.windowManager.sendToControlPanel("parakeet-download-progress", {
type: "error",
model: modelName,
error: error.message,
code: error.code || "DOWNLOAD_FAILED",
+ sequence: status?.sequence,
});
}
return {
@@ -4083,56 +4139,67 @@ class IPCHandlers {
}
});
+ ipcMain.handle("model-get-active-downloads", async () => {
+ return this.localModelDownloadStatus.getActiveDownloads();
+ });
+
ipcMain.handle("model-check", async (_, modelId) => {
const modelManager = require("./modelManagerBridge").default;
return modelManager.isModelDownloaded(modelId);
});
ipcMain.handle("model-download", async (event, modelId) => {
- let lastProgress = {
- progress: 0,
- downloadedSize: 0,
- totalSize: 0,
- };
-
+ if (this.localModelDownloadStatus.has("llm", modelId)) {
+ return {
+ success: false,
+ error: "Model is already being downloaded",
+ code: "DOWNLOAD_IN_PROGRESS",
+ details: { modelId },
+ };
+ }
+ // Claim ownership before the manager's asynchronous filesystem preflight.
+ this.localModelDownloadStatus.start("llm", modelId);
try {
const modelManager = require("./modelManagerBridge").default;
const result = await modelManager.downloadModel(
modelId,
(progress, downloadedSize, totalSize) => {
- lastProgress = { progress, downloadedSize, totalSize };
- if (!event.sender.isDestroyed()) {
- event.sender.send("model-download-progress", {
- modelId,
- progress,
- downloadedSize,
- totalSize,
- });
- }
+ const status = this.localModelDownloadStatus.update("llm", modelId, {
+ phase: "downloading",
+ progress,
+ downloadedBytes: downloadedSize,
+ totalBytes: totalSize,
+ });
+ this.windowManager.sendToControlPanel("model-download-progress", {
+ modelId,
+ type: "progress",
+ progress,
+ downloadedSize,
+ totalSize,
+ sequence: status.sequence,
+ });
}
);
- if (!event.sender.isDestroyed()) {
- event.sender.send("model-download-progress", {
- type: "complete",
- modelId,
- progress: 100,
- downloadedSize: lastProgress.downloadedSize,
- totalSize: lastProgress.totalSize,
- });
- }
+ const status = this.localModelDownloadStatus.finish("llm", modelId);
+ this.windowManager.sendToControlPanel("model-download-progress", {
+ modelId,
+ type: "complete",
+ progress: 100,
+ downloadedSize: status?.downloadedBytes,
+ totalSize: status?.totalBytes,
+ sequence: status?.sequence,
+ });
return { success: true, path: result };
} catch (error) {
- if (
- error.code !== "DOWNLOAD_IN_PROGRESS" &&
- error.code !== "DOWNLOAD_CANCELLED" &&
- !event.sender.isDestroyed()
- ) {
- event.sender.send("model-download-progress", {
- type: "error",
+ const status = this.localModelDownloadStatus.finish("llm", modelId);
+ if (error.code !== "DOWNLOAD_IN_PROGRESS") {
+ this.windowManager.sendToControlPanel("model-download-progress", {
modelId,
+ type: "error",
error: error.message,
code: error.code,
details: error.details,
+ sequence: status?.sequence,
});
}
return {
diff --git a/src/helpers/localModelDownloadStatus.js b/src/helpers/localModelDownloadStatus.js
new file mode 100644
index 000000000..789270ce2
--- /dev/null
+++ b/src/helpers/localModelDownloadStatus.js
@@ -0,0 +1,59 @@
+class LocalModelDownloadStatus {
+ constructor() {
+ this.downloads = new Map();
+ this.sequence = 0;
+ }
+
+ _key(modelType, modelId) {
+ return `${modelType}:${modelId}`;
+ }
+
+ start(modelType, modelId) {
+ const key = this._key(modelType, modelId);
+ const existing = this.downloads.get(key);
+ if (existing) return existing;
+
+ const status = {
+ modelType,
+ modelId,
+ phase: "downloading",
+ progress: 0,
+ downloadedBytes: 0,
+ totalBytes: 0,
+ sequence: ++this.sequence,
+ };
+ this.downloads.set(key, status);
+ return status;
+ }
+
+ has(modelType, modelId) {
+ return this.downloads.has(this._key(modelType, modelId));
+ }
+
+ update(modelType, modelId, updates) {
+ const key = this._key(modelType, modelId);
+ const current = this.downloads.get(key) || this.start(modelType, modelId);
+ const status = {
+ ...current,
+ ...updates,
+ modelType,
+ modelId,
+ sequence: ++this.sequence,
+ };
+ this.downloads.set(key, status);
+ return status;
+ }
+
+ finish(modelType, modelId) {
+ const key = this._key(modelType, modelId);
+ const current = this.downloads.get(key);
+ this.downloads.delete(key);
+ return current ? { ...current, sequence: ++this.sequence } : null;
+ }
+
+ getActiveDownloads() {
+ return Array.from(this.downloads.values());
+ }
+}
+
+module.exports = LocalModelDownloadStatus;
diff --git a/src/helpers/modelManagerBridge.js b/src/helpers/modelManagerBridge.js
index 10cff00a2..c6eed6a4d 100644
--- a/src/helpers/modelManagerBridge.js
+++ b/src/helpers/modelManagerBridge.js
@@ -44,6 +44,7 @@ class ModelManager {
this.modelsDir = null;
this.downloadProgress = new Map();
this.activeDownloads = new Map();
+ this.downloadReservations = new Map();
this.activeRequests = new Map(); // Track HTTP requests for cancellation
this.downloadLifecycleVersion = 0;
this.serverManager = new LlamaServerManager();
@@ -211,6 +212,14 @@ class ModelManager {
return options;
}
+ getReservedDownloadBytes() {
+ let reserved = 0;
+ for (const [modelId, bytes] of this.downloadReservations) {
+ reserved += Math.max(0, bytes - (this.downloadProgress.get(modelId)?.downloadedSize || 0));
+ }
+ return reserved;
+ }
+
async downloadModel(modelId, onProgress) {
this.ensureInitialized();
const modelInfo = this.findModelById(modelId);
@@ -225,11 +234,9 @@ class ModelManager {
return modelPath;
}
- if (this.activeDownloads.size > 0) {
- const activeModelId = this.activeDownloads.keys().next().value;
- throw new ModelError("A model is already being downloaded", "DOWNLOAD_IN_PROGRESS", {
+ if (this.activeDownloads.has(modelId)) {
+ throw new ModelError("Model is already being downloaded", "DOWNLOAD_IN_PROGRESS", {
modelId,
- activeModelId,
});
}
@@ -248,13 +255,15 @@ class ModelManager {
requiredBytes += model.draftSizeBytes;
}
if (requiredBytes > 0) {
- const spaceCheck = await checkDiskSpace(this.modelsDir, requiredBytes * 1.2);
+ this.downloadReservations.set(modelId, requiredBytes * 1.2);
+ const reservedBytes = this.getReservedDownloadBytes();
+ const spaceCheck = await checkDiskSpace(this.modelsDir, reservedBytes);
if (!spaceCheck.ok) {
throw new ModelError(
- `Not enough disk space. Need ~${Math.round((requiredBytes * 1.2) / 1_000_000)}MB, ` +
+ `Not enough disk space. Need ~${Math.round(reservedBytes / 1_000_000)}MB, ` +
`only ${Math.round(spaceCheck.availableBytes / 1_000_000)}MB available.`,
"INSUFFICIENT_DISK_SPACE",
- { required: requiredBytes, available: spaceCheck.availableBytes }
+ { required: reservedBytes, available: spaceCheck.availableBytes }
);
}
}
@@ -324,6 +333,7 @@ class ModelManager {
}
} catch (draftError) {
await fsPromises.unlink(draftPath).catch(() => {});
+ if (draftError.isAbort) throw draftError;
debugLogger.warn("MTP drafter download failed, keeping model without it", {
modelId,
error: draftError.message,
@@ -353,6 +363,7 @@ class ModelManager {
}
this.activeRequests.delete(modelId);
this.downloadProgress.delete(modelId);
+ this.downloadReservations.delete(modelId);
}
}
diff --git a/src/hooks/useModelDownload.ts b/src/hooks/useModelDownload.ts
index ae85f424e..958ce6b05 100644
--- a/src/hooks/useModelDownload.ts
+++ b/src/hooks/useModelDownload.ts
@@ -5,10 +5,8 @@ import { useDialogs } from "./useDialogs";
import { useToast } from "../components/ui/useToast";
import type {
LocalLLMDownloadProgressEvent,
- LocalLLMModelStatus,
- ParakeetModelResult,
+ LocalModelDownloadStatus,
WhisperDownloadProgressData,
- WhisperModelResult,
} from "../types/electron";
import { clearMissingLocalModelSelections } from "../stores/settingsStore";
import "../types/electron";
@@ -44,75 +42,72 @@ interface UseModelDownloadOptions {
interface ModelDownloadTerminalEvent {
type: "complete" | "error";
- modelId: string;
error?: string;
code?: string;
+ sequence?: number;
}
-interface PendingModelDownloadRequest {
- modelId: string;
- terminalEvent?: ModelDownloadTerminalEvent;
-}
-
-type TranscriptionModelStatus = WhisperModelResult | ParakeetModelResult;
+type LLMDownloadProgressData = LocalLLMDownloadProgressEvent & { sequence?: number };
export function formatETA(seconds: number): string {
if (seconds < 60) return `${Math.round(seconds)}s`;
const minutes = Math.floor(seconds / 60);
- const remainingSeconds = Math.round(seconds % 60);
- return `${minutes}m ${remainingSeconds}s`;
+ return `${minutes}m ${Math.round(seconds % 60)}s`;
}
function getDownloadErrorMessage(t: TFunction, error: string, code?: string): string {
- if (code === "EXTRACTION_FAILED" || error.includes("installation failed"))
+ if (code === "EXTRACTION_FAILED" || error.includes("installation failed")) {
return t("hooks.modelDownload.errors.extractionFailed");
- if (code === "TLS_ERROR" || error.includes("certificate") || error.includes("issuer"))
+ }
+ if (code === "TLS_ERROR" || error.includes("certificate") || error.includes("issuer")) {
return t("hooks.modelDownload.errors.tlsError");
- if (code === "ETIMEDOUT" || error.includes("timeout") || error.includes("stalled"))
+ }
+ if (code === "ETIMEDOUT" || error.includes("timeout") || error.includes("stalled")) {
return t("hooks.modelDownload.errors.timeout");
- if (code === "ENOTFOUND" || error.includes("ENOTFOUND"))
+ }
+ if (code === "ENOTFOUND" || error.includes("ENOTFOUND")) {
return t("hooks.modelDownload.errors.notFound");
+ }
if (error.includes("disk space")) return error;
- if (error.includes("corrupted") || error.includes("incomplete") || error.includes("too small"))
+ if (error.includes("corrupted") || error.includes("incomplete") || error.includes("too small")) {
return t("hooks.modelDownload.errors.corrupted");
- if (error.includes("HTTP 429") || error.includes("rate limit"))
+ }
+ if (error.includes("HTTP 429") || error.includes("rate limit")) {
return t("hooks.modelDownload.errors.rateLimited");
- if (error.includes("HTTP 4") || error.includes("HTTP 5"))
+ }
+ if (error.includes("HTTP 4") || error.includes("HTTP 5")) {
return t("hooks.modelDownload.errors.server", { error });
+ }
return t("hooks.modelDownload.errors.generic", { error });
}
+function isCancellation(error?: string, code?: string) {
+ return (
+ code === "DOWNLOAD_CANCELLED" ||
+ error?.includes("interrupted by user") ||
+ error?.includes("cancelled by user") ||
+ error?.includes("Download cancelled")
+ );
+}
+
export function useModelDownload({
modelType,
onDownloadComplete,
onModelsCleared,
}: UseModelDownloadOptions) {
const { t } = useTranslation();
- const [downloadingModel, setDownloadingModel] = useState<string | null>(null);
- const [downloadProgress, setDownloadProgress] = useState<DownloadProgress>({
- percentage: 0,
- downloadedBytes: 0,
- totalBytes: 0,
- });
- const [isCancelling, setIsCancelling] = useState(false);
- const [isInstalling, setIsInstalling] = useState(false);
- const [downloadError, setDownloadError] = useState<string | null>(null);
- const isCancellingRef = useRef(false);
- const lastProgressUpdateRef = useRef(0);
- const downloadingModelRef = useRef<string | null>(null);
- const downloadStateVersionRef = useRef(0);
- const activeDownloadRequestRef = useRef<PendingModelDownloadRequest | null>(null);
-
const { showAlertDialog } = useDialogs();
const { toast } = useToast();
- const showAlertDialogRef = useRef(showAlertDialog);
+ const [downloads, setDownloads] = useState<Record<string, LocalModelDownloadStatus>>({});
+ const [cancellingModels, setCancellingModels] = useState<Set<string>>(new Set());
+ const [downloadErrors, setDownloadErrors] = useState<Record<string, string>>({});
+ const ownedRequestsRef = useRef(new Map<string, ModelDownloadTerminalEvent | null>());
+ const settlingDownloadsRef = useRef(new Set<string>());
+ const terminalSequencesRef = useRef<Record<string, number>>({});
+ const lastProgressUpdateRef = useRef<Record<string, number>>({});
const onDownloadCompleteRef = useRef(onDownloadComplete);
const onModelsClearedRef = useRef(onModelsCleared);
- useEffect(() => {
- showAlertDialogRef.current = showAlertDialog;
- }, [showAlertDialog]);
-
useEffect(() => {
onDownloadCompleteRef.current = onDownloadComplete;
}, [onDownloadComplete]);
@@ -121,280 +116,189 @@ 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 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 {
- 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;
- }
-
- 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.downloadedBytes || 0,
- totalBytes: activeModel.totalBytes || 0,
+ const updateDownload = useCallback(
+ (status: LocalModelDownloadStatus) => {
+ if (status.modelType !== modelType) return;
+ setDownloads((current) => {
+ const terminalSequence = terminalSequencesRef.current[status.modelId] || 0;
+ if (status.sequence !== 0 && status.sequence <= terminalSequence) return current;
+ const existing = current[status.modelId];
+ if (existing && existing.sequence > status.sequence) return current;
+ return { ...current, [status.modelId]: status };
});
- return true;
},
[modelType]
);
- const applyTerminalEvent = useCallback(
- (data: ModelDownloadTerminalEvent) => {
- const trackedModel = downloadingModelRef.current;
- if (trackedModel && trackedModel !== data.modelId) return;
+ const removeDownload = useCallback((modelId: string, sequence?: number) => {
+ setDownloads((current) => {
+ const existing = current[modelId];
+ if (!existing || (sequence !== undefined && existing.sequence > sequence)) return current;
+ const { [modelId]: _removed, ...remaining } = current;
+ return remaining;
+ });
+ }, []);
- const terminalVersion = ++downloadStateVersionRef.current;
+ const clearCancelling = useCallback((modelId: string) => {
+ setCancellingModels((current) => {
+ if (!current.has(modelId)) return current;
+ const next = new Set(current);
+ next.delete(modelId);
+ return next;
+ });
+ }, []);
- if (data.type === "complete") {
- notifyLocalModelsChanged();
- 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 settleDownload = useCallback(
+ async (modelId: string, sequence?: number) => {
+ if (settlingDownloadsRef.current.has(modelId)) return;
+ settlingDownloadsRef.current.add(modelId);
+ try {
+ await onDownloadCompleteRef.current?.();
+ } catch {
+ // The model is already on disk even if the UI refresh fails.
+ } finally {
+ removeDownload(modelId, sequence);
+ clearCancelling(modelId);
+ settlingDownloadsRef.current.delete(modelId);
}
-
- 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]
+ [clearCancelling, removeDownload]
);
- const handleTranscriptionProgress = useCallback(
- (_event: unknown, data: WhisperDownloadProgressData) => {
- if (isCancellingRef.current) return;
-
- const trackedModel = downloadingModelRef.current;
- if (trackedModel && trackedModel !== data.model) return;
+ const handleTerminalDownload = useCallback(
+ async (
+ modelId: string,
+ type: "complete" | "error",
+ error?: string,
+ code?: string,
+ sequence?: number
+ ): Promise<void> => {
+ if (sequence !== undefined) {
+ terminalSequencesRef.current[modelId] = Math.max(
+ terminalSequencesRef.current[modelId] || 0,
+ sequence
+ );
+ }
+ if (ownedRequestsRef.current.has(modelId)) {
+ ownedRequestsRef.current.set(modelId, { type, error, code, sequence });
+ return;
+ }
+ if (type === "complete") notifyLocalModelsChanged();
+ if (type === "error" && !isCancellation(error, code)) {
+ const message = getDownloadErrorMessage(
+ t,
+ error || t("hooks.modelDownload.errors.unknown"),
+ code
+ );
+ setDownloadErrors((current) => ({ ...current, [modelId]: message }));
+ showAlertDialog({
+ title:
+ code === "EXTRACTION_FAILED"
+ ? t("hooks.modelDownload.installationFailed.title")
+ : t("hooks.modelDownload.downloadFailed.title"),
+ description: message,
+ });
+ }
+ await settleDownload(modelId, sequence);
+ },
+ [settleDownload, showAlertDialog, t]
+ );
+ const handleNativeProgress = useCallback(
+ (data: WhisperDownloadProgressData) => {
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);
+ void handleTerminalDownload(data.model, data.type, data.error, data.code, data.sequence);
return;
}
+ if (data.type !== "progress" && data.type !== "installing") return;
- downloadStateVersionRef.current += 1;
- downloadingModelRef.current = data.model;
- setDownloadingModel(data.model);
- setDownloadError(null);
-
- if (data.type === "progress") {
+ const isInstalling = data.type === "installing";
+ if (!isInstalling) {
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,
- totalBytes: data.total_bytes || 0,
- });
- } else if (data.type === "installing") {
- setIsInstalling(true);
- setDownloadProgress((current) => ({
- ...current,
- percentage: data.percentage ?? 100,
- }));
+ const lastUpdate = lastProgressUpdateRef.current[data.model] || 0;
+ if (now - lastUpdate < PROGRESS_THROTTLE_MS) return;
+ lastProgressUpdateRef.current[data.model] = now;
}
+ updateDownload({
+ modelType,
+ modelId: data.model,
+ phase: isInstalling ? "installing" : "downloading",
+ progress: isInstalling ? data.percentage || 100 : data.percentage || 0,
+ downloadedBytes: isInstalling ? 0 : data.downloaded_bytes || 0,
+ totalBytes: isInstalling ? 0 : data.total_bytes || 0,
+ sequence: data.sequence || 0,
+ });
},
- [applyTerminalEvent]
+ [handleTerminalDownload, modelType, updateDownload]
);
const handleLLMProgress = useCallback(
- (_event: unknown, data: LocalLLMDownloadProgressEvent) => {
- if (isCancellingRef.current) return;
-
+ (_event: unknown, data: LLMDownloadProgressData) => {
if (data.type === "complete") {
- const activeRequest = activeDownloadRequestRef.current;
- if (activeRequest?.modelId === data.modelId) {
- downloadStateVersionRef.current += 1;
- activeRequest.terminalEvent = data;
- return;
- }
- applyTerminalEvent({ ...data, modelId: data.modelId });
+ void handleTerminalDownload(data.modelId, data.type, undefined, undefined, data.sequence);
return;
}
-
if (data.type === "error") {
- const activeRequest = activeDownloadRequestRef.current;
- if (activeRequest?.modelId === data.modelId) {
- downloadStateVersionRef.current += 1;
- activeRequest.terminalEvent = data;
- return;
- }
- applyTerminalEvent({ ...data, modelId: data.modelId });
+ void handleTerminalDownload(data.modelId, data.type, data.error, data.code, data.sequence);
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) {
- return;
- }
- lastProgressUpdateRef.current = now;
-
- downloadingModelRef.current = data.modelId;
- setDownloadingModel(data.modelId);
- setDownloadProgress({
- percentage: data.progress || 0,
+ const lastUpdate = lastProgressUpdateRef.current[data.modelId] || 0;
+ if ((data.progress || 0) < 100 && now - lastUpdate < PROGRESS_THROTTLE_MS) return;
+ lastProgressUpdateRef.current[data.modelId] = now;
+ updateDownload({
+ modelType: "llm",
+ modelId: data.modelId,
+ phase: "downloading",
+ progress: data.progress || 0,
downloadedBytes: data.downloadedSize || 0,
totalBytes: data.totalSize || 0,
+ sequence: data.sequence || 0,
});
},
- [applyTerminalEvent]
+ [handleTerminalDownload, updateDownload]
);
useEffect(() => {
- let dispose: (() => void) | undefined;
-
- if (modelType === "whisper") {
- dispose = window.electronAPI?.onWhisperDownloadProgress(handleTranscriptionProgress);
- } else if (modelType === "parakeet") {
- dispose = window.electronAPI?.onParakeetDownloadProgress(handleTranscriptionProgress);
- } else {
- dispose = window.electronAPI?.onModelDownloadProgress(handleLLMProgress);
- }
-
- return () => {
- dispose?.();
- };
- }, [handleTranscriptionProgress, handleLLMProgress, modelType]);
+ const dispose =
+ modelType === "whisper"
+ ? window.electronAPI?.onWhisperDownloadProgress((_event, data) =>
+ handleNativeProgress(data)
+ )
+ : modelType === "parakeet"
+ ? window.electronAPI?.onParakeetDownloadProgress((_event, data) =>
+ handleNativeProgress(data)
+ )
+ : window.electronAPI?.onModelDownloadProgress(handleLLMProgress);
+ return () => dispose?.();
+ }, [handleLLMProgress, handleNativeProgress, modelType]);
useEffect(() => {
- 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();
+ let disposed = false;
+ window.electronAPI
+ ?.modelGetActiveDownloads?.()
+ .then((activeDownloads) => {
+ if (!disposed) activeDownloads.forEach(updateDownload);
+ })
+ .catch(() => {});
return () => {
- cancelled = true;
+ disposed = true;
};
- }, [hydrateActiveDownload]);
+ }, [updateDownload]);
const downloadModel = useCallback(
async (modelId: string, onSelectAfterDownload?: (id: string) => void) => {
- if (downloadingModelRef.current) {
+ if (
+ ownedRequestsRef.current.has(modelId) ||
+ downloads[modelId] ||
+ (modelType !== "llm" && Object.keys(downloads).length > 0)
+ ) {
toast({
title: t("hooks.modelDownload.downloadInProgress.title"),
description: t("hooks.modelDownload.downloadInProgress.description"),
@@ -402,115 +306,105 @@ export function useModelDownload({
return;
}
+ ownedRequestsRef.current.set(modelId, null);
+ setDownloadErrors((current) => {
+ if (!(modelId in current)) return current;
+ const { [modelId]: _removed, ...remaining } = current;
+ return remaining;
+ });
+ updateDownload({
+ modelType,
+ modelId,
+ phase: "downloading",
+ progress: 0,
+ downloadedBytes: 0,
+ totalBytes: 0,
+ sequence: 0,
+ });
+ lastProgressUpdateRef.current[modelId] = 0;
+
let keepActiveDownloadState = false;
- let terminalEventApplied = false;
- const downloadRequest: PendingModelDownloadRequest = { modelId };
+ let isDuplicateRequest = false;
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 = downloadRequest;
-
- let result: { success?: boolean; error?: string; code?: string } | undefined;
-
- if (modelType === "whisper") {
- result = await window.electronAPI?.downloadWhisperModel(modelId);
- } else if (modelType === "parakeet") {
- result = await window.electronAPI?.downloadParakeetModel(modelId);
- } else {
- result = (await window.electronAPI?.modelDownload?.(modelId)) as unknown as
- { success: boolean; error?: string; code?: string } | undefined;
- }
-
- 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;
- } 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;
- }
-
- if (result?.error) {
- const msg = getDownloadErrorMessage(t, result.error, result.code);
- setDownloadError(msg);
- showAlertDialog({
- title:
- result.code === "EXTRACTION_FAILED"
- ? t("hooks.modelDownload.installationFailed.title")
- : t("hooks.modelDownload.downloadFailed.title"),
- description: msg,
- });
- }
- } else {
+ const result =
+ modelType === "whisper"
+ ? await window.electronAPI?.downloadWhisperModel(modelId)
+ : modelType === "parakeet"
+ ? await window.electronAPI?.downloadParakeetModel(modelId)
+ : await window.electronAPI?.modelDownload?.(modelId);
+
+ if (result?.success) {
notifyLocalModelsChanged();
onSelectAfterDownload?.(modelId);
- }
-
- // Await the refresh so the model list is updated before we clear
- // the downloading state in `finally`. This prevents a flash where
- // the model briefly appears "not downloaded".
- try {
- await onDownloadCompleteRef.current?.();
- } catch {
- // Non-fatal — the model is on disk regardless
+ } else if (result?.code === "DOWNLOAD_IN_PROGRESS") {
+ isDuplicateRequest = true;
+ const activeDownloads = await window.electronAPI?.modelGetActiveDownloads?.();
+ if (ownedRequestsRef.current.get(modelId)) return;
+ const activeDownload = activeDownloads?.find(
+ (status) =>
+ status.modelType === modelType && (modelType !== "llm" || status.modelId === modelId)
+ );
+ if (activeDownload) {
+ updateDownload(activeDownload);
+ keepActiveDownloadState = activeDownload.modelId === modelId;
+ }
+ toast({
+ title: t("hooks.modelDownload.downloadInProgress.title"),
+ description: t("hooks.modelDownload.downloadInProgress.description"),
+ });
+ } else if (!isCancellation(result?.error, result?.code)) {
+ const message = getDownloadErrorMessage(
+ t,
+ result?.error || t("hooks.modelDownload.errors.unknown"),
+ result?.code
+ );
+ setDownloadErrors((current) => ({ ...current, [modelId]: message }));
+ showAlertDialog({
+ title:
+ result?.code === "EXTRACTION_FAILED"
+ ? t("hooks.modelDownload.installationFailed.title")
+ : t("hooks.modelDownload.downloadFailed.title"),
+ description: message,
+ });
}
} catch (error: unknown) {
- if (isCancellingRef.current) return;
-
const errorMessage = error instanceof Error ? error.message : String(error);
- if (
- !errorMessage.includes("interrupted by user") &&
- !errorMessage.includes("cancelled by user") &&
- !errorMessage.includes("DOWNLOAD_CANCELLED")
- ) {
- const msg = getDownloadErrorMessage(t, errorMessage);
- setDownloadError(msg);
+ if (!isCancellation(errorMessage)) {
+ const message = getDownloadErrorMessage(t, errorMessage);
+ setDownloadErrors((current) => ({ ...current, [modelId]: message }));
showAlertDialog({
title: t("hooks.modelDownload.downloadFailed.title"),
- description: msg,
+ description: message,
});
}
} finally {
- if (activeDownloadRequestRef.current === downloadRequest) {
- activeDownloadRequestRef.current = null;
+ const terminalEvent = ownedRequestsRef.current.get(modelId);
+ ownedRequestsRef.current.delete(modelId);
+ if (isDuplicateRequest && terminalEvent) {
+ // A duplicate response cannot carry the original transfer's terminal result.
+ await handleTerminalDownload(
+ modelId,
+ terminalEvent.type,
+ terminalEvent.error,
+ terminalEvent.code,
+ terminalEvent.sequence
+ );
+ } else if (!keepActiveDownloadState) {
+ await settleDownload(modelId);
}
- if (keepActiveDownloadState) return;
- if (terminalEventApplied) return;
- downloadingModelRef.current = null;
- setIsInstalling(false);
- setDownloadingModel(null);
- setDownloadProgress({ percentage: 0, downloadedBytes: 0, totalBytes: 0 });
}
},
- [applyTerminalEvent, hydrateActiveDownload, modelType, showAlertDialog, toast, t]
+ [
+ downloads,
+ handleTerminalDownload,
+ modelType,
+ settleDownload,
+ showAlertDialog,
+ t,
+ toast,
+ updateDownload,
+ ]
);
const deleteModel = useCallback(
@@ -557,61 +451,57 @@ export function useModelDownload({
});
}
},
- [modelType, toast, showAlertDialog, t]
+ [modelType, showAlertDialog, t, toast]
);
- const cancelDownload = useCallback(async () => {
- 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") {
- result = await window.electronAPI?.cancelWhisperDownload();
- } else if (modelType === "parakeet") {
- result = await window.electronAPI?.cancelParakeetDownload();
- } else {
- result = await window.electronAPI?.modelCancelDownload?.(downloadingModel);
- }
- if (!result?.success) return;
+ const cancelDownload = useCallback(
+ async (modelId?: string) => {
+ const targetModel = modelId || Object.keys(downloads)[0];
+ if (!targetModel || cancellingModels.has(targetModel)) return;
+ if (downloads[targetModel]?.phase === "installing") return;
- cancelled = true;
- toast({
- title: t("hooks.modelDownload.downloadCancelled.title"),
- description: t("hooks.modelDownload.downloadCancelled.description"),
- });
- } catch (error) {
- console.error("Failed to cancel download:", error);
- } 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, isInstalling, modelType, toast, t]);
-
- const isDownloading = downloadingModel !== null;
- const isDownloadingModel = useCallback(
- (modelId: string) => downloadingModel === modelId,
- [downloadingModel]
+ setCancellingModels((current) => new Set(current).add(targetModel));
+ try {
+ const result =
+ modelType === "whisper"
+ ? await window.electronAPI?.cancelWhisperDownload()
+ : modelType === "parakeet"
+ ? await window.electronAPI?.cancelParakeetDownload()
+ : await window.electronAPI?.modelCancelDownload?.(targetModel);
+ if (result?.success) {
+ toast({
+ title: t("hooks.modelDownload.downloadCancelled.title"),
+ description: t("hooks.modelDownload.downloadCancelled.description"),
+ });
+ return;
+ }
+ } catch (error) {
+ console.error("Failed to cancel download:", error);
+ }
+ clearCancelling(targetModel);
+ },
+ [cancellingModels, clearCancelling, downloads, modelType, t, toast]
);
+ const downloadingModel = Object.keys(downloads)[0] || null;
+ const activeDownload = downloadingModel ? downloads[downloadingModel] : null;
+ const errorMessages = Object.values(downloadErrors);
+
return {
+ downloads,
+ downloadErrors,
downloadingModel,
- downloadProgress,
- downloadError,
- isDownloading,
- isDownloadingModel,
- isInstalling,
- isCancelling,
+ downloadProgress: {
+ percentage: activeDownload?.progress || 0,
+ downloadedBytes: activeDownload?.downloadedBytes || 0,
+ totalBytes: activeDownload?.totalBytes || 0,
+ },
+ downloadError: errorMessages[errorMessages.length - 1] || null,
+ isDownloading: downloadingModel !== null,
+ isInstalling: activeDownload?.phase === "installing",
+ isCancelling: downloadingModel ? cancellingModels.has(downloadingModel) : false,
+ isDownloadingModel: (modelId: string) => !!downloads[modelId],
+ isCancellingModel: (modelId: string) => cancellingModels.has(modelId),
downloadModel,
deleteModel,
cancelDownload,
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 168f8f6eb..cd6680c9d 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -762,6 +762,17 @@ export interface WhisperDownloadProgressData {
error?: string;
code?: string;
result?: any;
+ sequence?: number;
+}
+
+export interface LocalModelDownloadStatus {
+ modelType: "whisper" | "parakeet" | "llm";
+ modelId: string;
+ phase: "downloading" | "installing";
+ progress: number;
+ downloadedBytes: number;
+ totalBytes: number;
+ sequence: number;
}
export interface ParakeetCheckResult {
@@ -813,6 +824,7 @@ export interface ParakeetDownloadProgressData {
total_bytes?: number;
error?: string;
code?: string;
+ sequence?: number;
}
export interface ParakeetTranscriptionResult {
@@ -898,6 +910,7 @@ export type LocalLLMDownloadProgressEvent =
progress: number;
downloadedSize: number;
totalSize: number;
+ sequence?: number;
}
| {
type: "complete";
@@ -905,6 +918,7 @@ export type LocalLLMDownloadProgressEvent =
progress: 100;
downloadedSize?: number;
totalSize?: number;
+ sequence?: number;
}
| {
type: "error";
@@ -912,6 +926,7 @@ export type LocalLLMDownloadProgressEvent =
error: string;
code?: string;
details?: unknown;
+ sequence?: number;
};
export interface ConversationPreview {
@@ -1658,6 +1673,7 @@ declare global {
// Local AI model management
modelGetAll: () => Promise<LocalLLMModelStatus[]>;
+ modelGetActiveDownloads: () => Promise<LocalModelDownloadStatus[]>;
modelCheck: (modelId: string) => Promise<boolean>;
modelDownload: (modelId: string) => Promise<{
success: boolean;
diff --git a/test/components/localModelSetupStep.test.js b/test/components/localModelSetupStep.test.js
new file mode 100644
index 000000000..f85f8532b
--- /dev/null
+++ b/test/components/localModelSetupStep.test.js
@@ -0,0 +1,370 @@
+const assert = require("node:assert/strict");
+const test = require("node:test");
+const React = require("react");
+const { createRoot } = require("react-dom/client");
+const {
+ createRendererServer,
+ installBrowserGlobals,
+ installHookDom,
+} = require("../lib/rendererTestHarness");
+
+const FIRST_LLM = "qwen3.5-4b-q4_k_m";
+const SECOND_LLM = "qwen3.5-2b-q4_k_m";
+
+function findElement(node, predicate) {
+ if (Array.isArray(node)) {
+ for (const child of node) {
+ const match = findElement(child, predicate);
+ if (match) return match;
+ }
+ return null;
+ }
+ if (!node || typeof node !== "object") return null;
+ return predicate(node) ? node : findElement(node.props?.children, predicate);
+}
+
+function textContent(node) {
+ if (Array.isArray(node)) return node.map(textContent).join("");
+ if (node && typeof node === "object") return textContent(node.props?.children);
+ return node == null || typeof node === "boolean" ? "" : String(node);
+}
+
+async function createSetupHarness(
+ t,
+ { assistant = false, provider = assistant ? "qwen" : "whisper", installed = {} } = {}
+) {
+ let unmount = async () => {};
+ t.after(() => unmount());
+ const listeners = { whisper: new Set(), parakeet: new Set(), llm: new Set() };
+ const inventory = {
+ whisper: new Set(installed.whisper),
+ parakeet: new Set(installed.parakeet),
+ llm: new Set(installed.llm),
+ };
+ const requests = new Map();
+ const events = new EventTarget();
+ const subscribe = (family) => (listener) => {
+ listeners[family].add(listener);
+ return () => listeners[family].delete(listener);
+ };
+ const startDownload = (family) => (modelId) =>
+ new Promise((resolve) => requests.set(modelId, { family, resolve }));
+ installBrowserGlobals(t, {
+ window: {
+ addEventListener: events.addEventListener.bind(events),
+ removeEventListener: events.removeEventListener.bind(events),
+ dispatchEvent: events.dispatchEvent.bind(events),
+ electronAPI: {
+ getPlatform: () => "linux",
+ listWhisperModels: async () => ({
+ success: true,
+ models: [...inventory.whisper].map((model) => ({ model, downloaded: true })),
+ }),
+ listParakeetModels: async () => ({
+ success: true,
+ models: [...inventory.parakeet].map((model) => ({ model, downloaded: true })),
+ }),
+ modelGetAll: async () =>
+ [...inventory.llm].map((id) => ({ id, isDownloaded: true, isDownloading: false })),
+ modelGetActiveDownloads: async () => [],
+ downloadWhisperModel: startDownload("whisper"),
+ downloadParakeetModel: startDownload("parakeet"),
+ modelDownload: startDownload("llm"),
+ modelCancelDownload: async (modelId) => {
+ const response = {
+ success: false,
+ code: "DOWNLOAD_CANCELLED",
+ error: "Download cancelled by user",
+ };
+ for (const listener of listeners.llm) {
+ listener({}, { type: "error", modelId, code: response.code, error: response.error });
+ }
+ requests.get(modelId).resolve(response);
+ return { success: true };
+ },
+ onWhisperDownloadProgress: subscribe("whisper"),
+ onParakeetDownloadProgress: subscribe("parakeet"),
+ onModelDownloadProgress: subscribe("llm"),
+ },
+ },
+ });
+ const container = installHookDom(t);
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-local-setup-test-",
+ noExternal: ["react-i18next"],
+ mockModules: {
+ "react-i18next": `
+ const t = (key) => key;
+ export function useTranslation() { return { t }; }
+ export const initReactI18next = { type: "3rdParty", init() {} };
+ `,
+ "/ProviderConnectionTest": `export default function ProviderConnectionTest() { return null; }`,
+ "/OnboardingShell": `export function BrandMark() { return null; }`,
+ "/ui/ProviderIcon": `export function ProviderIcon() { return null; }`,
+ },
+ });
+ const { useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");
+ useSettingsStore.setState({
+ localTranscriptionProvider: provider === "nvidia" ? "nvidia" : "whisper",
+ whisperModel: "",
+ parakeetModel: "",
+ chatAgentProvider: assistant ? provider : "qwen",
+ chatAgentModel: "",
+ chatAgentMode: "local",
+ });
+ const { LocalModelSetupStep } = await vite.ssrLoadModule(
+ "/components/onboarding/ProviderSetupStep.tsx"
+ );
+ const { ToastContext } = await vite.ssrLoadModule("/components/ui/useToast.ts");
+ const pending = await vite.ssrLoadModule("/components/onboarding/pendingLocalModels.ts");
+ const { default: BackgroundModelDownloadTray } = await vite.ssrLoadModule(
+ "/components/onboarding/BackgroundModelDownloadTray.tsx"
+ );
+ let tree;
+ let trayTree;
+ let ready = false;
+ let proceeded = false;
+ const props = {
+ stepId: assistant ? "local-assistant" : "local-dictation",
+ onReadinessChange: (value) => {
+ ready = value;
+ },
+ onProceed() {
+ proceeded = true;
+ },
+ onSkip() {},
+ };
+ function Harness() {
+ // Execute the real component and hooks with React lifecycle, while leaving
+ // native controls unmounted: their returned handlers are the test boundary.
+ tree = LocalModelSetupStep(props);
+ trayTree = BackgroundModelDownloadTray();
+ return null;
+ }
+ const root = createRoot(container);
+ const toast = { toast: () => "test-toast" };
+ await React.act(async () => {
+ root.render(
+ React.createElement(ToastContext.Provider, { value: toast }, React.createElement(Harness))
+ );
+ });
+ unmount = async () => {
+ await React.act(async () => root.unmount());
+ };
+
+ const row = (modelId) => {
+ const element = findElement(tree, (node) => node.type === "div" && node.key === modelId);
+ assert.ok(element, `model row ${modelId} is visible`);
+ return element;
+ };
+ const click = async (modelId, action) => {
+ const button = findElement(
+ row(modelId),
+ (node) => typeof node.props?.onClick === "function" && textContent(node) === action
+ );
+ assert.ok(button, `${action} is available for ${modelId}: ${textContent(row(modelId))}`);
+ await React.act(async () => button.props.onClick());
+ };
+ const progress = async (modelId, percentage, phase = "progress") => {
+ const family = requests.get(modelId).family;
+ const event =
+ family === "llm"
+ ? { modelId, type: phase, progress: percentage, downloadedSize: percentage, totalSize: 100 }
+ : {
+ model: modelId,
+ type: phase,
+ percentage,
+ downloaded_bytes: percentage,
+ total_bytes: 100,
+ };
+ await React.act(async () => {
+ for (const listener of listeners[family]) listener({}, event);
+ });
+ };
+ const complete = async (modelId) => {
+ const request = requests.get(modelId);
+ assert.ok(request, `download ${modelId} started`);
+ inventory[request.family].add(modelId);
+ await React.act(async () => {
+ for (const listener of listeners[request.family]) {
+ listener(
+ {},
+ request.family === "llm"
+ ? { type: "complete", modelId, progress: 100 }
+ : { type: "complete", model: modelId, percentage: 100 }
+ );
+ }
+ request.resolve({ success: true });
+ });
+ };
+ const actionButton = (label) =>
+ findElement(
+ tree,
+ (node) => typeof node.props?.onClick === "function" && textContent(node) === label
+ );
+ return {
+ store: useSettingsStore,
+ pending,
+ row,
+ click,
+ progress,
+ complete,
+ cancel: async (modelId) => {
+ const trayRow = findElement(
+ trayTree,
+ (node) => node.type === "div" && node.key === `llm:${modelId}`
+ );
+ assert.ok(trayRow, `tray row ${modelId} is visible`);
+ const button = findElement(trayRow, (node) => node.type === "button");
+ await React.act(async () => button.props.onClick());
+ },
+ chooseProvider: async (providerId) => {
+ const select = findElement(tree, (node) => typeof node.props?.onValueChange === "function");
+ await React.act(async () => select.props.onValueChange(providerId));
+ },
+ proceed: async () => {
+ const button = actionButton("onboarding.rehaul.provider.proceed");
+ assert.equal(button.props.disabled, false, "Proceed is enabled");
+ await React.act(async () => button.props.onClick());
+ },
+ proceeded: () => proceeded,
+ ready: () => ready,
+ canProceed: () => !actionButton("onboarding.rehaul.provider.proceed").props.disabled,
+ canSkip: () => {
+ const button = actionButton("common.skip");
+ return Boolean(button && !button.props.disabled);
+ },
+ };
+}
+
+for (const fixture of [
+ { family: "whisper", provider: "whisper", modelId: "base", setting: "whisperModel" },
+ {
+ family: "parakeet",
+ provider: "nvidia",
+ modelId: "parakeet-tdt-0.6b-v3",
+ setting: "parakeetModel",
+ },
+ { family: "llm", provider: "qwen", modelId: FIRST_LLM, setting: "chatAgentModel" },
+]) {
+ test(`Use selects an installed ${fixture.family} model without a pending download`, async (t) => {
+ const setup = await createSetupHarness(t, {
+ assistant: fixture.family === "llm",
+ provider: fixture.provider,
+ installed: { [fixture.family]: [fixture.modelId] },
+ });
+ assert.equal(setup.canProceed(), false);
+ await setup.click(fixture.modelId, "onboarding.rehaul.local.use");
+ assert.equal(setup.store.getState()[fixture.setting], fixture.modelId);
+ assert.equal(setup.ready(), true);
+ assert.equal(setup.canProceed(), true);
+ });
+}
+
+test("an explicit installed-model choice supersedes an earlier pending download", async (t) => {
+ const setup = await createSetupHarness(t, { assistant: true, installed: { llm: [SECOND_LLM] } });
+ await setup.click(FIRST_LLM, "onboarding.rehaul.local.download");
+ await setup.click(SECOND_LLM, "onboarding.rehaul.local.use");
+ assert.equal(setup.pending.hasPendingLocalModels(), false);
+ assert.equal(setup.canProceed(), true);
+ assert.equal(setup.canSkip(), true);
+ await setup.complete(FIRST_LLM);
+ assert.equal(setup.store.getState().chatAgentModel, SECOND_LLM);
+ assert.equal(setup.ready(), true);
+});
+
+test("completion enables Proceed after the background tray consumes the pending selection", async (t) => {
+ const setup = await createSetupHarness(t, { assistant: true });
+ await setup.click(FIRST_LLM, "onboarding.rehaul.local.download");
+ localStorage.setItem("localSetupPending", "true");
+ await setup.complete(FIRST_LLM);
+ assert.equal(setup.pending.hasPendingLocalModels(), false);
+ assert.equal(setup.store.getState().chatAgentModel, FIRST_LLM);
+ assert.equal(setup.ready(), true);
+ assert.equal(setup.canProceed(), true);
+});
+
+test("simultaneous assistant downloads display their own progress", async (t) => {
+ const setup = await createSetupHarness(t, { assistant: true });
+ await setup.click(FIRST_LLM, "onboarding.rehaul.local.download");
+ await setup.click(SECOND_LLM, "onboarding.rehaul.local.download");
+ await setup.progress(FIRST_LLM, 10);
+ await setup.progress(SECOND_LLM, 80);
+ assert.match(textContent(setup.row(FIRST_LLM)), /10%/);
+ assert.match(textContent(setup.row(SECOND_LLM)), /80%/);
+});
+
+test("the most recently started assistant download owns pending selection", async (t) => {
+ const setup = await createSetupHarness(t, { assistant: true });
+ await setup.click(FIRST_LLM, "onboarding.rehaul.local.download");
+ await setup.click(SECOND_LLM, "onboarding.rehaul.local.download");
+ assert.equal(setup.pending.readPendingLocalModels().assistant.modelId, SECOND_LLM);
+ await setup.complete(FIRST_LLM);
+ assert.equal(setup.store.getState().chatAgentModel, "");
+ await setup.complete(SECOND_LLM);
+ assert.equal(setup.store.getState().chatAgentModel, SECOND_LLM);
+ assert.equal(setup.ready(), true);
+});
+
+test("a refused concurrent Whisper download preserves the original pending selection", async (t) => {
+ const setup = await createSetupHarness(t);
+ await setup.click("base", "onboarding.rehaul.local.download");
+ await setup.click("small", "onboarding.rehaul.local.download");
+ assert.equal(setup.pending.readPendingLocalModels().dictation.modelId, "base");
+ await setup.complete("base");
+ assert.equal(setup.store.getState().whisperModel, "base");
+ assert.equal(setup.ready(), true);
+});
+
+test("cancelling the newest assistant download blocks both ways to continue until a model is chosen", async (t) => {
+ const setup = await createSetupHarness(t, { assistant: true });
+ await setup.click(FIRST_LLM, "onboarding.rehaul.local.download");
+ await setup.click(SECOND_LLM, "onboarding.rehaul.local.download");
+ await setup.progress(FIRST_LLM, 10);
+ await setup.progress(SECOND_LLM, 20);
+ await setup.cancel(SECOND_LLM);
+
+ assert.equal(setup.pending.hasPendingLocalModels(), false);
+ assert.deepEqual(
+ { proceed: setup.canProceed(), skip: setup.canSkip() },
+ { proceed: false, skip: false }
+ );
+ await setup.complete(FIRST_LLM);
+ assert.equal(setup.store.getState().chatAgentModel, "");
+ assert.equal(setup.canProceed(), false);
+ await setup.click(FIRST_LLM, "onboarding.rehaul.local.use");
+ assert.equal(setup.store.getState().chatAgentModel, FIRST_LLM);
+ assert.equal(setup.canProceed(), true);
+});
+
+test("cancelling an older assistant download preserves the pending background selection", async (t) => {
+ const setup = await createSetupHarness(t, { assistant: true });
+ await setup.click(FIRST_LLM, "onboarding.rehaul.local.download");
+ await setup.click(SECOND_LLM, "onboarding.rehaul.local.download");
+ await setup.progress(FIRST_LLM, 10);
+ await setup.progress(SECOND_LLM, 20);
+ await setup.cancel(FIRST_LLM);
+
+ assert.equal(setup.pending.readPendingLocalModels().assistant.modelId, SECOND_LLM);
+ assert.equal(setup.canProceed(), true);
+ assert.equal(setup.canSkip(), true);
+ await setup.proceed();
+ assert.equal(setup.proceeded(), true);
+ assert.equal(localStorage.getItem("localSetupPending"), "true");
+ await setup.complete(SECOND_LLM);
+ assert.equal(setup.store.getState().chatAgentModel, SECOND_LLM);
+ assert.equal(setup.ready(), true);
+});
+
+test("browsing another dictation provider preserves the active pending background selection", async (t) => {
+ const setup = await createSetupHarness(t);
+ await setup.click("base", "onboarding.rehaul.local.download");
+ await setup.chooseProvider("nvidia");
+ assert.equal(setup.canProceed(), true);
+ assert.equal(setup.canSkip(), true);
+ await setup.proceed();
+ assert.equal(localStorage.getItem("localSetupPending"), "true");
+ await setup.complete("base");
+ assert.equal(setup.store.getState().localTranscriptionProvider, "whisper");
+ assert.equal(setup.store.getState().whisperModel, "base");
+});
diff --git a/test/helpers/localModelDownloadStatus.test.js b/test/helpers/localModelDownloadStatus.test.js
new file mode 100644
index 000000000..8dbabe1c3
--- /dev/null
+++ b/test/helpers/localModelDownloadStatus.test.js
@@ -0,0 +1,57 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const LocalModelDownloadStatus = require("../../src/helpers/localModelDownloadStatus");
+
+test("tracks independent local model downloads with normalized progress", () => {
+ const status = new LocalModelDownloadStatus();
+
+ const whisper = status.start("whisper", "base");
+ const llm = status.start("llm", "qwen-2.5-7b");
+ const installing = status.update("parakeet", "parakeet-tdt-0.6b-v3", {
+ phase: "installing",
+ progress: 100,
+ });
+ const progressed = status.update("whisper", "base", {
+ progress: 42,
+ downloadedBytes: 42,
+ totalBytes: 100,
+ });
+
+ assert.equal(whisper.phase, "downloading");
+ assert.equal(llm.progress, 0);
+ assert.equal(installing.phase, "installing");
+ assert.equal(progressed.sequence > installing.sequence, true);
+ assert.deepEqual(status.getActiveDownloads(), [progressed, llm, installing]);
+});
+
+test("does not reset an existing download and removes it only on finish", () => {
+ const status = new LocalModelDownloadStatus();
+
+ status.start("llm", "qwen-2.5-7b");
+ const progressed = status.update("llm", "qwen-2.5-7b", {
+ progress: 55,
+ downloadedBytes: 55,
+ totalBytes: 100,
+ });
+ const duplicateStart = status.start("llm", "qwen-2.5-7b");
+
+ assert.deepEqual(duplicateStart, progressed);
+ assert.equal(status.has("llm", "qwen-2.5-7b"), true);
+
+ const finished = status.finish("llm", "qwen-2.5-7b");
+ assert.equal(finished.progress, 55);
+ assert.equal(finished.sequence > progressed.sequence, true);
+ assert.deepEqual(status.getActiveDownloads(), []);
+});
+
+test("starts an active download with zero progress", () => {
+ const status = new LocalModelDownloadStatus();
+ const started = status.start("whisper", "small");
+
+ assert.equal(started.modelType, "whisper");
+ assert.equal(started.phase, "downloading");
+ assert.equal(started.progress, 0);
+ assert.equal(started.downloadedBytes, 0);
+ assert.equal(started.totalBytes, 0);
+});
diff --git a/test/helpers/modelManagerBridgeDownloadStatus.test.js b/test/helpers/modelManagerBridgeDownloadStatus.test.js
index dc56a7aab..cc8a4c6c1 100644
--- a/test/helpers/modelManagerBridgeDownloadStatus.test.js
+++ b/test/helpers/modelManagerBridgeDownloadStatus.test.js
@@ -4,15 +4,18 @@ const Module = require("node:module");
const fs = require("node:fs/promises");
const os = require("node:os");
const path = require("node:path");
+const vm = require("node:vm");
const modelRegistryData = require("../../src/models/modelRegistryData.json");
+const downloadUtils = require("../../src/helpers/downloadUtils");
+const LocalModelDownloadStatus = require("../../src/helpers/localModelDownloadStatus");
const originalLoad = Module._load;
const modelManagerModulePath = require.resolve("../../src/helpers/modelManagerBridge.js");
const modelDirUtilsModulePath = require.resolve("../../src/helpers/modelDirUtils.js");
let electronHome = os.tmpdir();
-function loadModelManager() {
+function loadModelManager({ downloadFile, checkDiskSpace } = {}) {
delete require.cache[modelManagerModulePath];
delete require.cache[modelDirUtilsModulePath];
@@ -28,21 +31,191 @@ function loadModelManager() {
};
}
+ if (request === "./downloadUtils" && parent?.filename === modelManagerModulePath) {
+ return {
+ ...downloadUtils,
+ ...(downloadFile ? { downloadFile } : {}),
+ ...(checkDiskSpace ? { checkDiskSpace } : {}),
+ };
+ }
+
return originalLoad.call(this, request, parent, isMain);
};
try {
// modelManagerBridge requires modelDirUtils lazily (inside getModelsDir),
- // after this mock is uninstalled — load it now so its electron binding is
- // the stub and modelsDir resolves inside the per-test temp home instead of
- // the real ~/.cache/openwhispr.
+ // after this mock is uninstalled. Load it with the Electron stub, then pin
+ // this manager to the test home so host XDG/OPENWHISPR cache overrides
+ // cannot expose real downloaded models to the test.
require("../../src/helpers/modelDirUtils.js");
- return require("../../src/helpers/modelManagerBridge.js").default;
+ const modelManager = require("../../src/helpers/modelManagerBridge.js").default;
+ modelManager.getModelsDir = () => path.join(electronHome, ".cache", "openwhispr", "models");
+ return modelManager;
} finally {
Module._load = originalLoad;
}
}
+async function loadModelDownloadHandler(modelManager) {
+ const source = await fs.readFile(require.resolve("../../src/helpers/ipcHandlers.js"), "utf8");
+ const start = source.indexOf(' ipcMain.handle("model-download",');
+ const end = source.indexOf(' ipcMain.handle("model-delete",', start);
+ assert.ok(start >= 0 && end > start, "the model-download handler must be registered");
+
+ const events = [];
+ const status = new LocalModelDownloadStatus();
+ const context = {
+ localModelDownloadStatus: status,
+ windowManager: {
+ sendToControlPanel(channel, data) {
+ events.push({ channel, ...data });
+ },
+ },
+ };
+ let handleDownload;
+ // Execute the production registration without booting unrelated Electron services.
+ vm.runInNewContext(`(function () { ${source.slice(start, end)} }).call(context)`, {
+ context,
+ ipcMain: {
+ handle(channel, handler) {
+ assert.equal(channel, "model-download");
+ handleDownload = handler;
+ },
+ },
+ require(request) {
+ assert.equal(request, "./modelManagerBridge");
+ return { default: modelManager };
+ },
+ });
+ return { handleDownload, events, status };
+}
+
+for (const outcome of ["cancel", "error", "complete"]) {
+ test(`the owning IPC request settles after ${outcome} when a duplicate arrives during preflight`, async (t) => {
+ const tmpHome = await fs.mkdtemp(path.join(os.tmpdir(), "openwhispr-ipc-owner-"));
+ electronHome = tmpHome;
+ const preflight = Promise.withResolvers();
+ const transferStarted = Promise.withResolvers();
+ const transferFinished = Promise.withResolvers();
+ const modelManager = loadModelManager({
+ checkDiskSpace: async () => ({ ok: true, availableBytes: Infinity }),
+ downloadFile: async (_url, destination, { signal, onProgress }) => {
+ signal.onAbort = () =>
+ transferFinished.reject(Object.assign(new Error("cancelled"), { isAbort: true }));
+ onProgress(420_000, 1_000_001);
+ transferStarted.resolve();
+ await transferFinished.promise;
+ await fs.writeFile(destination, Buffer.alloc(1_000_001));
+ },
+ });
+ const model = modelRegistryData.localProviders[0].models[0];
+ const checkModelValid = modelManager.checkModelValid.bind(modelManager);
+ let firstCheck = true;
+ modelManager.checkModelValid = async (modelPath) => {
+ if (firstCheck) {
+ firstCheck = false;
+ await preflight.promise;
+ }
+ return checkModelValid(modelPath);
+ };
+ const { handleDownload, events, status } = await loadModelDownloadHandler(modelManager);
+ const owner = handleDownload({}, model.id);
+ const duplicate = handleDownload({}, model.id);
+ t.after(async () => {
+ preflight.resolve();
+ transferFinished.resolve();
+ await Promise.allSettled([owner, duplicate]);
+ await fs.rm(tmpHome, { recursive: true, force: true });
+ });
+
+ const duplicateResult = await Promise.race([
+ duplicate,
+ transferStarted.promise.then(() => ({ code: "DUPLICATE_STARTED_TRANSFER" })),
+ ]);
+ assert.equal(duplicateResult.code, "DOWNLOAD_IN_PROGRESS");
+ assert.equal(duplicateResult.success, false);
+ assert.equal(status.getActiveDownloads().length, 1);
+ assert.equal(status.getActiveDownloads()[0].progress, 0);
+ assert.equal(events.length, 0);
+
+ preflight.resolve();
+ await transferStarted.promise;
+ assert.equal(status.getActiveDownloads()[0].downloadedBytes, 420_000);
+ const progressSequence = status.getActiveDownloads()[0].sequence;
+
+ if (outcome === "cancel") {
+ assert.equal(modelManager.cancelDownload(model.id), true);
+ assert.equal(status.has("llm", model.id), true);
+ } else if (outcome === "error") {
+ transferFinished.reject(new Error("connection lost"));
+ } else {
+ transferFinished.resolve();
+ }
+
+ const result = await owner;
+ assert.equal(result.success, outcome === "complete");
+ if (outcome !== "complete") {
+ assert.equal(result.code, outcome === "cancel" ? "DOWNLOAD_CANCELLED" : "NETWORK_ERROR");
+ }
+ assert.deepEqual(status.getActiveDownloads(), []);
+ assert.equal(modelManager.activeDownloads.size, 0);
+ assert.equal(modelManager.activeRequests.size, 0);
+ assert.equal(modelManager.downloadReservations.size, 0);
+ const terminalEvents = events.filter((event) => event.type !== "progress");
+ assert.equal(terminalEvents.length, 1);
+ assert.equal(terminalEvents[0].modelId, model.id);
+ assert.equal(terminalEvents[0].type, outcome === "complete" ? "complete" : "error");
+ assert.ok(terminalEvents[0].sequence > progressSequence);
+ });
+}
+
+test("the IPC registry permits distinct LLM transfers and settles them independently", async (t) => {
+ const tmpHome = await fs.mkdtemp(path.join(os.tmpdir(), "openwhispr-ipc-concurrent-"));
+ electronHome = tmpHome;
+ const [firstModel, secondModel] = modelRegistryData.localProviders[0].models;
+ const firstTransfer = Promise.withResolvers();
+ const secondTransfer = Promise.withResolvers();
+ const bothStarted = Promise.withResolvers();
+ let startedCount = 0;
+ const modelManager = loadModelManager({
+ checkDiskSpace: async () => ({ ok: true, availableBytes: Infinity }),
+ downloadFile: async (_url, destination, { onProgress }) => {
+ const transfer = destination.endsWith(firstModel.fileName) ? firstTransfer : secondTransfer;
+ onProgress(420_000, 1_000_001);
+ startedCount += 1;
+ if (startedCount === 2) bothStarted.resolve();
+ await transfer.promise;
+ await fs.writeFile(destination, Buffer.alloc(1_000_001));
+ },
+ });
+ const { handleDownload, events, status } = await loadModelDownloadHandler(modelManager);
+ const firstRequest = handleDownload({}, firstModel.id);
+ const secondRequest = handleDownload({}, secondModel.id);
+ t.after(async () => {
+ firstTransfer.resolve();
+ secondTransfer.resolve();
+ await Promise.allSettled([firstRequest, secondRequest]);
+ await fs.rm(tmpHome, { recursive: true, force: true });
+ });
+
+ await bothStarted.promise;
+ assert.equal(status.getActiveDownloads().length, 2);
+ firstTransfer.reject(new Error("connection lost"));
+ assert.equal((await firstRequest).code, "NETWORK_ERROR");
+ assert.equal(status.has("llm", firstModel.id), false);
+ assert.equal(status.has("llm", secondModel.id), true);
+ secondTransfer.resolve();
+ assert.equal((await secondRequest).success, true);
+ assert.deepEqual(status.getActiveDownloads(), []);
+ assert.deepEqual(
+ events.filter((event) => event.type !== "progress").map((event) => [event.modelId, event.type]),
+ [
+ [firstModel.id, "error"],
+ [secondModel.id, "complete"],
+ ]
+ );
+});
+
test("getAllModels surfaces in-flight local model download state", async (t) => {
const tmpHome = await fs.mkdtemp(path.join(os.tmpdir(), "openwhispr-model-status-"));
electronHome = tmpHome;
@@ -122,26 +295,139 @@ test("getAllModels retries when a download completes during filesystem checks",
assert.equal(completedModel.totalSize, 0);
});
-test("downloadModel rejects a second local model while another model is active", async (t) => {
+test("downloadModel permits distinct local models to download concurrently", 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;
+ const [firstModel, secondModel] = modelRegistryData.localProviders.flatMap(
+ (provider) => provider.models
+ );
+ const started = [];
+ let releaseDownloads;
+ const downloadsStarted = new Promise((resolve) => {
+ releaseDownloads = resolve;
+ });
+ let continueDownloads;
+ const allowDownloadsToFinish = new Promise((resolve) => {
+ continueDownloads = resolve;
+ });
+ const modelManager = loadModelManager({
+ downloadFile: async (_url, destination, options) => {
+ started.push(destination);
+ options.onProgress?.(1, 2);
+ if (started.length === 2) releaseDownloads();
+ await allowDownloadsToFinish;
+ await fs.writeFile(destination, Buffer.alloc(1_000_001));
+ },
+ });
- modelManager.activeDownloads.set(activeModel.id, true);
- t.after(() => {
- modelManager.activeDownloads.clear();
- modelManager.downloadProgress.clear();
+ const firstDownload = modelManager.downloadModel(firstModel.id);
+ const secondDownload = modelManager.downloadModel(secondModel.id);
+
+ await downloadsStarted;
+ assert.equal(modelManager.activeDownloads.has(firstModel.id), true);
+ assert.equal(modelManager.activeDownloads.has(secondModel.id), true);
+
+ continueDownloads();
+ await Promise.all([firstDownload, secondDownload]);
+});
+
+test("parallel downloads reserve their combined disk space", async (t) => {
+ const tmpHome = await fs.mkdtemp(path.join(os.tmpdir(), "openwhispr-disk-reservation-"));
+ electronHome = tmpHome;
+ t.after(() => fs.rm(tmpHome, { recursive: true, force: true }));
+
+ const [firstModel, secondModel] = modelRegistryData.localProviders
+ .flatMap((provider) => provider.models)
+ .filter((model) => !model.draftFileName)
+ .slice(0, 2);
+ const required = [firstModel, secondModel].map(
+ (model) => (model.sizeBytes || model.sizeMb * 1_000_000) * 1.2
+ );
+ const availableBytes = Math.max(...required) + 1;
+ let releaseFirst;
+ const firstCanFinish = new Promise((resolve) => {
+ releaseFirst = resolve;
+ });
+ let firstStarted;
+ const firstDidStart = new Promise((resolve) => {
+ firstStarted = resolve;
+ });
+ const modelManager = loadModelManager({
+ checkDiskSpace: async (_directory, requiredBytes) => ({
+ ok: requiredBytes <= availableBytes,
+ availableBytes,
+ }),
+ downloadFile: async (_url, destination) => {
+ firstStarted();
+ await firstCanFinish;
+ await fs.writeFile(destination, Buffer.alloc(1_000_001));
+ },
+ });
+
+ const firstDownload = modelManager.downloadModel(firstModel.id);
+ await firstDidStart;
+ await assert.rejects(
+ modelManager.downloadModel(secondModel.id),
+ (error) => error.code === "INSUFFICIENT_DISK_SPACE"
+ );
+
+ releaseFirst();
+ await firstDownload;
+ assert.equal(modelManager.downloadReservations.size, 0);
+});
+
+test("cancelling an optional drafter does not complete the model download", async (t) => {
+ const tmpHome = await fs.mkdtemp(path.join(os.tmpdir(), "openwhispr-drafter-cancel-"));
+ electronHome = tmpHome;
+ t.after(() => fs.rm(tmpHome, { recursive: true, force: true }));
+
+ let downloadCount = 0;
+ const modelManager = loadModelManager({
+ checkDiskSpace: async () => ({ ok: true, availableBytes: Number.MAX_SAFE_INTEGER }),
+ downloadFile: async (_url, destination) => {
+ downloadCount += 1;
+ if (downloadCount === 1) {
+ await fs.writeFile(destination, Buffer.alloc(1_000_001));
+ return;
+ }
+ const error = new Error("cancelled");
+ error.isAbort = true;
+ throw error;
+ },
});
+ const model = modelRegistryData.localProviders
+ .flatMap((provider) => provider.models)
+ .find((candidate) => candidate.draftFileName);
await assert.rejects(
- modelManager.downloadModel(requestedModel.id),
- (error) =>
- error.code === "DOWNLOAD_IN_PROGRESS" &&
- error.details.modelId === requestedModel.id &&
- error.details.activeModelId === activeModel.id
+ modelManager.downloadModel(model.id),
+ (error) => error.code === "DOWNLOAD_CANCELLED"
+ );
+ assert.equal(
+ await modelManager.checkFileExists(path.join(modelManager.modelsDir, model.fileName)),
+ true
+ );
+ assert.equal(
+ await modelManager.checkFileExists(path.join(modelManager.modelsDir, model.draftFileName)),
+ false
+ );
+});
+
+test("downloadModel rejects a duplicate local model download", async (t) => {
+ const tmpHome = await fs.mkdtemp(path.join(os.tmpdir(), "openwhispr-duplicate-download-"));
+ electronHome = tmpHome;
+ t.after(() => fs.rm(tmpHome, { recursive: true, force: true }));
+
+ const modelManager = loadModelManager();
+ const model = modelRegistryData.localProviders[0].models[0];
+ modelManager.activeDownloads.set(model.id, true);
+ t.after(() => modelManager.activeDownloads.clear());
+
+ await assert.rejects(
+ modelManager.downloadModel(model.id),
+ (error) => error.code === "DOWNLOAD_IN_PROGRESS" && error.details.modelId === model.id
);
});
@@ -151,10 +437,13 @@ test("cancelDownload keeps the local LLM guard until the request unwinds", async
t.after(() => fs.rm(tmpHome, { recursive: true, force: true }));
const modelManager = loadModelManager();
- const model = modelRegistryData.localProviders[0].models[0];
+ const [model, otherModel] = modelRegistryData.localProviders.flatMap(
+ (provider) => provider.models
+ );
let aborted = false;
modelManager.activeDownloads.set(model.id, true);
+ modelManager.activeDownloads.set(otherModel.id, true);
modelManager.activeRequests.set(model.id, {
abort() {
aborted = true;
@@ -166,6 +455,13 @@ test("cancelDownload keeps the local LLM guard until the request unwinds", async
downloadedSize: 420,
totalSize: 1000,
});
+ modelManager.activeRequests.set(otherModel.id, { abort() {} });
+ modelManager.downloadProgress.set(otherModel.id, {
+ modelId: otherModel.id,
+ progress: 24,
+ downloadedSize: 240,
+ totalSize: 1000,
+ });
t.after(() => {
modelManager.activeDownloads.clear();
modelManager.activeRequests.clear();
@@ -177,4 +473,7 @@ test("cancelDownload keeps the local LLM guard until the request unwinds", async
assert.equal(modelManager.activeDownloads.has(model.id), true);
assert.equal(modelManager.activeRequests.has(model.id), true);
assert.equal(modelManager.downloadProgress.has(model.id), true);
+ assert.equal(modelManager.activeDownloads.has(otherModel.id), true);
+ assert.equal(modelManager.activeRequests.has(otherModel.id), true);
+ assert.equal(modelManager.downloadProgress.has(otherModel.id), true);
});
diff --git a/test/helpers/pendingLocalModels.test.js b/test/helpers/pendingLocalModels.test.js
index 074b36d4e..1f8ed1f66 100644
--- a/test/helpers/pendingLocalModels.test.js
+++ b/test/helpers/pendingLocalModels.test.js
@@ -47,17 +47,18 @@ test("a completion cannot consume a different pending model", async () => {
test("pending selections can be cleared when onboarding finishes on another mode", async () => {
global.localStorage = createStorage();
const pending = await import("../../src/components/onboarding/pendingLocalModels.ts");
+ const selection = { provider: "whisper", modelId: "base" };
- pending.rememberPendingLocalModel("dictation", { provider: "whisper", modelId: "base" });
+ pending.rememberPendingLocalModel("dictation", selection);
pending.rememberPendingLocalModel("assistant", {
provider: "qwen",
modelId: "qwen3.5-4b-q4_k_m",
});
-
pending.clearPendingLocalModels();
assert.deepEqual(pending.readPendingLocalModels(), {});
assert.equal(pending.hasPendingLocalModels(), false);
+ assert.equal(pending.isPendingLocalModel("dictation", selection), false);
});
test("pending local model availability distinguishes active, installed, and orphaned models", async () => {
diff --git a/test/hooks/modelDownloadErrors.test.js b/test/hooks/modelDownloadErrors.test.js
new file mode 100644
index 000000000..160755f95
--- /dev/null
+++ b/test/hooks/modelDownloadErrors.test.js
@@ -0,0 +1,384 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const React = require("react");
+const { createRoot } = require("react-dom/client");
+const {
+ createRendererServer,
+ installBrowserGlobals,
+ installHookDom,
+} = require("../lib/rendererTestHarness");
+
+function deferred() {
+ let resolve;
+ const promise = new Promise((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+async function createDownloadRenderer(t, electronAPI) {
+ let root = null;
+ t.after(async () => {
+ if (root) await React.act(async () => root.unmount());
+ });
+ installBrowserGlobals(t, {
+ window: { electronAPI, dispatchEvent() {} },
+ });
+ const container = installHookDom(t);
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-model-download-errors-",
+ noExternal: ["react-i18next"],
+ mockModules: {
+ "react-i18next": `
+ const t = (key) => key;
+ export function useTranslation() { return { t }; }
+ `,
+ "/components/ui/useToast": `
+ const context = { toast() {} };
+ export function useToast() { return context; }
+ `,
+ "/stores/settingsStore": `
+ export function clearMissingLocalModelSelections() {}
+ export function isCloudCleanupMode() { return false; }
+ export function getSettings() { return {}; }
+ `,
+ "/ProviderSetupStep": `export const SETUP_CARD_CLASS = "";`,
+ "/ui/ProviderIcon": `export function ProviderIcon() { return null; }`,
+ },
+ });
+ return {
+ vite,
+ async render(Component) {
+ root ??= createRoot(container);
+ await React.act(async () => root.render(React.createElement(Component)));
+ },
+ async unmount() {
+ await React.act(async () => root.unmount());
+ root = null;
+ },
+ };
+}
+
+function findRetryButtons(children) {
+ return React.Children.toArray(children).flatMap((child) => {
+ if (!React.isValidElement(child)) return [];
+ const matches = child.props.children === "common.retry" ? [child] : [];
+ return [...matches, ...findRetryButtons(child.props.children)];
+ });
+}
+
+test("required models with identical errors wait for explicit retry independently", async (t) => {
+ const tinyResponse = deferred();
+ const baseResponse = deferred();
+ const retryResponse = deferred();
+ const tinyRefresh = deferred();
+ const baseRefresh = deferred();
+ const requests = [];
+ let refreshCount = 0;
+ const renderer = await createDownloadRenderer(t, {
+ onWhisperDownloadProgress: () => () => {},
+ onParakeetDownloadProgress: () => () => {},
+ modelGetActiveDownloads: async () => [],
+ downloadWhisperModel(modelId) {
+ requests.push(modelId);
+ if (modelId === "tiny") return tinyResponse.promise;
+ return requests.length === 2 ? baseResponse.promise : retryResponse.promise;
+ },
+ });
+ const { RequiredModelDownloadStep } = await renderer.vite.ssrLoadModule(
+ "/components/onboarding/RequiredModelDownloadStep.tsx"
+ );
+ const required = ["tiny", "base"];
+ const props = {
+ required,
+ missing: required,
+ loading: false,
+ refresh: () => (++refreshCount === 1 ? tinyRefresh.promise : baseRefresh.promise),
+ onProceed() {},
+ };
+ let tree;
+ function Harness() {
+ tree = RequiredModelDownloadStep(props);
+ return null;
+ }
+ await renderer.render(Harness);
+ assert.deepEqual(requests, ["tiny"]);
+
+ const failure = { success: false, code: "ENOTFOUND", error: "ENOTFOUND" };
+ await React.act(async () => tinyResponse.resolve(failure));
+ await React.act(async () => tinyRefresh.resolve());
+ assert.deepEqual(requests, ["tiny", "base"]);
+
+ await React.act(async () => baseResponse.resolve(failure));
+ await React.act(async () => baseRefresh.resolve());
+ assert.deepEqual(requests, ["tiny", "base"], "failed downloads must not restart automatically");
+ const retryButtons = findRetryButtons(tree);
+ assert.equal(retryButtons.length, 2, "each failed model needs its own Retry control");
+
+ await React.act(async () => retryButtons[1].props.onClick());
+ assert.deepEqual(requests, ["tiny", "base", "base"]);
+ assert.equal(findRetryButtons(tree).length, 1, "retrying base preserves tiny's failure");
+
+ await React.act(async () => retryResponse.resolve(failure));
+ assert.deepEqual(requests, ["tiny", "base", "base"]);
+ assert.equal(findRetryButtons(tree).length, 2);
+});
+
+test("remount restores concurrent LLM downloads and cancellation settles only its model", async (t) => {
+ let activeDownloads = [
+ {
+ modelType: "llm",
+ modelId: "model-a",
+ phase: "downloading",
+ progress: 20,
+ downloadedBytes: 200,
+ totalBytes: 1000,
+ sequence: 1,
+ },
+ {
+ modelType: "llm",
+ modelId: "model-b",
+ phase: "downloading",
+ progress: 30,
+ downloadedBytes: 300,
+ totalBytes: 1000,
+ sequence: 2,
+ },
+ ];
+ const listeners = new Set();
+ const cancellations = [];
+ let refreshes = 0;
+ const renderer = await createDownloadRenderer(t, {
+ modelGetActiveDownloads: async () => activeDownloads,
+ onModelDownloadProgress(listener) {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ async modelCancelDownload(modelId) {
+ cancellations.push(modelId);
+ return { success: true };
+ },
+ });
+ const { useModelDownload } = await renderer.vite.ssrLoadModule("/hooks/useModelDownload.ts");
+ let download;
+ function Harness() {
+ download = useModelDownload({
+ modelType: "llm",
+ onDownloadComplete() {
+ refreshes += 1;
+ },
+ });
+ return null;
+ }
+
+ await renderer.render(Harness);
+ assert.deepEqual(Object.keys(download.downloads), ["model-a", "model-b"]);
+ await renderer.unmount();
+ assert.equal(listeners.size, 0);
+
+ activeDownloads = [
+ { ...activeDownloads[0], progress: 40, downloadedBytes: 400, sequence: 3 },
+ { ...activeDownloads[1], progress: 50, downloadedBytes: 500, sequence: 4 },
+ ];
+ await renderer.render(Harness);
+ assert.equal(download.downloads["model-a"].progress, 40);
+ assert.equal(download.downloads["model-b"].progress, 50);
+
+ await React.act(async () => download.cancelDownload("model-a"));
+ assert.deepEqual(cancellations, ["model-a"]);
+ assert.equal(download.isCancellingModel("model-a"), true);
+ assert.equal(download.isCancellingModel("model-b"), false);
+
+ await React.act(async () => {
+ for (const listener of listeners) {
+ listener(null, {
+ type: "error",
+ modelId: "model-a",
+ error: "Download cancelled by user",
+ code: "DOWNLOAD_CANCELLED",
+ sequence: 5,
+ });
+ }
+ });
+ assert.deepEqual(Object.keys(download.downloads), ["model-b"]);
+ assert.equal(download.isCancellingModel("model-a"), false);
+ assert.deepEqual(download.downloadErrors, {});
+
+ await React.act(async () => {
+ for (const listener of listeners) {
+ listener(null, { type: "complete", modelId: "model-b", progress: 100, sequence: 6 });
+ }
+ });
+ assert.equal(download.isDownloading, false);
+ assert.equal(refreshes, 2);
+});
+
+test("a failed required download waits for Retry when failure arrives during duplicate recovery", async (t) => {
+ const duplicateResponse = deferred();
+ const recoverySnapshot = deferred();
+ const retryResponse = deferred();
+ const requests = [];
+ let snapshotCalls = 0;
+ let progressListener;
+ const renderer = await createDownloadRenderer(t, {
+ onWhisperDownloadProgress(listener) {
+ progressListener = listener;
+ return () => {};
+ },
+ onParakeetDownloadProgress: () => () => {},
+ modelGetActiveDownloads() {
+ return ++snapshotCalls <= 2 ? Promise.resolve([]) : recoverySnapshot.promise;
+ },
+ downloadWhisperModel(modelId) {
+ requests.push(modelId);
+ return requests.length === 1 ? duplicateResponse.promise : retryResponse.promise;
+ },
+ });
+ const { RequiredModelDownloadStep } = await renderer.vite.ssrLoadModule(
+ "/components/onboarding/RequiredModelDownloadStep.tsx"
+ );
+ const props = {
+ required: ["tiny"],
+ missing: ["tiny"],
+ loading: false,
+ refresh: async () => {},
+ onProceed() {},
+ };
+ let tree;
+ function Harness() {
+ tree = RequiredModelDownloadStep(props);
+ return null;
+ }
+ await renderer.render(Harness);
+ assert.deepEqual(requests, ["tiny"]);
+
+ await React.act(async () =>
+ duplicateResponse.resolve({ success: false, code: "DOWNLOAD_IN_PROGRESS" })
+ );
+ assert.equal(snapshotCalls, 3);
+ // The original transfer fails before the second IPC request reaches main.
+ await React.act(async () => {
+ progressListener(null, {
+ model: "tiny",
+ type: "error",
+ error: "ENOTFOUND",
+ code: "ENOTFOUND",
+ sequence: 2,
+ });
+ });
+ await React.act(async () => recoverySnapshot.resolve([]));
+
+ assert.deepEqual(requests, ["tiny"], "failure must not trigger an automatic retry");
+ const retryButtons = findRetryButtons(tree);
+ assert.equal(retryButtons.length, 1);
+ await React.act(async () => retryButtons[0].props.onClick());
+ assert.deepEqual(requests, ["tiny", "tiny"]);
+ await React.act(async () =>
+ retryResponse.resolve({ success: false, error: "ENOTFOUND", code: "ENOTFOUND" })
+ );
+});
+
+for (const outcome of ["error", "complete", "cancel"]) {
+ test(`LLM duplicate recovery preserves ${outcome} before an empty snapshot`, async (t) => {
+ const duplicateResponse = deferred();
+ const recoverySnapshot = deferred();
+ let snapshotCalls = 0;
+ let progressListener;
+ let refreshes = 0;
+ let selections = 0;
+ const renderer = await createDownloadRenderer(t, {
+ onModelDownloadProgress(listener) {
+ progressListener = listener;
+ return () => {};
+ },
+ modelGetActiveDownloads() {
+ return ++snapshotCalls === 1 ? Promise.resolve([]) : recoverySnapshot.promise;
+ },
+ modelDownload: () => duplicateResponse.promise,
+ });
+ const { useModelDownload } = await renderer.vite.ssrLoadModule("/hooks/useModelDownload.ts");
+ let download;
+ function Harness() {
+ download = useModelDownload({
+ modelType: "llm",
+ onDownloadComplete() {
+ refreshes += 1;
+ },
+ });
+ return null;
+ }
+ await renderer.render(Harness);
+ let request;
+ await React.act(async () => {
+ request = download.downloadModel("model-a", () => {
+ selections += 1;
+ });
+ });
+ await React.act(async () =>
+ duplicateResponse.resolve({ success: false, code: "DOWNLOAD_IN_PROGRESS" })
+ );
+ assert.equal(snapshotCalls, 2);
+ await React.act(async () => {
+ progressListener(
+ null,
+ outcome === "complete"
+ ? { modelId: "model-a", type: "complete", progress: 100, sequence: 2 }
+ : {
+ modelId: "model-a",
+ type: "error",
+ error: outcome === "cancel" ? "Download cancelled by user" : "ENOTFOUND",
+ code: outcome === "cancel" ? "DOWNLOAD_CANCELLED" : "ENOTFOUND",
+ sequence: 2,
+ }
+ );
+ });
+ await React.act(async () => {
+ recoverySnapshot.resolve([]);
+ await request;
+ });
+ assert.equal(download.isDownloading, false);
+ assert.equal(
+ download.downloadError,
+ outcome === "error" ? "hooks.modelDownload.errors.notFound" : null
+ );
+ assert.equal(refreshes, 1);
+ assert.equal(selections, 0, "a refused request must not take over model selection");
+ });
+}
+
+for (const modelType of ["whisper", "parakeet", "llm"]) {
+ test(`${modelType} duplicate recovery ${modelType === "llm" ? "keeps exact model ownership" : "restores the active family model"}`, async (t) => {
+ let snapshotCalls = 0;
+ const subscribe = () => () => {};
+ const refuseDownload = async () => ({ success: false, code: "DOWNLOAD_IN_PROGRESS" });
+ const active = {
+ modelType,
+ modelId: "active-model",
+ phase: "downloading",
+ progress: 42,
+ downloadedBytes: 420,
+ totalBytes: 1000,
+ sequence: 2,
+ };
+ const renderer = await createDownloadRenderer(t, {
+ onWhisperDownloadProgress: subscribe,
+ onParakeetDownloadProgress: subscribe,
+ onModelDownloadProgress: subscribe,
+ modelGetActiveDownloads: async () => (++snapshotCalls === 1 ? [] : [active]),
+ downloadWhisperModel: refuseDownload,
+ downloadParakeetModel: refuseDownload,
+ modelDownload: refuseDownload,
+ });
+ const { useModelDownload } = await renderer.vite.ssrLoadModule("/hooks/useModelDownload.ts");
+ let download;
+ function Harness() {
+ download = useModelDownload({ modelType });
+ return null;
+ }
+ await renderer.render(Harness);
+ await React.act(async () => download.downloadModel("requested-model"));
+ assert.equal(download.isDownloadingModel("requested-model"), false);
+ assert.equal(download.downloadingModel, modelType === "llm" ? null : "active-model");
+ if (modelType !== "llm") assert.equal(download.downloadProgress.percentage, 42);
+ });
+}