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: add IPC listener cleanup to prevent memory leaks
Gabriel Stein3d538b0e5417
diff --git a/src/App.jsx b/src/App.jsxindex 2be6a1d5c..a07378c12 100644--- a/src/App.jsx+++ b/src/App.jsx@@ -4,7 +4,7 @@ import { useToast } from "./components/ui/Toast";import { LoadingDots } from "./components/ui/LoadingDots";import { useHotkey } from "./hooks/useHotkey";import { useWindowDrag } from "./hooks/useWindowDrag";-import AudioManager from "./helpers/audioManager";+import { useAudioRecording } from "./hooks/useAudioRecording";// Sound Wave Icon Component (for idle/hover states)const SoundWaveIcon = ({ size = 16 }) => {@@ -73,14 +73,8 @@ const Tooltip = ({ children, content, emoji }) => {};export default function App() {- const [isRecording, setIsRecording] = useState(false);- const [isProcessing, setIsProcessing] = useState(false);- const [transcript, setTranscript] = useState("");- const [error, setError] = useState("");const [isHovered, setIsHovered] = useState(false);const [isCommandMenuOpen, setIsCommandMenuOpen] = useState(false);- const mediaRecorderRef = useRef(null);- const audioChunksRef = useRef([]);const commandMenuRef = useRef(null);const buttonRef = useRef(null);const { toast } = useToast();@@ -107,97 +101,16 @@ export default function App() {}}, [isCommandMenuOpen, isHovered, setWindowInteractivity]);- const startRecording = async () => {- try {- 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",- });- // Start processing immediately without waiting- processAudio(audioBlob);- stream.getTracks().forEach((track) => track.stop());- };-- mediaRecorderRef.current.start();- setIsRecording(true);- } catch (err) {- console.error("Recording error:", err);- toast({- title: "Recording Error",- description: "Failed to access microphone: " + err.message,- variant: "destructive",- });- }- };-- const stopRecording = () => {- if (mediaRecorderRef.current && isRecording) {- mediaRecorderRef.current.stop();- setIsRecording(false);- // Don't set processing immediately - let the onstop handler do it- }- };-- const safePaste = async (text) => {- try {- await window.electronAPI.pasteText(text);- } catch (err) {- toast({- title: "Paste Error",- description:- "Failed to paste text. Please check accessibility permissions.",- variant: "destructive",- });+ const { isRecording, isProcessing, toggleListening } = useAudioRecording(+ toast,+ {+ onToggle: () => {+ setIsCommandMenuOpen(false);+ setWindowInteractivity(false);+ },}- };-- const processAudio = async (audioBlob) => {- try {- const audioManager = new AudioManager();- audioManager.setCallbacks({- onStateChange: ({ isRecording, isProcessing }) => {- setIsRecording(isRecording);- setIsProcessing(isProcessing);- },- onError: (error) => {- toast({- title: error.title,- description: error.description,- variant: "destructive",- });- },- onTranscriptionComplete: async (result) => {- if (result.success && result.text) {- setTranscript(result.text);-- safePaste(result.text);- window.electronAPI.saveTranscription(result.text).catch(() => {});- }- },- });+ );- await audioManager.processAudio(audioBlob);- } catch (err) {- toast({- title: "Transcription Error",- description: "Transcription failed: " + err.message,- variant: "destructive",- });- } finally {- setIsProcessing(false);- }- };const handleClose = () => {window.electronAPI.hideWindow();diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex ccb4570b9..c5d358abf 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -2,6 +2,8 @@ import ReasoningService from "../services/ReasoningService";import { API_ENDPOINTS, buildApiUrl, normalizeBaseUrl } from "../config/constants";const isDebugMode = typeof process !== 'undefined' && (process.env.OPENWHISPR_DEBUG === 'true' || process.env.NODE_ENV === 'development');+const SHORT_CLIP_DURATION_SECONDS = 2.5;+const REASONING_CACHE_TTL = 30000; // 30 secondsconst debugLogger = {logReasoning: async (stage, details) => {@@ -29,6 +31,9 @@ class AudioManager {this.onTranscriptionComplete = null;this.cachedApiKey = null;this.cachedTranscriptionEndpoint = null;+ this.recordingStartTime = null;+ this.reasoningAvailabilityCache = { value: false, expiresAt: 0 };+ this.cachedReasoningPreference = null;}setCallbacks({ onStateChange, onError, onTranscriptionComplete }) {@@ -48,6 +53,7 @@ class AudioManager {this.mediaRecorder = new MediaRecorder(stream);this.audioChunks = [];+ this.recordingStartTime = Date.now();this.mediaRecorder.ondataavailable = (event) => {this.audioChunks.push(event.data);@@ -63,7 +69,11 @@ class AudioManager {if (audioBlob.size === 0) {}- await this.processAudio(audioBlob);+ const durationSeconds = this.recordingStartTime+ ? (Date.now() - this.recordingStartTime) / 1000+ : null;+ this.recordingStartTime = null;+ await this.processAudio(audioBlob, { durationSeconds });// Clean up streamstream.getTracks().forEach((track) => track.stop());@@ -108,16 +118,16 @@ class AudioManager {return false;}- async processAudio(audioBlob) {+ async processAudio(audioBlob, metadata = {}) {try {const useLocalWhisper = localStorage.getItem("useLocalWhisper") === "true";const whisperModel = localStorage.getItem("whisperModel") || "base";let result;if (useLocalWhisper) {- result = await this.processWithLocalWhisper(audioBlob, whisperModel);+ result = await this.processWithLocalWhisper(audioBlob, whisperModel, metadata);} else {- result = await this.processWithOpenAIAPI(audioBlob);+ result = await this.processWithOpenAIAPI(audioBlob, metadata);}this.onTranscriptionComplete?.(result);} catch (error) {@@ -133,7 +143,7 @@ class AudioManager {}}- async processWithLocalWhisper(audioBlob, model = "base") {+ async processWithLocalWhisper(audioBlob, model = "base", metadata = {}) {try {const arrayBuffer = await audioBlob.arrayBuffer();const language = localStorage.getItem("preferredLanguage");@@ -173,7 +183,7 @@ class AudioManager {if (allowOpenAIFallback && isLocalMode) {try {- const fallbackResult = await this.processWithOpenAIAPI(audioBlob);+ const fallbackResult = await this.processWithOpenAIAPI(audioBlob, metadata);return { ...fallbackResult, source: "openai-fallback" };} catch (fallbackError) {throw new Error(`Local Whisper failed: ${error.message}. OpenAI fallback also failed: ${fallbackError.message}`);@@ -330,43 +340,69 @@ class AudioManager {}async isReasoningAvailable() {- // Check if we're in renderer process (has localStorage)- if (typeof window !== 'undefined' && window.localStorage) {- const storedValue = localStorage.getItem("useReasoningModel");-- // Debug log the actual stored value- debugLogger.logReasoning("REASONING_STORAGE_CHECK", {- storedValue,- typeOfStoredValue: typeof storedValue,- isTrue: storedValue === "true",- isTruthy: !!storedValue && storedValue !== "false"+ if (typeof window === "undefined" || !window.localStorage) {+ return false;+ }++ const storedValue = localStorage.getItem("useReasoningModel");+ const now = Date.now();+ const cacheValid =+ this.reasoningAvailabilityCache &&+ now < this.reasoningAvailabilityCache.expiresAt &&+ this.cachedReasoningPreference === storedValue;++ if (cacheValid) {+ return this.reasoningAvailabilityCache.value;+ }++ debugLogger.logReasoning("REASONING_STORAGE_CHECK", {+ storedValue,+ typeOfStoredValue: typeof storedValue,+ isTrue: storedValue === "true",+ isTruthy: !!storedValue && storedValue !== "false",+ });++ const useReasoning =+ storedValue === "true" || (!!storedValue && storedValue !== "false");++ if (!useReasoning) {+ this.reasoningAvailabilityCache = {+ value: false,+ expiresAt: now + REASONING_CACHE_TTL,+ };+ this.cachedReasoningPreference = storedValue;+ return false;+ }++ try {+ const isAvailable = await ReasoningService.isAvailable();++ debugLogger.logReasoning("REASONING_AVAILABILITY", {+ isAvailable,+ reasoningEnabled: useReasoning,+ finalDecision: useReasoning && isAvailable,});-- // Check for both "true" string and truthy values (but not "false")- const useReasoning = storedValue === "true" || (!!storedValue && storedValue !== "false");-- if (!useReasoning) return false;-- try {- const isAvailable = await ReasoningService.isAvailable();-- debugLogger.logReasoning("REASONING_AVAILABILITY", {- isAvailable,- reasoningEnabled: useReasoning,- finalDecision: useReasoning && isAvailable- });-- return isAvailable;- } catch (error) {- debugLogger.logReasoning("REASONING_AVAILABILITY_ERROR", {- error: error.message,- stack: error.stack- });- return false;- }++ this.reasoningAvailabilityCache = {+ value: isAvailable,+ expiresAt: now + REASONING_CACHE_TTL,+ };+ this.cachedReasoningPreference = storedValue;++ return isAvailable;+ } catch (error) {+ debugLogger.logReasoning("REASONING_AVAILABILITY_ERROR", {+ error: error.message,+ stack: error.stack,+ });++ this.reasoningAvailabilityCache = {+ value: false,+ expiresAt: now + REASONING_CACHE_TTL,+ };+ this.cachedReasoningPreference = storedValue;+ return false;}- // If not in renderer, reasoning is not available- return false;}async processTranscription(text, source) {@@ -433,12 +469,22 @@ class AudioManager {return normalizedText;}- async processWithOpenAIAPI(audioBlob) {+ async processWithOpenAIAPI(audioBlob, metadata = {}) {+ const language = localStorage.getItem("preferredLanguage");+ const allowLocalFallback =+ localStorage.getItem("allowLocalFallback") === "true";+ const fallbackModel = localStorage.getItem("fallbackWhisperModel") || "base";+try {- const language = localStorage.getItem("preferredLanguage");- const allowLocalFallback = localStorage.getItem("allowLocalFallback") === "true";- const fallbackModel = localStorage.getItem("fallbackWhisperModel") || "base";- const shouldOptimize = audioBlob.size > 1024 * 1024;++ const durationSeconds = metadata.durationSeconds ?? null;+ const shouldSkipOptimizationForDuration =+ typeof durationSeconds === "number" &&+ durationSeconds > 0 &&+ durationSeconds < SHORT_CLIP_DURATION_SECONDS;++ const shouldOptimize =+ !shouldSkipOptimizationForDuration && audioBlob.size > 1024 * 1024;const [apiKey, optimizedAudio] = await Promise.all([this.getAPIKey(),diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.jsindex 53cf21897..51f677e3a 100644--- a/src/hooks/useAudioRecording.js+++ b/src/hooks/useAudioRecording.js@@ -1,11 +1,12 @@import { useState, useEffect, useRef } from "react";import AudioManager from "../helpers/audioManager";-export const useAudioRecording = (toast) => {+export const useAudioRecording = (toast, options = {}) => {const [isRecording, setIsRecording] = useState(false);const [isProcessing, setIsProcessing] = useState(false);const [transcript, setTranscript] = useState("");const audioManagerRef = useRef(null);+ const { onToggle } = options;useEffect(() => {// Initialize AudioManager@@ -67,7 +68,10 @@ export const useAudioRecording = (toast) => {}};- const disposeToggle = window.electronAPI.onToggleDictation(handleToggle);+ const disposeToggle = window.electronAPI.onToggleDictation(() => {+ handleToggle();+ onToggle?.();+ });// Set up no-audio-detected listenerconst handleNoAudioDetected = () => {@@ -91,7 +95,7 @@ export const useAudioRecording = (toast) => {audioManagerRef.current.cleanup();}};- }, [toast]);+ }, [toast, onToggle]);const startRecording = async () => {if (audioManagerRef.current) {