Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix: fixed crash when cancelling model download
Gabriel Steinc65f3ff6ee88
diff --git a/package.json b/package.jsonindex fda2a4964..3a4727dfe 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-wispr",- "version": "0.0.3-alpha",+ "version": "0.0.4-alpha","description": "A desktop dictation application using OpenAI Whisper for speech-to-text transcription","main": "main.js","private": true,diff --git a/src/App.jsx b/src/App.jsxindex 1674bba9f..f19237236 100644--- a/src/App.jsx+++ b/src/App.jsx@@ -1,8 +1,7 @@import React, { useState, useEffect, useRef } from "react";import "./index.css";-import { Toast } from "./components/ui/Toast";+import { useToast } from "./components/ui/Toast";import { LoadingDots } from "./components/ui/LoadingDots";-import { Settings } from "lucide-react";// Sound Wave Icon Component (for idle/hover states)const SoundWaveIcon = ({ size = 16 }) => {@@ -78,32 +77,39 @@ export default function App() {const [isHovered, setIsHovered] = useState(false);const mediaRecorderRef = useRef(null);const audioChunksRef = useRef([]);+ const { toast } = useToast();const startRecording = async () => {try {- setError('');+ setError("");const stream = await navigator.mediaDevices.getUserMedia({ audio: true });-+mediaRecorderRef.current = new window.MediaRecorder(stream);audioChunksRef.current = [];-+mediaRecorderRef.current.ondataavailable = (event) => {audioChunksRef.current.push(event.data);};-+mediaRecorderRef.current.onstop = async () => {setIsProcessing(true);- const audioBlob = new Blob(audioChunksRef.current, { type: 'audio/wav' });+ const audioBlob = new Blob(audioChunksRef.current, {+ type: "audio/wav",+ });// Start processing immediately without waitingprocessAudio(audioBlob);- stream.getTracks().forEach(track => track.stop());+ stream.getTracks().forEach((track) => track.stop());};-+mediaRecorderRef.current.start();setIsRecording(true);} catch (err) {- console.error("Recording error:", err)- setError('Failed to access microphone: ' + err.message);+ console.error("Recording error:", err);+ toast({+ title: "Recording Error",+ description: "Failed to access microphone: " + err.message,+ variant: "destructive",+ });}};@@ -119,25 +125,34 @@ export default function App() {try {await window.electronAPI.pasteText(text);} catch (err) {- setError("Failed to paste text. Please check accessibility permissions.");+ toast({+ title: "Paste Error",+ description:+ "Failed to paste text. Please check accessibility permissions.",+ variant: "destructive",+ });}};const processAudio = async (audioBlob) => {try {// Cache preferences to avoid repeated localStorage calls- const useLocalWhisper = localStorage.getItem('useLocalWhisper') === 'true';- const whisperModel = localStorage.getItem('whisperModel') || 'base';-+ const useLocalWhisper =+ localStorage.getItem("useLocalWhisper") === "true";+ const whisperModel = localStorage.getItem("whisperModel") || "base";+if (useLocalWhisper) {await processWithLocalWhisper(audioBlob, whisperModel);} else {await processWithOpenAIAPI(audioBlob);}-} catch (err) {- console.error("Transcription error:", err)- setError('Transcription failed: ' + err.message);+ console.error("Transcription error:", err);+ toast({+ title: "Transcription Error",+ description: "Transcription failed: " + err.message,+ variant: "destructive",+ });} finally {setIsProcessing(false);}@@ -172,13 +187,21 @@ export default function App() {// Wait for paste to complete, but don't block on database saveawait pastePromise;} else {- setError("No text transcribed. Try again.");+ toast({+ title: "No Audio",+ description: "No text transcribed. Try again.",+ variant: "destructive",+ });}} else if (result.success === false &&result.message === "No audio detected") {- setError("No audio detected");+ toast({+ title: "No Audio",+ description: "No audio detected",+ variant: "destructive",+ });return;} else {throw new Error(result.error || "Local Whisper transcription failed");@@ -189,7 +212,11 @@ export default function App() {localStorage.getItem("allowOpenAIFallback") === "true";if (allowFallback) {- setError("Local Whisper failed. Retrying with OpenAI API...");+ toast({+ title: "Fallback Mode",+ description: "Local Whisper failed. Retrying with OpenAI API...",+ variant: "default",+ });await processWithOpenAIAPI(audioBlob);} else {throw new Error(`Local Whisper failed: ${err.message}`);@@ -214,9 +241,12 @@ export default function App() {apiKey.trim() === "" ||apiKey === "your_openai_api_key_here") {- setError(- "OpenAI API key not found. Please set your API key in the .env file or Control Panel."- );+ toast({+ title: "API Key Missing",+ description:+ "OpenAI API key not found. Please set your API key in the .env file or Control Panel.",+ variant: "destructive",+ });return;}@@ -238,7 +268,11 @@ export default function App() {if (!response.ok) {const errorText = await response.text();console.error("API Error:", errorText);- setError(`Transcription failed: ${response.status} ${errorText}`);+ toast({+ title: "API Error",+ description: `Transcription failed: ${response.status} ${errorText}`,+ variant: "destructive",+ });throw new Error(`Failed to transcribe audio: ${response.status} ${errorText}`);@@ -263,7 +297,11 @@ export default function App() {// Wait for paste to complete, but don't block on database saveawait pastePromise;} else {- setError("No text transcribed. Try again.");+ toast({+ title: "No Audio",+ description: "No text transcribed. Try again.",+ variant: "destructive",+ });}} catch (err) {console.error("OpenAI API error:", err);@@ -416,8 +454,6 @@ export default function App() {</button></Tooltip></div>-- <Toast message={error} onClose={() => setError("")} /></>);}diff --git a/src/components/WhisperModelPicker.tsx b/src/components/WhisperModelPicker.tsxindex 194516781..2bef9a6b0 100644--- a/src/components/WhisperModelPicker.tsx+++ b/src/components/WhisperModelPicker.tsx@@ -2,6 +2,7 @@ import React, { useState, useEffect, useCallback, useMemo } from "react";import { Button } from "./ui/button";import { RefreshCw, Download, Trash2, X } from "lucide-react";import { ConfirmDialog, AlertDialog } from "./ui/dialog";+import { useToast } from "./ui/Toast";interface WhisperModel {model: string;@@ -123,6 +124,7 @@ export default function WhisperModelPicker({title: "",});+ const { toast } = useToast();const styles = useMemo(() => VARIANT_STYLES[variant], [variant]);const loadModelList = useCallback(async () => {@@ -174,7 +176,7 @@ export default function WhisperModelPicker({});if (data.error?.includes("interrupted by user")) {- console.log("Model download was cancelled by user");+ // Toast is handled by the cancel button - don't show duplicate here} else if (data.error?.includes("timeout")) {setAlertDialog({open: true,@@ -211,6 +213,9 @@ export default function WhisperModelPicker({totalBytes: 0,});+ // Auto-select the model when starting download+ onModelSelect(modelName);+const result = await window.electronAPI.downloadWhisperModel(modelName);if (result.success) {@@ -224,6 +229,7 @@ export default function WhisperModelPicker({description: `Failed to download model "${modelName}": ${result.error}`,});}+ // Don't show toast here - it's handled by the progress handler}} catch (error) {// Only show error if it's not a cancellation@@ -234,6 +240,7 @@ export default function WhisperModelPicker({description: `Failed to download model "${modelName}": ${error}`,});}+ // Don't show toast here - it's handled by the progress handler} finally {setDownloadingModel(null);setDownloadProgress({@@ -243,7 +250,7 @@ export default function WhisperModelPicker({});}},- [loadModelList]+ [loadModelList, onModelSelect]);const cancelDownload = useCallback(async (modelName: string) => {@@ -262,13 +269,23 @@ export default function WhisperModelPicker({downloadedBytes: 0,totalBytes: 0,});- console.log(`Download of "${modelName}" cancelled successfully`);- } else {- setAlertDialog({- open: true,- title: "Cancel Failed",- description: `Failed to cancel download: ${result.error}`,+ toast({+ title: "Download Cancelled",+ description: "Model download was cancelled successfully.",+ variant: "default",});+ } else {+ // Only show error dialog if it's not a successful cancellation+ if (+ !result.error?.includes("interrupted") &&+ !result.error?.includes("cancelled")+ ) {+ setAlertDialog({+ open: true,+ title: "Cancel Failed",+ description: `Failed to cancel download: ${result.error}`,+ });+ }}} catch (error) {console.error(`Failed to cancel download of "${modelName}":`, error);diff --git a/src/components/ui/Toast.tsx b/src/components/ui/Toast.tsxindex ca2d34585..dd5ca1ce7 100644--- a/src/components/ui/Toast.tsx+++ b/src/components/ui/Toast.tsx@@ -1,35 +1,145 @@-import React, { useEffect } from 'react';+import * as React from "react";+import { X } from "lucide-react";-interface ToastProps {- message: string;- onClose: () => void;+export interface ToastProps {+ id?: string;+ title?: string;+ description?: string;+ action?: React.ReactNode;+ variant?: "default" | "destructive" | "success";+ duration?: number;+ onClose?: () => void;}-export const Toast = ({ message, onClose }: ToastProps) => {- useEffect(() => {- if (!message) return;- const timer = setTimeout(onClose, 3500);- return () => clearTimeout(timer);- }, [message, onClose]);-- if (!message) return null;-+export interface ToastContextType {+ toast: (props: Omit<ToastProps, "id">) => void;+ dismiss: (id?: string) => void;+}++const ToastContext = React.createContext<ToastContextType | undefined>(+ undefined+);++export const useToast = () => {+ const context = React.useContext(ToastContext);+ if (!context) {+ throw new Error("useToast must be used within a ToastProvider");+ }+ return context;+};++export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({+ children,+}) => {+ const [toasts, setToasts] = React.useState<(ToastProps & { id: string })[]>(+ []+ );++ const toast = React.useCallback((props: Omit<ToastProps, "id">) => {+ const id = Math.random().toString(36).substr(2, 9);+ const newToast = { ...props, id };++ setToasts((prev) => [...prev, newToast]);++ // Auto-dismiss after duration+ const duration = props.duration ?? 3500;+ if (duration > 0) {+ setTimeout(() => {+ dismiss(id);+ }, duration);+ }++ return id;+ }, []);++ const dismiss = React.useCallback((id?: string) => {+ setToasts((prev) => {+ if (id) {+ return prev.filter((toast) => toast.id !== id);+ }+ return prev.slice(0, -1);+ });+ }, []);+return (- <div style={{- position: 'fixed',- left: '50%',- bottom: 60,- transform: 'translateX(-50%)',- background: '#222',- color: '#fff',- padding: '10px 22px',- borderRadius: 8,- boxShadow: '0 2px 12px rgba(0,0,0,0.18)',- fontSize: 15,- zIndex: 9999,- pointerEvents: 'auto',- }}>- {message}+ <ToastContext.Provider value={{ toast, dismiss }}>+ {children}+ <ToastViewport toasts={toasts} onDismiss={dismiss} />+ </ToastContext.Provider>+ );+};++const ToastViewport: React.FC<{+ toasts: (ToastProps & { id: string })[];+ onDismiss: (id: string) => void;+}> = ({ toasts, onDismiss }) => {+ if (toasts.length === 0) return null;++ return (+ <div className="fixed bottom-4 right-4 z-50 flex flex-col gap-2 max-w-sm">+ {toasts.map((toast) => (+ <Toast key={toast.id} {...toast} onClose={() => onDismiss(toast.id)} />+ ))}</div>);-};\ No newline at end of file+};++const Toast: React.FC<ToastProps & { onClose?: () => void }> = ({+ title,+ description,+ action,+ variant = "default",+ onClose,+}) => {+ const baseClasses =+ "relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-lg border p-4 pr-8 shadow-lg transition-all duration-300 ease-in-out";++ const variantClasses = {+ default: "bg-white border-gray-200 text-gray-900",+ destructive: "bg-red-50 border-red-200 text-red-900",+ success: "bg-green-50 border-green-200 text-green-900",+ };++ const iconClasses = {+ default: "text-gray-400",+ destructive: "text-red-400",+ success: "text-green-400",+ };++ return (+ <div className={`${baseClasses} ${variantClasses[variant]}`}>+ <div className="flex-1 space-y-1">+ {title && <div className="text-sm font-medium">{title}</div>}+ {description && <div className="text-sm opacity-90">{description}</div>}+ </div>+ {action && <div className="flex-shrink-0">{action}</div>}+ {onClose && (+ <button+ onClick={onClose}+ className={`absolute right-2 top-2 rounded-sm opacity-70 ring-offset-white transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-gray-400 focus:ring-offset-2 ${iconClasses[variant]}`}+ >+ <X className="h-4 w-4" />+ <span className="sr-only">Close</span>+ </button>+ )}+ </div>+ );+};++// Helper function for common toast patterns+export const toast = {+ success: (message: string) => ({+ title: "Success",+ description: message,+ variant: "success" as const,+ }),+ error: (message: string) => ({+ title: "Error",+ description: message,+ variant: "destructive" as const,+ }),+ info: (message: string) => ({+ description: message,+ variant: "default" as const,+ }),+};diff --git a/src/helpers/whisper.js b/src/helpers/whisper.jsindex e9d2efe81..55adf8854 100644--- a/src/helpers/whisper.js+++ b/src/helpers/whisper.js@@ -126,7 +126,6 @@ class WhisperManager {if (!currentPath.includes(ffmpegDir)) {enhancedEnv.PATH = `${ffmpegDir}${pathSeparator}${currentPath}`;}-} else {console.warn("No valid FFmpeg path found, transcription may fail");}@@ -182,7 +181,8 @@ class WhisperManager {stderr.includes("No such file or directory") ||stderr.includes("FFmpeg not found")) {- errorMessage += "\n\nFFmpeg issue detected. Try restarting the app or reinstalling.";+ errorMessage +=+ "\n\nFFmpeg issue detected. Try restarting the app or reinstalling.";}reject(new Error(errorMessage));@@ -495,13 +495,12 @@ class WhisperManager {);}} else {- if (code === 143 || code === 137) {+ // Handle cancellation cases (SIGTERM, SIGKILL, or null exit codes)+ if (code === 143 || code === 137 || code === null) {reject(new Error("Download interrupted by user"));} else {console.error("Model download failed with code:", code);- reject(- new Error(`Model download failed (code ${code}): ${stderr}`)- );+ reject(new Error(`Model download failed (exit code ${code})`));}}});diff --git a/src/main.jsx b/src/main.jsxindex 6997b728c..03ccf1849 100644--- a/src/main.jsx+++ b/src/main.jsx@@ -1,44 +1,49 @@-import React, { useState, useEffect } from 'react'-import ReactDOM from 'react-dom/client'-import App from './App.jsx'-import ControlPanel from './components/ControlPanel.tsx'-import OnboardingFlow from './components/OnboardingFlow.tsx'-import './index.css'+import React, { useState, useEffect } from "react";+import ReactDOM from "react-dom/client";+import App from "./App.jsx";+import ControlPanel from "./components/ControlPanel.tsx";+import OnboardingFlow from "./components/OnboardingFlow.tsx";+import { ToastProvider } from "./components/ui/Toast.tsx";+import "./index.css";function AppRouter() {const [showOnboarding, setShowOnboarding] = useState(false);const [isLoading, setIsLoading] = useState(true);-+// Check if this is the control panel window- const isControlPanel = window.location.pathname.includes('control') ||- window.location.search.includes('panel=true');-+ const isControlPanel =+ window.location.pathname.includes("control") ||+ window.location.search.includes("panel=true");+// Check if this is the dictation panel (main app)const isDictationPanel = !isControlPanel;-+useEffect(() => {// Check if onboarding has been completed- const onboardingCompleted = localStorage.getItem('onboardingCompleted') === 'true';- const currentStep = parseInt(localStorage.getItem('onboardingCurrentStep') || '0');-+ const onboardingCompleted =+ localStorage.getItem("onboardingCompleted") === "true";+ const currentStep = parseInt(+ localStorage.getItem("onboardingCurrentStep") || "0"+ );+if (isControlPanel && !onboardingCompleted) {// Show onboarding for control panel if not completedsetShowOnboarding(true);}-+// Hide dictation panel window unless onboarding is complete or we're past the permissions stepif (isDictationPanel && !onboardingCompleted && currentStep < 4) {window.electronAPI?.hideWindow?.();}-+setIsLoading(false);}, [isControlPanel, isDictationPanel]);-+const handleOnboardingComplete = () => {setShowOnboarding(false);- localStorage.setItem('onboardingCompleted', 'true');+ localStorage.setItem("onboardingCompleted", "true");};-+if (isLoading) {return (<div className="min-h-screen bg-gray-50 flex items-center justify-center">@@ -49,16 +54,18 @@ function AppRouter() {</div>);}-+if (isControlPanel && showOnboarding) {return <OnboardingFlow onComplete={handleOnboardingComplete} />;}-+return isControlPanel ? <ControlPanel /> : <App />;}-ReactDOM.createRoot(document.getElementById('root')).render(+ReactDOM.createRoot(document.getElementById("root")).render(<React.StrictMode>- <AppRouter />- </React.StrictMode>,-)+ <ToastProvider>+ <AppRouter />+ </ToastProvider>+ </React.StrictMode>+);