Skip to content

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

refactor: migrate to whisper.cpp with WebM-to-WAV conversion, add download cancellation, streamline onboarding flow, and fix button styling consistency

Gabriel Stein72af3e0f9a89
diff --git a/src/components/LocalModelPicker.tsx b/src/components/LocalModelPicker.tsx
index df5865157..a95580046 100644
--- a/src/components/LocalModelPicker.tsx
+++ b/src/components/LocalModelPicker.tsx
@@ -162,7 +162,7 @@ export default function LocalModelPicker({
variant="outline"
size="sm"
disabled={loadingModels}
- className={styles.buttons.refresh}
+ className={`${styles.buttons.refresh} min-w-[105px] transition-colors`}
>
<RefreshCw size={14} className={loadingModels ? "animate-spin" : ""} />
<span className="ml-1">{loadingModels ? "Checking..." : "Refresh"}</span>
diff --git a/src/components/LocalWhisperPicker.tsx b/src/components/LocalWhisperPicker.tsx
index 855365fee..318e41308 100644
--- a/src/components/LocalWhisperPicker.tsx
+++ b/src/components/LocalWhisperPicker.tsx
@@ -1,8 +1,9 @@
-import { useState, useEffect, useCallback, useMemo } from "react";
+import { useState, useEffect, useCallback, useMemo, useRef } from "react";
import { Button } from "./ui/button";
-import { RefreshCw, Download, Trash2, Check } from "lucide-react";
+import { RefreshCw, Download, Trash2, Check, X } from "lucide-react";
import { ProviderIcon } from "./ui/ProviderIcon";
import { DownloadProgressBar } from "./ui/DownloadProgressBar";
+import { ConfirmDialog } from "./ui/dialog";
import { useDialogs } from "../hooks/useDialogs";
import { useModelDownload } from "../hooks/useModelDownload";
import { WHISPER_MODEL_INFO } from "../models/ModelRegistry";
@@ -17,6 +18,7 @@ interface WhisperModel {
interface LocalWhisperPickerProps {
selectedModel: string;
onModelSelect: (modelId: string) => void;
+ onModelDownloaded?: (modelId: string) => void;
className?: string;
variant?: "onboarding" | "settings";
}
@@ -24,13 +26,16 @@ interface LocalWhisperPickerProps {
export default function LocalWhisperPicker({
selectedModel,
onModelSelect,
+ onModelDownloaded,
className = "",
variant = "settings",
}: LocalWhisperPickerProps) {
const [models, setModels] = useState<WhisperModel[]>([]);
const [loadingModels, setLoadingModels] = useState(false);
+ const hasLoadedRef = useRef(false);
+ const downloadingModelRef = useRef<string | null>(null);
- const { showConfirmDialog } = useDialogs();
+ const { confirmDialog, showConfirmDialog, hideConfirmDialog } = useDialogs();
const colorScheme: ColorScheme = variant === "settings" ? "purple" : "blue";
const styles = useMemo(() => MODEL_PICKER_COLORS[colorScheme], [colorScheme]);
@@ -49,16 +54,38 @@ export default function LocalWhisperPicker({
}
}, []);
+ // Only load models once on mount to prevent re-renders
useEffect(() => {
- loadModels();
+ if (!hasLoadedRef.current) {
+ hasLoadedRef.current = true;
+ loadModels();
+ }
}, [loadModels]);
- const { downloadingModel, downloadProgress, downloadModel, deleteModel, isDownloadingModel } =
- useModelDownload({
- modelType: "whisper",
- onDownloadComplete: loadModels,
- onModelsCleared: loadModels,
- });
+ const {
+ downloadingModel,
+ downloadProgress,
+ downloadModel,
+ deleteModel,
+ isDownloadingModel,
+ cancelDownload,
+ isCancelling,
+ } = useModelDownload({
+ modelType: "whisper",
+ onDownloadComplete: () => {
+ loadModels();
+ // Notify parent when a model is downloaded (use ref to avoid stale closure)
+ if (downloadingModelRef.current && onModelDownloaded) {
+ onModelDownloaded(downloadingModelRef.current);
+ }
+ },
+ onModelsCleared: loadModels,
+ });
+
+ // Keep ref in sync with downloadingModel to avoid stale closure in onDownloadComplete
+ useEffect(() => {
+ downloadingModelRef.current = downloadingModel;
+ }, [downloadingModel]);
const handleDelete = useCallback(
(modelId: string) => {
@@ -96,10 +123,10 @@ export default function LocalWhisperPicker({
variant="outline"
size="sm"
disabled={loadingModels}
- className={styles.buttons.refresh}
+ className={`${styles.buttons.refresh} min-w-[105px] justify-center transition-colors`}
>
<RefreshCw size={14} className={loadingModels ? "animate-spin" : ""} />
- <span className="ml-1">{loadingModels ? "Checking..." : "Refresh"}</span>
+ <span>{loadingModels ? "Checking..." : "Refresh"}</span>
</Button>
</div>
@@ -169,21 +196,25 @@ export default function LocalWhisperPicker({
<span className="ml-1">Delete</span>
</Button>
</>
+ ) : isDownloading ? (
+ <Button
+ onClick={cancelDownload}
+ disabled={isCancelling}
+ size="sm"
+ variant="outline"
+ className="text-red-600 border-red-300 hover:bg-red-50"
+ >
+ <X size={14} />
+ <span className="ml-1">{isCancelling ? "..." : "Cancel"}</span>
+ </Button>
) : (
<Button
onClick={() => downloadModel(modelId, onModelSelect)}
size="sm"
- disabled={isDownloading}
className={styles.buttons.download}
>
- {isDownloading ? (
- `${Math.round(downloadProgress.percentage)}%`
- ) : (
- <>
- <Download size={14} />
- <span className="ml-1">Download</span>
- </>
- )}
+ <Download size={14} />
+ <span className="ml-1">Download</span>
</Button>
)}
</div>
@@ -193,6 +224,17 @@ export default function LocalWhisperPicker({
})}
</div>
</div>
+
+ <ConfirmDialog
+ open={confirmDialog.open}
+ onOpenChange={(open) => !open && hideConfirmDialog()}
+ title={confirmDialog.title}
+ description={confirmDialog.description}
+ confirmText={confirmDialog.confirmText}
+ cancelText={confirmDialog.cancelText}
+ onConfirm={confirmDialog.onConfirm}
+ variant={confirmDialog.variant}
+ />
</div>
);
}
diff --git a/src/components/OnboardingFlow.tsx b/src/components/OnboardingFlow.tsx
index 95cedaf8b..d0aeb4241 100644
--- a/src/components/OnboardingFlow.tsx
+++ b/src/components/OnboardingFlow.tsx
@@ -12,7 +12,6 @@ import {
Key,
Shield,
Command,
- TestTube,
Sparkles,
Lock,
User,
@@ -88,6 +87,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
const [transcriptionBaseUrl, setTranscriptionBaseUrl] = useState(cloudTranscriptionBaseUrl);
const [reasoningBaseUrl, setReasoningBaseUrl] = useState(cloudReasoningBaseUrl);
const [agentName, setAgentName] = useState("Agent");
+ const [isModelDownloaded, setIsModelDownloaded] = useState(false);
const readableHotkey = formatHotkeyLabel(hotkey);
const {
alertDialog,
@@ -318,18 +318,36 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
{ title: "Privacy", icon: Lock },
{ title: "Setup", icon: Settings },
{ title: "Permissions", icon: Shield },
- { title: "Hotkey", icon: Command },
- { title: "Test", icon: TestTube },
+ { title: "Hotkey & Test", icon: Command },
{ title: "Agent Name", icon: User },
- { title: "Finish", icon: Check },
];
const updateProcessingMode = (useLocal: boolean) => {
updateTranscriptionSettings({ useLocalWhisper: useLocal });
};
+ // Check if selected whisper model is downloaded
useEffect(() => {
- if (currentStep === 5) {
+ if (!useLocalWhisper || !whisperModel) {
+ setIsModelDownloaded(false);
+ return;
+ }
+
+ const checkModelStatus = async () => {
+ try {
+ const result = await window.electronAPI?.checkModelStatus(whisperModel);
+ setIsModelDownloaded(result?.downloaded ?? false);
+ } catch (error) {
+ console.error("Failed to check model status:", error);
+ setIsModelDownloaded(false);
+ }
+ };
+
+ checkModelStatus();
+ }, [useLocalWhisper, whisperModel]);
+
+ useEffect(() => {
+ if (currentStep === 4) {
if (practiceTextareaRef.current) {
practiceTextareaRef.current.focus();
}
@@ -466,36 +484,19 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
const newStep = currentStep + 1;
- if (currentStep === 4) {
- const registered = await ensureHotkeyRegistered();
- if (!registered) {
- return;
- }
- setDictationKey(hotkey);
- }
if (currentStep === 2 && !useLocalWhisper) {
await persistOpenAIKey(apiKey);
}
setCurrentStep(newStep);
- // Show dictation panel when moving from permissions step (3) to hotkey step (4)
+ // Show dictation panel when moving from permissions step (3) to hotkey & test step (4)
if (currentStep === 3 && newStep === 4) {
if (window.electronAPI?.showDictationPanel) {
window.electronAPI.showDictationPanel();
}
}
- }, [
- currentStep,
- ensureHotkeyRegistered,
- hotkey,
- setCurrentStep,
- setDictationKey,
- steps.length,
- useLocalWhisper,
- persistOpenAIKey,
- apiKey,
- ]);
+ }, [currentStep, setCurrentStep, steps.length, useLocalWhisper, persistOpenAIKey, apiKey]);
const prevStep = useCallback(() => {
if (currentStep > 0) {
@@ -595,6 +596,10 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
<LocalWhisperPicker
selectedModel={whisperModel}
onModelSelect={setWhisperModel}
+ onModelDownloaded={(modelId) => {
+ setIsModelDownloaded(true);
+ setWhisperModel(modelId);
+ }}
variant="onboarding"
/>
</div>
@@ -800,14 +805,12 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
</div>
);
- case 4: // Choose Hotkey
+ case 4: // Hotkey & Test (combined)
return (
<div className="space-y-6">
<div className="text-center">
- <h2 className="text-2xl font-bold text-gray-900 mb-2">Choose Your Hotkey</h2>
- <p className="text-gray-600">
- Set the key combination you'll use to start and stop dictation
- </p>
+ <h2 className="text-2xl font-bold text-gray-900 mb-2">Set Your Hotkey & Test</h2>
+ <p className="text-gray-600">Choose your hotkey and try it out</p>
</div>
<HotkeyInput
@@ -820,89 +823,43 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
}}
disabled={isHotkeyRegistering}
/>
- </div>
- );
- case 5: // Test & Practice
- return (
- <div className="space-y-6">
- <div className="text-center">
- <h2 className="text-2xl font-bold text-stone-900 mb-2">Test & Practice</h2>
- <p className="text-stone-600">Let's test your setup and practice using OpenWhispr</p>
+ <div className="bg-blue-50/50 p-5 rounded-lg border border-blue-200/60">
+ <h3 className="font-semibold text-blue-900 mb-3">Try It Now</h3>
+ <p className="text-sm text-blue-800 mb-3">
+ Click in the text area, press{" "}
+ <kbd className="bg-white px-2 py-1 rounded text-xs font-mono border border-blue-200">
+ {readableHotkey}
+ </kbd>{" "}
+ to start recording, speak, then press it again to stop.
+ </p>
+
+ <div>
+ <label className="block text-sm font-medium text-stone-700 mb-2">
+ Test your dictation:
+ </label>
+ <Textarea rows={3} placeholder="Click here, then use your hotkey to dictate..." />
+ </div>
</div>
- <div className="space-y-6">
- <div className="bg-blue-50/50 p-6 rounded-lg border border-blue-200/60">
- <h3 className="font-semibold text-blue-900 mb-3">Practice with Your Hotkey</h3>
- <p className="text-sm text-blue-800 mb-4">
- <strong>Step 1:</strong> Click in the text area below to place your cursor there.
- <br />
- <strong>Step 2:</strong> Press{" "}
- <kbd className="bg-white px-2 py-1 rounded text-xs font-mono border border-blue-200">
- {readableHotkey}
- </kbd>{" "}
- to start recording, then speak something.
- <br />
- <strong>Step 3:</strong> Press{" "}
- <kbd className="bg-white px-2 py-1 rounded text-xs font-mono border border-blue-200">
+ <div className="bg-green-50/50 p-4 rounded-lg border border-green-200/60">
+ <h4 className="font-medium text-green-900 mb-2">How it works:</h4>
+ <ol className="text-sm text-green-800 space-y-1">
+ <li>1. Click in any text field</li>
+ <li>
+ 2. Press{" "}
+ <kbd className="bg-white px-1 py-0.5 rounded text-xs font-mono border border-green-200">
{readableHotkey}
</kbd>{" "}
- again to stop and see your transcribed text appear where your cursor is!
- </p>
-
- <div className="space-y-4">
- <div className="text-center">
- <div className="flex items-center justify-center gap-2 text-stone-600">
- <Mic className="w-4 h-4" />
- <span>
- Click in the text area below, then press{" "}
- <kbd className="bg-white px-1 py-0.5 rounded text-xs font-mono border">
- {readableHotkey}
- </kbd>{" "}
- to start dictation
- </span>
- </div>
- </div>
-
- <div>
- <label className="block text-sm font-medium text-stone-700 mb-2">
- Transcribed Text:
- </label>
- <Textarea
- rows={4}
- placeholder="Click here to place your cursor, then use your hotkey to start dictation..."
- />
- </div>
- </div>
- </div>
-
- <div className="bg-green-50/50 p-4 rounded-lg border border-green-200/60">
- <h4 className="font-medium text-green-900 mb-2">πŸ’‘ How to use OpenWhispr:</h4>
- <ol className="text-sm text-green-800 space-y-1">
- <li>1. Click in any text field (email, document, etc.)</li>
- <li>
- 2. Press{" "}
- <kbd className="bg-white px-2 py-1 rounded text-xs font-mono border border-green-200">
- {readableHotkey}
- </kbd>{" "}
- to start recording
- </li>
- <li>3. Speak your text clearly</li>
- <li>
- 4. Press{" "}
- <kbd className="bg-white px-2 py-1 rounded text-xs font-mono border border-green-200">
- {readableHotkey}
- </kbd>{" "}
- again to stop
- </li>
- <li>5. Your text will automatically appear where you were typing!</li>
- </ol>
- </div>
+ to start, speak, press again to stop
+ </li>
+ <li>3. Your text appears automatically!</li>
+ </ol>
</div>
</div>
);
- case 6: // Agent Name
+ case 5: // Agent Name (final step)
return (
<div className="space-y-6">
<div className="text-center">
@@ -913,7 +870,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
</div>
<div className="space-y-4 p-4 bg-gradient-to-r from-purple-50 to-blue-50 border border-purple-200 rounded-xl">
- <h4 className="font-medium text-purple-900 mb-3">πŸ’‘ How this helps:</h4>
+ <h4 className="font-medium text-purple-900 mb-3">How this helps:</h4>
<ul className="text-sm text-purple-800 space-y-1">
<li>
β€’ Say "Hey {agentName || "Agent"}, write a formal email" for specific instructions
@@ -936,73 +893,6 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
</div>
);
- case 7: // Complete
- return (
- <div className="text-center space-y-6">
- <div className="w-16 h-16 mx-auto bg-green-100 rounded-full flex items-center justify-center">
- <Check className="w-8 h-8 text-green-600" />
- </div>
- <div>
- <h2 className="text-2xl font-bold text-gray-900 mb-2">You're All Set!</h2>
- <p className="text-gray-600">OpenWhispr is now configured and ready to use.</p>
- </div>
-
- <div className="bg-gradient-to-r from-indigo-50 to-purple-50 p-6 rounded-lg">
- <h3 className="font-semibold text-gray-900 mb-3">Your Setup Summary:</h3>
- <div className="space-y-2 text-sm">
- <div className="flex justify-between">
- <span>Processing:</span>
- <span className="font-medium">
- {useLocalWhisper ? `Local (${whisperModel})` : "OpenAI Cloud"}
- </span>
- </div>
- {!useLocalWhisper && (
- <div className="flex justify-between">
- <span>Reasoning Model:</span>
- <span className="font-medium">{activeReasoningModelLabel}</span>
- </div>
- )}
- {!useLocalWhisper && hasEnteredReasoningBase && (
- <div className="flex justify-between">
- <span>Custom Endpoint:</span>
- <span className="font-medium break-all">
- {normalizedReasoningBaseUrl || trimmedReasoningBase}
- </span>
- </div>
- )}
- <div className="flex justify-between">
- <span>Hotkey:</span>
- <kbd className="bg-white px-2 py-1 rounded text-xs font-mono">{hotkey}</kbd>
- </div>
- <div className="flex justify-between">
- <span>Language:</span>
- <span className="font-medium">{getLanguageLabel(preferredLanguage)}</span>
- </div>
- <div className="flex justify-between">
- <span>Agent Name:</span>
- <span className="font-medium">{agentName}</span>
- </div>
- <div className="flex justify-between">
- <span>Permissions:</span>
- <span className="font-medium text-green-600">
- {permissionsHook.micPermissionGranted &&
- permissionsHook.accessibilityPermissionGranted
- ? "βœ“ Granted"
- : "⚠ Review needed"}
- </span>
- </div>
- </div>
- </div>
-
- <div className="bg-blue-50 p-4 rounded-lg">
- <p className="text-sm text-blue-800">
- <strong>Pro tip:</strong> You can always change these settings later in the Control
- Panel.
- </p>
- </div>
- </div>
- );
-
default:
return null;
}
@@ -1016,7 +906,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
return true; // Mode selection
case 2:
if (useLocalWhisper) {
- return whisperModel !== ""; // Just need a model selected
+ return whisperModel !== "" && isModelDownloaded;
} else {
const trimmedKey = apiKey.trim();
if (!trimmedKey) {
@@ -1041,13 +931,9 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
return true;
}
case 4:
- return hotkey.trim() !== "";
+ return hotkey.trim() !== ""; // Hotkey & Test step
case 5:
- return true; // Practice step is always ready to proceed
- case 6:
- return agentName.trim() !== ""; // Agent name step
- case 7:
- return true;
+ return agentName.trim() !== ""; // Agent name step (final)
default:
return false;
}
@@ -1141,10 +1027,11 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
{currentStep === steps.length - 1 ? (
<Button
onClick={finishOnboarding}
+ disabled={!canProceed()}
className="bg-green-600 hover:bg-green-700 px-8 py-3 h-12 text-sm font-medium"
>
<Check className="w-4 h-4 mr-2" />
- Finish Setup
+ Complete Setup
</Button>
) : (
<Button
diff --git a/src/components/TranscriptionModelPicker.tsx b/src/components/TranscriptionModelPicker.tsx
index 2047af6a0..732ee1715 100644
--- a/src/components/TranscriptionModelPicker.tsx
+++ b/src/components/TranscriptionModelPicker.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useCallback, useMemo } from "react";
+import { useState, useEffect, useCallback, useMemo, useRef } from "react";
import { Button } from "./ui/button";
import { RefreshCw, Download, Trash2, Check, Cloud, Lock } from "lucide-react";
import { ProviderIcon } from "./ui/ProviderIcon";
@@ -74,6 +74,8 @@ export default function TranscriptionModelPicker({
const [localModels, setLocalModels] = useState<WhisperModel[]>([]);
const [loadingModels, setLoadingModels] = useState(false);
const [internalLocalProvider, setInternalLocalProvider] = useState(selectedLocalProvider);
+ const hasLoadedRef = useRef(false);
+ const isLoadingRef = useRef(false);
const { showConfirmDialog } = useDialogs();
const colorScheme: ColorScheme = variant === "settings" ? "purple" : "blue";
@@ -82,6 +84,10 @@ export default function TranscriptionModelPicker({
const cloudProviders = useMemo(() => getTranscriptionProviders(), []);
const loadLocalModels = useCallback(async () => {
+ // Prevent concurrent loading
+ if (isLoadingRef.current) return;
+ isLoadingRef.current = true;
+
try {
setLoadingModels(true);
const result = await window.electronAPI?.listWhisperModels();
@@ -93,6 +99,7 @@ export default function TranscriptionModelPicker({
setLocalModels([]);
} finally {
setLoadingModels(false);
+ isLoadingRef.current = false;
}
}, []);
@@ -121,13 +128,19 @@ export default function TranscriptionModelPicker({
onCloudModelSelect,
]);
+ // Only load models once on mount when in local mode, or when switching to local mode
useEffect(() => {
if (useLocalWhisper) {
- loadLocalModels();
+ if (!hasLoadedRef.current) {
+ hasLoadedRef.current = true;
+ loadLocalModels();
+ }
} else {
+ hasLoadedRef.current = false; // Reset when switching to cloud
ensureValidCloudSelection();
}
- }, [useLocalWhisper, loadLocalModels, ensureValidCloudSelection]);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [useLocalWhisper]); // Intentionally exclude callbacks to prevent re-render loops
useEffect(() => {
const handleModelsCleared = () => loadLocalModels();
@@ -470,10 +483,10 @@ export default function TranscriptionModelPicker({
variant="outline"
size="sm"
disabled={loadingModels}
- className={styles.buttons.refresh}
+ className={`${styles.buttons.refresh} min-w-[105px] justify-center transition-colors`}
>
<RefreshCw size={14} className={loadingModels ? "animate-spin" : ""} />
- <span className="ml-1">{loadingModels ? "Checking..." : "Refresh"}</span>
+ <span>{loadingModels ? "Checking..." : "Refresh"}</span>
</Button>
</div>
diff --git a/src/helpers/whisper.js b/src/helpers/whisper.js
index 36a057fc3..851a0fa5b 100644
--- a/src/helpers/whisper.js
+++ b/src/helpers/whisper.js
@@ -58,9 +58,7 @@ class WhisperManager {
// Only allow known model names to prevent path traversal attacks
const validModels = Object.keys(WHISPER_MODELS);
if (!validModels.includes(modelName)) {
- throw new Error(
- `Invalid model name: ${modelName}. Valid models: ${validModels.join(", ")}`
- );
+ throw new Error(`Invalid model name: ${modelName}. Valid models: ${validModels.join(", ")}`);
}
return true;
}
@@ -219,8 +217,7 @@ class WhisperManager {
async createTempAudioFile(audioBlob) {
const tempDir = os.tmpdir();
- const filename = `whisper_audio_${crypto.randomUUID()}.wav`;
- const tempAudioPath = path.join(tempDir, filename);
+ const uniqueId = crypto.randomUUID();
debugLogger.logAudioData("createTempAudioFile", audioBlob);
@@ -241,84 +238,215 @@ class WhisperManager {
throw new Error("Audio buffer is empty - no audio data received");
}
- // WAV header is 44 bytes minimum (RIFF + fmt + data chunk headers)
const MIN_AUDIO_SIZE = 44;
if (buffer.length < MIN_AUDIO_SIZE) {
throw new Error(`Audio data too small (${buffer.length} bytes) - recording may have failed`);
}
- await fsPromises.writeFile(tempAudioPath, buffer);
+ // Check if the audio is already in WAV format (starts with "RIFF" header)
+ const isWav =
+ buffer.length >= 4 &&
+ buffer[0] === 0x52 &&
+ buffer[1] === 0x49 &&
+ buffer[2] === 0x46 &&
+ buffer[3] === 0x46;
+
+ if (isWav) {
+ // Already WAV format - write directly
+ const tempAudioPath = path.join(tempDir, `whisper_audio_${uniqueId}.wav`);
+ await fsPromises.writeFile(tempAudioPath, buffer);
+ const stats = await fsPromises.stat(tempAudioPath);
+ debugLogger.logWhisperPipeline("Temp audio file created (WAV passthrough)", {
+ path: tempAudioPath,
+ size: stats.size,
+ });
+ return tempAudioPath;
+ }
- const stats = await fsPromises.stat(tempAudioPath);
- debugLogger.logWhisperPipeline("Temp audio file created", {
- path: tempAudioPath,
- size: stats.size,
+ // Audio is in WebM/Opus or other format - convert to WAV using FFmpeg
+ const inputPath = path.join(tempDir, `whisper_input_${uniqueId}.webm`);
+ const outputPath = path.join(tempDir, `whisper_audio_${uniqueId}.wav`);
+
+ await fsPromises.writeFile(inputPath, buffer);
+
+ const ffmpegPath = await this.getFFmpegPath();
+ if (!ffmpegPath) {
+ // Clean up input file
+ await fsPromises.unlink(inputPath).catch(() => {});
+ throw new Error("FFmpeg not found - required for audio format conversion");
+ }
+
+ debugLogger.logWhisperPipeline("Converting audio to WAV format", {
+ inputPath,
+ outputPath,
+ ffmpegPath,
+ inputSize: buffer.length,
});
- return tempAudioPath;
+ try {
+ // Convert to 16kHz mono WAV (optimal for Whisper)
+ await new Promise((resolve, reject) => {
+ const ffmpegProcess = spawn(
+ ffmpegPath,
+ [
+ "-i",
+ inputPath,
+ "-ar",
+ "16000", // 16kHz sample rate
+ "-ac",
+ "1", // Mono
+ "-c:a",
+ "pcm_s16le", // 16-bit PCM
+ "-y", // Overwrite output
+ outputPath,
+ ],
+ {
+ stdio: ["ignore", "pipe", "pipe"],
+ windowsHide: true,
+ }
+ );
+
+ let stderrData = "";
+ let settled = false;
+
+ const settle = (resolver, value) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timeout);
+ resolver(value);
+ };
+
+ // Timeout after 30 seconds
+ const timeout = setTimeout(() => {
+ ffmpegProcess.kill("SIGTERM");
+ settle(reject, new Error("FFmpeg conversion timed out"));
+ }, 30000);
+
+ ffmpegProcess.stderr.on("data", (data) => {
+ stderrData += data.toString();
+ });
+
+ ffmpegProcess.on("close", (code) => {
+ if (code === 0) {
+ settle(resolve, undefined);
+ } else {
+ settle(reject, new Error(`FFmpeg conversion failed (code ${code}): ${stderrData}`));
+ }
+ });
+
+ ffmpegProcess.on("error", (err) => {
+ settle(reject, new Error(`FFmpeg process error: ${err.message}`));
+ });
+ });
+
+ // Clean up input file
+ await fsPromises.unlink(inputPath).catch(() => {});
+
+ const stats = await fsPromises.stat(outputPath);
+ debugLogger.logWhisperPipeline("Audio converted to WAV", {
+ path: outputPath,
+ size: stats.size,
+ });
+
+ return outputPath;
+ } catch (error) {
+ // Clean up both files on error
+ await fsPromises.unlink(inputPath).catch(() => {});
+ await fsPromises.unlink(outputPath).catch(() => {});
+ throw error;
+ }
}
async runWhisperProcess(binaryPath, audioPath, modelPath, language) {
- const args = ["-m", modelPath, "-f", audioPath, "--output-json", "--no-prints"];
-
+ // whisper.cpp --output-json writes to a file, not stdout
+ const outputBasePath = audioPath.replace(/\.[^.]+$/, "");
+ const jsonOutputPath = `${outputBasePath}.json`;
+
+ const args = [
+ "-m",
+ modelPath,
+ "-f",
+ audioPath,
+ "--output-json",
+ "-of",
+ outputBasePath,
+ "--no-prints",
+ ];
if (language && language !== "auto") {
args.push("-l", language);
}
debugLogger.logProcessStart(binaryPath, args, {});
- return new Promise((resolve, reject) => {
+ const cleanupJsonFile = () => fsPromises.unlink(jsonOutputPath).catch(() => {});
+
+ const { code, stderr } = await new Promise((resolve, reject) => {
const whisperProcess = spawn(binaryPath, args, {
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
});
- let stdout = "";
- let stderr = "";
- let isResolved = false;
+ let stderrData = "";
+ let settled = false;
+
+ const settle = (resolver, value) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timeout);
+ resolver(value);
+ };
const timeout = setTimeout(() => {
- if (!isResolved) {
- killProcess(whisperProcess, "SIGTERM");
- reject(new Error("Whisper transcription timed out"));
- }
+ killProcess(whisperProcess, "SIGTERM");
+ settle(reject, new Error("Whisper transcription timed out"));
}, TIMEOUTS.TRANSCRIPTION);
- whisperProcess.stdout.on("data", (data) => {
- stdout += data.toString();
- debugLogger.logProcessOutput("Whisper", "stdout", data);
- });
-
+ whisperProcess.stdout.on("data", (data) =>
+ debugLogger.logProcessOutput("Whisper", "stdout", data)
+ );
whisperProcess.stderr.on("data", (data) => {
- stderr += data.toString();
+ stderrData += data.toString();
debugLogger.logProcessOutput("Whisper", "stderr", data);
});
- whisperProcess.on("close", (code) => {
- if (isResolved) return;
- isResolved = true;
- clearTimeout(timeout);
+ whisperProcess.on("close", (exitCode) =>
+ settle(resolve, { code: exitCode, stderr: stderrData })
+ );
+ whisperProcess.on("error", (err) =>
+ settle(reject, new Error(`Whisper process error: ${err.message}`))
+ );
+ });
- debugLogger.logWhisperPipeline("Process closed", {
- code,
- stdoutLength: stdout.length,
- stderrLength: stderr.length,
- });
+ debugLogger.logWhisperPipeline("Process closed", {
+ code,
+ stderrLength: stderr.length,
+ jsonOutputPath,
+ });
- if (code === 0) {
- resolve(stdout);
- } else {
- reject(new Error(`Whisper transcription failed (code ${code}): ${stderr}`));
- }
- });
+ if (code !== 0) {
+ await cleanupJsonFile();
+ throw new Error(`Whisper transcription failed (code ${code}): ${stderr}`);
+ }
- whisperProcess.on("error", (error) => {
- if (isResolved) return;
- isResolved = true;
- clearTimeout(timeout);
- reject(new Error(`Whisper process error: ${error.message}`));
- });
- });
+ // Check stderr for errors - whisper.cpp may exit 0 even on failure
+ if (stderr.includes("error:")) {
+ await cleanupJsonFile();
+ throw new Error(`Whisper processing error: ${stderr}`);
+ }
+
+ // Verify JSON file was created
+ if (!fs.existsSync(jsonOutputPath)) {
+ throw new Error(`Whisper did not produce output. stderr: ${stderr || "(empty)"}`);
+ }
+
+ try {
+ const jsonContent = await fsPromises.readFile(jsonOutputPath, "utf-8");
+ await cleanupJsonFile();
+ return jsonContent;
+ } catch (readError) {
+ await cleanupJsonFile();
+ throw new Error(`Failed to read Whisper output: ${readError.message}`);
+ }
}
parseWhisperResult(stdout) {
diff --git a/src/hooks/useModelDownload.ts b/src/hooks/useModelDownload.ts
index b34601fb0..587bc7778 100644
--- a/src/hooks/useModelDownload.ts
+++ b/src/hooks/useModelDownload.ts
@@ -45,6 +45,8 @@ export function useModelDownload({
downloadedBytes: 0,
totalBytes: 0,
});
+ const [isCancelling, setIsCancelling] = useState(false);
+ const isCancellingRef = useRef(false);
const { showAlertDialog } = useDialogs();
const { toast } = useToast();
@@ -68,14 +70,14 @@ export function useModelDownload({
const handleWhisperProgress = useCallback(
(_event: unknown, data: WhisperDownloadProgressData) => {
if (data.type === "progress") {
- const progress: DownloadProgress = {
+ setDownloadProgress({
percentage: data.percentage || 0,
downloadedBytes: data.downloaded_bytes || 0,
totalBytes: data.total_bytes || 0,
- };
-
- setDownloadProgress(progress);
+ });
} else if (data.type === "complete" || data.type === "error") {
+ // Skip if cancellation is handling cleanup
+ if (isCancellingRef.current) return;
setDownloadingModel(null);
setDownloadProgress({ percentage: 0, downloadedBytes: 0, totalBytes: 0 });
onDownloadCompleteRef.current?.();
@@ -186,6 +188,30 @@ export function useModelDownload({
[modelType, toast, showAlertDialog]
);
+ const cancelDownload = useCallback(async () => {
+ if (!downloadingModel) return;
+
+ setIsCancelling(true);
+ isCancellingRef.current = true;
+ try {
+ if (modelType === "whisper") {
+ await window.electronAPI?.cancelWhisperDownload();
+ }
+ toast({
+ title: "Download Cancelled",
+ description: "The download has been cancelled.",
+ });
+ } catch (error) {
+ console.error("Failed to cancel download:", error);
+ } finally {
+ setIsCancelling(false);
+ isCancellingRef.current = false;
+ setDownloadingModel(null);
+ setDownloadProgress({ percentage: 0, downloadedBytes: 0, totalBytes: 0 });
+ onDownloadCompleteRef.current?.();
+ }
+ }, [downloadingModel, modelType, toast]);
+
const isDownloading = downloadingModel !== null;
const isDownloadingModel = useCallback(
(modelId: string) => downloadingModel === modelId,
@@ -197,8 +223,10 @@ export function useModelDownload({
downloadProgress,
isDownloading,
isDownloadingModel,
+ isCancelling,
downloadModel,
deleteModel,
+ cancelDownload,
formatETA,
};
}
diff --git a/src/utils.js b/src/utils.js
index cbe81dcf3..5c39e158c 100644
--- a/src/utils.js
+++ b/src/utils.js
@@ -35,7 +35,7 @@ class AppUtils {
// Local Whisper model deletion
try {
- const modelCacheDir = path.join(os.homedir(), ".cache", "whisper");
+ const modelCacheDir = path.join(os.homedir(), ".cache", "openwhispr", "whisper-models");
if (fs.existsSync(modelCacheDir)) {
fs.rmSync(modelCacheDir, { recursive: true, force: true });
console.log("βœ… Local Whisper models deleted:", modelCacheDir);