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
refactor: add cleanup functions to IPC listeners to prevent memory leaks
Gabriel Steinb6b45710df60
diff --git a/preload.js b/preload.jsindex 485c36dde..a0bbd6361 100644--- a/preload.js+++ b/preload.js@@ -1,10 +1,35 @@const { contextBridge, ipcRenderer } = require("electron");+/**+ * Helper to register an IPC listener and return a cleanup function.+ * Ensures renderer code can easily remove listeners to avoid leaks.+ */+const registerListener = (channel, handlerFactory) => {+ return (callback) => {+ if (typeof callback !== "function") {+ return () => {};+ }++ const listener =+ typeof handlerFactory === "function"+ ? handlerFactory(callback)+ : (event, ...args) => callback(event, ...args);++ ipcRenderer.on(channel, listener);+ return () => {+ ipcRenderer.removeListener(channel, listener);+ };+ };+};+contextBridge.exposeInMainWorld("electronAPI", {pasteText: (text) => ipcRenderer.invoke("paste-text", text),hideWindow: () => ipcRenderer.invoke("hide-window"),showDictationPanel: () => ipcRenderer.invoke("show-dictation-panel"),- onToggleDictation: (callback) => ipcRenderer.on("toggle-dictation", callback),+ onToggleDictation: registerListener(+ "toggle-dictation",+ (callback) => () => callback()+ ),// Database functionssaveTranscription: (text) =>@@ -48,8 +73,7 @@ contextBridge.exposeInMainWorld("electronAPI", {checkPythonInstallation: () =>ipcRenderer.invoke("check-python-installation"),installPython: () => ipcRenderer.invoke("install-python"),- onPythonInstallProgress: (callback) =>- ipcRenderer.on("python-install-progress", callback),+ onPythonInstallProgress: registerListener("python-install-progress"),// Local Whisper functionstranscribeLocalWhisper: (audioBlob, options) =>@@ -57,12 +81,10 @@ contextBridge.exposeInMainWorld("electronAPI", {checkWhisperInstallation: () =>ipcRenderer.invoke("check-whisper-installation"),installWhisper: () => ipcRenderer.invoke("install-whisper"),- onWhisperInstallProgress: (callback) =>- ipcRenderer.on("whisper-install-progress", callback),+ onWhisperInstallProgress: registerListener("whisper-install-progress"),downloadWhisperModel: (modelName) =>ipcRenderer.invoke("download-whisper-model", modelName),- onWhisperDownloadProgress: (callback) =>- ipcRenderer.on("whisper-download-progress", callback),+ onWhisperDownloadProgress: registerListener("whisper-download-progress"),checkModelStatus: (modelName) =>ipcRenderer.invoke("check-model-status", modelName),listWhisperModels: () => ipcRenderer.invoke("list-whisper-models"),@@ -96,18 +118,14 @@ contextBridge.exposeInMainWorld("electronAPI", {getUpdateInfo: () => ipcRenderer.invoke("get-update-info"),// Update event listeners- onUpdateAvailable: (callback) => ipcRenderer.on("update-available", callback),- onUpdateNotAvailable: (callback) =>- ipcRenderer.on("update-not-available", callback),- onUpdateDownloaded: (callback) =>- ipcRenderer.on("update-downloaded", callback),- onUpdateDownloadProgress: (callback) =>- ipcRenderer.on("update-download-progress", callback),- onUpdateError: (callback) => ipcRenderer.on("update-error", callback),+ onUpdateAvailable: registerListener("update-available"),+ onUpdateNotAvailable: registerListener("update-not-available"),+ onUpdateDownloaded: registerListener("update-downloaded"),+ onUpdateDownloadProgress: registerListener("update-download-progress"),+ onUpdateError: registerListener("update-error"),// Audio event listeners- onNoAudioDetected: (callback) =>- ipcRenderer.on("no-audio-detected", callback),+ onNoAudioDetected: registerListener("no-audio-detected"),// External link openeropenExternal: (url) => ipcRenderer.invoke("open-external", url),@@ -119,7 +137,7 @@ contextBridge.exposeInMainWorld("electronAPI", {modelDelete: (modelId) => ipcRenderer.invoke("model-delete", modelId),modelDeleteAll: () => ipcRenderer.invoke("model-delete-all"),modelCheckRuntime: () => ipcRenderer.invoke("model-check-runtime"),- onModelDownloadProgress: (callback) => ipcRenderer.on("model-download-progress", callback),+ onModelDownloadProgress: registerListener("model-download-progress"),// Anthropic APIgetAnthropicKey: () => ipcRenderer.invoke("get-anthropic-key"),diff --git a/src/App.jsx b/src/App.jsxindex 0f65c743d..2be6a1d5c 100644--- a/src/App.jsx+++ b/src/App.jsx@@ -235,9 +235,9 @@ export default function App() {recording = false;}};- window.electronAPI.onToggleDictation(handleToggle);+ const dispose = window.electronAPI.onToggleDictation(handleToggle);return () => {- // No need to remove listener, as it's handled in preload+ dispose?.();};}, [isRecording, isProcessing]);diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsxindex 9d11a1963..cd207c244 100644--- a/src/components/ControlPanel.tsx+++ b/src/components/ControlPanel.tsx@@ -71,15 +71,15 @@ export default function ControlPanel() {// Update errors are handled by the update service};- window.electronAPI.onUpdateAvailable(handleUpdateAvailable);- window.electronAPI.onUpdateDownloaded(handleUpdateDownloaded);- window.electronAPI.onUpdateError(handleUpdateError);+ const disposers = [+ window.electronAPI.onUpdateAvailable(handleUpdateAvailable),+ window.electronAPI.onUpdateDownloaded(handleUpdateDownloaded),+ window.electronAPI.onUpdateError(handleUpdateError),+ ];// Cleanup listeners on unmountreturn () => {- window.electronAPI.removeAllListeners?.("update-available");- window.electronAPI.removeAllListeners?.("update-downloaded");- window.electronAPI.removeAllListeners?.("update-error");+ disposers.forEach((dispose) => dispose?.());};}, []);diff --git a/src/components/OnboardingFlow.tsx b/src/components/OnboardingFlow.tsxindex d4712660b..25f490dd6 100644--- a/src/components/OnboardingFlow.tsx+++ b/src/components/OnboardingFlow.tsx@@ -268,6 +268,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {}, [displayedReasoningModels, reasoningModel]);const whisperHook = useWhisper(showAlertDialog);+ const { setupProgressListener } = whisperHook;const pythonHook = usePython(showAlertDialog);const permissionsHook = usePermissions(showAlertDialog);const { pasteFromClipboard } = useClipboard(showAlertDialog);@@ -284,12 +285,11 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {];useEffect(() => {- whisperHook.setupProgressListener();+ const dispose = setupProgressListener();return () => {- // Clean up listeners on unmount- window.electronAPI?.removeAllListeners?.("whisper-install-progress");+ dispose?.();};- }, []);+ }, [setupProgressListener]);const updateProcessingMode = (useLocal: boolean) => {updateTranscriptionSettings({ useLocalWhisper: useLocal });diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 8103ba4db..f3977f01a 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -114,57 +114,91 @@ export default function SettingsPage({const installTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);const subscribeToUpdates = useCallback(() => {- if (!window.electronAPI) return;-- window.electronAPI.onUpdateAvailable?.((_event, info) => {- setUpdateStatus((prev) => ({ ...prev, updateAvailable: true, updateDownloaded: false }));- if (info) {- setUpdateInfo({- version: info.version || "unknown",- releaseDate: info.releaseDate,- releaseNotes: info.releaseNotes ?? undefined,- });- }- });+ if (!window.electronAPI) return () => {};++ const disposers: Array<(() => void) | void> = [];++ if (window.electronAPI.onUpdateAvailable) {+ disposers.push(+ window.electronAPI.onUpdateAvailable((_event, info) => {+ setUpdateStatus((prev) => ({+ ...prev,+ updateAvailable: true,+ updateDownloaded: false,+ }));+ if (info) {+ setUpdateInfo({+ version: info.version || "unknown",+ releaseDate: info.releaseDate,+ releaseNotes: info.releaseNotes ?? undefined,+ });+ }+ })+ );+ }- window.electronAPI.onUpdateNotAvailable?.(() => {- setUpdateStatus((prev) => ({ ...prev, updateAvailable: false, updateDownloaded: false }));- setUpdateInfo({});- setDownloadingUpdate(false);- setInstallInitiated(false);- setUpdateDownloadProgress(0);- });+ if (window.electronAPI.onUpdateNotAvailable) {+ disposers.push(+ window.electronAPI.onUpdateNotAvailable(() => {+ setUpdateStatus((prev) => ({+ ...prev,+ updateAvailable: false,+ updateDownloaded: false,+ }));+ setUpdateInfo({});+ setDownloadingUpdate(false);+ setInstallInitiated(false);+ setUpdateDownloadProgress(0);+ })+ );+ }- window.electronAPI.onUpdateDownloaded?.((_event, info) => {- setUpdateStatus((prev) => ({ ...prev, updateDownloaded: true }));- setDownloadingUpdate(false);- setInstallInitiated(false);- if (info) {- setUpdateInfo({- version: info.version || "unknown",- releaseDate: info.releaseDate,- releaseNotes: info.releaseNotes ?? undefined,- });- }- });+ if (window.electronAPI.onUpdateDownloaded) {+ disposers.push(+ window.electronAPI.onUpdateDownloaded((_event, info) => {+ setUpdateStatus((prev) => ({ ...prev, updateDownloaded: true }));+ setDownloadingUpdate(false);+ setInstallInitiated(false);+ if (info) {+ setUpdateInfo({+ version: info.version || "unknown",+ releaseDate: info.releaseDate,+ releaseNotes: info.releaseNotes ?? undefined,+ });+ }+ })+ );+ }- window.electronAPI.onUpdateDownloadProgress?.((_event, progressObj) => {- setUpdateDownloadProgress(progressObj.percent || 0);- });+ if (window.electronAPI.onUpdateDownloadProgress) {+ disposers.push(+ window.electronAPI.onUpdateDownloadProgress((_event, progressObj) => {+ setUpdateDownloadProgress(progressObj.percent || 0);+ })+ );+ }- window.electronAPI.onUpdateError?.((_event, error) => {- setCheckingForUpdates(false);- setDownloadingUpdate(false);- setInstallInitiated(false);- console.error("Update error:", error);- showAlertDialog({- title: "Update Error",- description:- typeof error?.message === "string"- ? error.message- : "The updater encountered a problem. Please try again or download the latest release manually.",- });- });+ if (window.electronAPI.onUpdateError) {+ disposers.push(+ window.electronAPI.onUpdateError((_event, error) => {+ setCheckingForUpdates(false);+ setDownloadingUpdate(false);+ setInstallInitiated(false);+ console.error("Update error:", error);+ showAlertDialog({+ title: "Update Error",+ description:+ typeof error?.message === "string"+ ? error.message+ : "The updater encountered a problem. Please try again or download the latest release manually.",+ });+ })+ );+ }++ return () => {+ disposers.forEach((dispose) => dispose?.());+ };}, [showAlertDialog]);// Local state for provider selection (overrides computed value)@@ -203,7 +237,7 @@ export default function SettingsPage({}}- subscribeToUpdates();+ const unsubscribeUpdates = subscribeToUpdates();// Check whisper after initial renderif (mounted) {@@ -215,13 +249,7 @@ export default function SettingsPage({mounted = false;clearTimeout(timer);// Always clean up update listeners if they exist- if (window.electronAPI) {- window.electronAPI.removeAllListeners?.("update-available");- window.electronAPI.removeAllListeners?.("update-not-available");- window.electronAPI.removeAllListeners?.("update-downloaded");- window.electronAPI.removeAllListeners?.("update-error");- window.electronAPI.removeAllListeners?.("update-download-progress");- }+ unsubscribeUpdates?.();};}, [whisperHook, subscribeToUpdates]);diff --git a/src/components/UnifiedModelPicker.tsx b/src/components/UnifiedModelPicker.tsxindex 788826033..a7d1ac917 100644--- a/src/components/UnifiedModelPicker.tsx+++ b/src/components/UnifiedModelPicker.tsx@@ -300,11 +300,14 @@ export default function UnifiedModelPicker({}, [modelType, loadModels]);useEffect(() => {- if (modelType === 'whisper') {- window.electronAPI.onWhisperDownloadProgress(handleDownloadProgress);- } else {- window.electronAPI.onModelDownloadProgress(handleDownloadProgress);- }+ const dispose =+ modelType === 'whisper'+ ? window.electronAPI.onWhisperDownloadProgress(handleDownloadProgress)+ : window.electronAPI.onModelDownloadProgress(handleDownloadProgress);++ return () => {+ dispose?.();+ };}, [handleDownloadProgress, modelType]);const downloadModel = useCallback(async (modelId: string) => {diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.jsindex 708b2404d..53cf21897 100644--- a/src/hooks/useAudioRecording.js+++ b/src/hooks/useAudioRecording.js@@ -67,7 +67,7 @@ export const useAudioRecording = (toast) => {}};- window.electronAPI.onToggleDictation(handleToggle);+ const disposeToggle = window.electronAPI.onToggleDictation(handleToggle);// Set up no-audio-detected listenerconst handleNoAudioDetected = () => {@@ -79,10 +79,14 @@ export const useAudioRecording = (toast) => {});};- window.electronAPI.onNoAudioDetected?.(handleNoAudioDetected);+ const disposeNoAudio = window.electronAPI.onNoAudioDetected?.(+ handleNoAudioDetected+ );// Cleanupreturn () => {+ disposeToggle?.();+ disposeNoAudio?.();if (audioManagerRef.current) {audioManagerRef.current.cleanup();}diff --git a/src/hooks/useLocalModels.ts b/src/hooks/useLocalModels.tsindex 240ea0930..13954b742 100644--- a/src/hooks/useLocalModels.ts+++ b/src/hooks/useLocalModels.ts@@ -43,10 +43,12 @@ export function useLocalModels() {setProgressMap(prev => new Map(prev).set(data.modelId, data));};- window.electronAPI.onModelDownloadProgress(handleProgress);+ const disposeProgress = window.electronAPI.onModelDownloadProgress(+ handleProgress+ );return () => {- window.electronAPI.removeAllListeners("model-download-progress");+ disposeProgress?.();};}, [loadModels]);@@ -102,4 +104,4 @@ export function useLocalModels() {getModelProgress,isRuntimeAvailable: checkRuntimeAvailable,};-}\ No newline at end of file+}diff --git a/src/hooks/usePython.ts b/src/hooks/usePython.tsindex c13a02bab..f693087b4 100644--- a/src/hooks/usePython.ts+++ b/src/hooks/usePython.ts@@ -83,6 +83,7 @@ export function usePython(showAlertDialog: ShowAlertDialog) {}let progressListener: ((event: any, data: PythonInstallProgress) => void) | null = null;+ let disposeProgress: (() => void) | void;try {setInstallingPython(true);@@ -96,7 +97,7 @@ export function usePython(showAlertDialog: ShowAlertDialog) {// Listen for progress updatesif (window.electronAPI.onPythonInstallProgress) {- window.electronAPI.onPythonInstallProgress(progressListener);+ disposeProgress = window.electronAPI.onPythonInstallProgress(progressListener);}const result = await window.electronAPI.installPython();@@ -127,9 +128,7 @@ export function usePython(showAlertDialog: ShowAlertDialog) {} finally {setInstallingPython(false);// Clean up the listener- if (progressListener) {- window.electronAPI?.removeAllListeners?.("python-install-progress");- }+ disposeProgress?.();}}, [showAlertDialog, checkPythonInstallation]);diff --git a/src/hooks/useWhisper.ts b/src/hooks/useWhisper.tsindex 3a3cc58f5..825d61149 100644--- a/src/hooks/useWhisper.ts+++ b/src/hooks/useWhisper.ts@@ -10,7 +10,7 @@ export interface UseWhisperReturn {checkWhisperInstallation: () => Promise<void>;installWhisper: () => Promise<void>;- setupProgressListener: () => void;+ setupProgressListener: () => (() => void) | void;}export interface UseWhisperProps {@@ -77,12 +77,15 @@ export const useWhisper = (}, [showAlertDialog]);const setupProgressListener = useCallback(() => {- // Remove any existing listeners first- window.electronAPI?.removeAllListeners?.("whisper-install-progress");-- window.electronAPI.onWhisperInstallProgress((_, data) => {+ if (!window.electronAPI?.onWhisperInstallProgress) {+ return;+ }++ const dispose = window.electronAPI.onWhisperInstallProgress((_, data) => {setInstallProgress(data.message);});++ return () => dispose?.();}, []);// Check Whisper installation on mountdiff --git a/src/types/electron.ts b/src/types/electron.tsindex 7b215bccf..a54b6894e 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -118,7 +118,7 @@ declare global {pasteText: (text: string) => Promise<void>;hideWindow: () => Promise<void>;showDictationPanel: () => Promise<void>;- onToggleDictation: (callback: () => void) => void;+ onToggleDictation: (callback: () => void) => (() => void) | void;// Database operationssaveTranscription: (@@ -161,13 +161,16 @@ declare global {text?: string;error?: string;}>;+ onNoAudioDetected: (+ callback: (event: any, data?: any) => void+ ) => (() => void) | void;// Python operationscheckPythonInstallation: () => Promise<PythonInstallation>;installPython: () => Promise<PythonInstallResult>;onPythonInstallProgress: (callback: (event: any, data: PythonInstallProgressData) => void- ) => void;+ ) => (() => void) | void;// Whisper operationstranscribeLocalWhisper: (@@ -178,11 +181,11 @@ declare global {installWhisper: () => Promise<WhisperInstallResult>;onWhisperInstallProgress: (callback: (event: any, data: WhisperInstallProgressData) => void- ) => void;+ ) => (() => void) | void;downloadWhisperModel: (modelName: string) => Promise<WhisperModelResult>;onWhisperDownloadProgress: (callback: (event: any, data: WhisperDownloadProgressData) => void- ) => void;+ ) => (() => void) | void;checkModelStatus: (modelName: string) => Promise<WhisperModelResult>;listWhisperModels: () => Promise<WhisperModelsListResult>;deleteWhisperModel: (@@ -201,7 +204,9 @@ declare global {modelDelete: (modelId: string) => Promise<void>;modelDeleteAll: () => Promise<{ success: boolean; error?: string; code?: string }>;modelCheckRuntime: () => Promise<boolean>;- onModelDownloadProgress: (callback: (event: any, data: any) => void) => void;+ onModelDownloadProgress: (+ callback: (event: any, data: any) => void+ ) => (() => void) | void;// Local reasoningprocessLocalReasoning: (text: string, modelId: string, agentName: string | null, config: any) => Promise<{ success: boolean; text?: string; error?: string }>;@@ -239,13 +244,21 @@ declare global {getUpdateInfo: () => Promise<UpdateInfoResult | null>;// Update event listeners- onUpdateAvailable: (callback: (event: any, info: any) => void) => void;- onUpdateNotAvailable: (callback: (event: any, info: any) => void) => void;- onUpdateDownloaded: (callback: (event: any, info: any) => void) => void;+ onUpdateAvailable: (+ callback: (event: any, info: any) => void+ ) => (() => void) | void;+ onUpdateNotAvailable: (+ callback: (event: any, info: any) => void+ ) => (() => void) | void;+ onUpdateDownloaded: (+ callback: (event: any, info: any) => void+ ) => (() => void) | void;onUpdateDownloadProgress: (callback: (event: any, progressObj: any) => void- ) => void;- onUpdateError: (callback: (event: any, error: any) => void) => void;+ ) => (() => void) | void;+ onUpdateError: (+ callback: (event: any, error: any) => void+ ) => (() => void) | void;// Settings management (used by OnboardingFlow but not in preload.js)saveSettings?: (settings: SaveSettings) => Promise<void>;