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: centralize update event listeners in useUpdater hook to fix EventEmitter memory leak caused by duplicate listener registration across ControlPanel and SettingsPage components
Gabriel Stein05a7ae4ae490
diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsxindex 7e9345b5a..798e91443 100644--- a/src/components/ControlPanel.tsx+++ b/src/components/ControlPanel.tsx@@ -1,4 +1,4 @@-import { useState, useEffect, useRef } from "react";+import { useState, useEffect } from "react";import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";import { Button } from "./ui/button";import { Trash2, Settings, FileText, Mic, Download, RefreshCw, Loader2 } from "lucide-react";@@ -10,6 +10,7 @@ import { ConfirmDialog, AlertDialog } from "./ui/dialog";import { useDialogs } from "../hooks/useDialogs";import { useHotkey } from "../hooks/useHotkey";import { useToast } from "./ui/Toast";+import { useUpdater } from "../hooks/useUpdater";import {useTranscriptions,initializeTranscriptions,@@ -23,15 +24,17 @@ export default function ControlPanel() {const [showSettings, setShowSettings] = useState(false);const { hotkey } = useHotkey();const { toast } = useToast();- const [updateStatus, setUpdateStatus] = useState({- updateAvailable: false,- updateDownloaded: false,- isDevelopment: false,- });- const [isDownloading, setIsDownloading] = useState(false);- const [isInstalling, setIsInstalling] = useState(false);- const [downloadProgress, setDownloadProgress] = useState(0);- const isInstallingRef = useRef(false);++ // Use centralized updater hook to prevent EventEmitter memory leaks+ const {+ status: updateStatus,+ downloadProgress,+ isDownloading,+ isInstalling,+ downloadUpdate,+ installUpdate,+ error: updateError,+ } = useUpdater();const {confirmDialog,@@ -44,65 +47,29 @@ export default function ControlPanel() {useEffect(() => {loadTranscriptions();+ }, []);- // Initialize update status- const initializeUpdateStatus = async () => {- try {- const status = await window.electronAPI.getUpdateStatus();- setUpdateStatus(status);- } catch (error) {- // Update status not critical for app function- }- };-- initializeUpdateStatus();-- // Set up update event listeners- const handleUpdateAvailable = (_event: any, _info: any) => {- setUpdateStatus((prev) => ({ ...prev, updateAvailable: true }));- };-- const handleUpdateDownloaded = (_event: any, _info: any) => {- setIsDownloading(false);- setDownloadProgress(100);- setUpdateStatus((prev) => ({ ...prev, updateDownloaded: true }));+ // Show toast when update is ready+ useEffect(() => {+ if (updateStatus.updateDownloaded && !isDownloading) {toast({title: "Update Ready",description: "Click 'Install Update' to restart and apply the update.",variant: "success",});- };+ }+ }, [updateStatus.updateDownloaded, isDownloading, toast]);- const handleUpdateError = (_event: any, _error: any) => {- setIsDownloading(false);- setIsInstalling(false);+ // Show toast on update error+ useEffect(() => {+ if (updateError) {toast({title: "Update Error",description: "Failed to update. Please try again later.",variant: "destructive",});- };-- const handleDownloadProgress = (_event: any, progressObj: any) => {- if (progressObj?.percent != null) {- const newProgress = Math.round(progressObj.percent);- setDownloadProgress((prev) => (newProgress > prev ? newProgress : prev));- setIsDownloading(true);- }- };-- const disposers = [- window.electronAPI.onUpdateAvailable(handleUpdateAvailable),- window.electronAPI.onUpdateDownloaded(handleUpdateDownloaded),- window.electronAPI.onUpdateError(handleUpdateError),- window.electronAPI.onUpdateDownloadProgress(handleDownloadProgress),- ];-- // Cleanup listeners on unmount- return () => {- disposers.forEach((dispose) => dispose?.());- };- }, []);+ }+ }, [updateError, toast]);const loadTranscriptions = async () => {try {@@ -194,25 +161,9 @@ export default function ControlPanel() {description:"The update will be installed and the app will restart. Make sure you've saved any work.",onConfirm: async () => {- setIsInstalling(true);- isInstallingRef.current = true;try {- await window.electronAPI.installUpdate();- // Set a timeout to show an alert if the app doesn't restart- setTimeout(() => {- if (isInstallingRef.current) {- isInstallingRef.current = false;- setIsInstalling(false);- showAlertDialog({- title: "Update Installation",- description:- "The app may not have restarted automatically. Please quit and reopen the app to complete the update.",- });- }- }, 10000);+ await installUpdate();} catch (error) {- isInstallingRef.current = false;- setIsInstalling(false);toast({title: "Install Failed",description: "Failed to install update. Please try again.",@@ -223,12 +174,9 @@ export default function ControlPanel() {});} else if (updateStatus.updateAvailable && !isDownloading) {// Start download- setIsDownloading(true);- setDownloadProgress(0);try {- await window.electronAPI.downloadUpdate();+ await downloadUpdate();} catch (error) {- setIsDownloading(false);toast({title: "Download Failed",description: "Failed to download update. Please try again.",diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 282a65de3..8e83fe0ed 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -12,6 +12,7 @@ import { useAgentName } from "../utils/agentName";import { useWhisper } from "../hooks/useWhisper";import { usePermissions } from "../hooks/usePermissions";import { useClipboard } from "../hooks/useClipboard";+import { useUpdater } from "../hooks/useUpdater";import { REASONING_PROVIDERS, getTranscriptionProviders } from "../models/ModelRegistry";import { formatHotkeyLabel } from "../utils/hotkeys";import LanguageSelector from "./ui/LanguageSelector";@@ -86,26 +87,27 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage} = useSettings();const [currentVersion, setCurrentVersion] = useState<string>("");- const [updateStatus, setUpdateStatus] = useState<{- updateAvailable: boolean;- updateDownloaded: boolean;- isDevelopment: boolean;- }>({ updateAvailable: false, updateDownloaded: false, isDevelopment: false });- const [checkingForUpdates, setCheckingForUpdates] = useState(false);- const [downloadingUpdate, setDownloadingUpdate] = useState(false);- const [installInitiated, setInstallInitiated] = useState(false);- const [updateDownloadProgress, setUpdateDownloadProgress] = useState(0);- const [updateInfo, setUpdateInfo] = useState<{- version?: string;- releaseDate?: string;- releaseNotes?: string;- }>({});const [isRemovingModels, setIsRemovingModels] = useState(false);const cachePathHint =typeof navigator !== "undefined" && /Windows/i.test(navigator.userAgent)? "%USERPROFILE%\\.cache\\openwhispr\\models": "~/.cache/openwhispr/models";+ // Use centralized updater hook to prevent EventEmitter memory leaks+ const {+ status: updateStatus,+ info: updateInfo,+ downloadProgress: updateDownloadProgress,+ isChecking: checkingForUpdates,+ isDownloading: downloadingUpdate,+ isInstalling: installInitiated,+ checkForUpdates,+ downloadUpdate,+ installUpdate: installUpdateAction,+ getAppVersion,+ error: updateError,+ } = useUpdater();+const isUpdateAvailable =!updateStatus.isDevelopment && (updateStatus.updateAvailable || updateStatus.updateDownloaded);@@ -125,93 +127,6 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPageshowAlert: showAlertDialog,});- const subscribeToUpdates = useCallback(() => {- 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,- });- }- })- );- }-- if (window.electronAPI.onUpdateNotAvailable) {- disposers.push(- window.electronAPI.onUpdateNotAvailable(() => {- setUpdateStatus((prev) => ({- ...prev,- updateAvailable: false,- updateDownloaded: false,- }));- setUpdateInfo({});- setDownloadingUpdate(false);- setInstallInitiated(false);- setUpdateDownloadProgress(0);- })- );- }-- 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,- });- }- })- );- }-- if (window.electronAPI.onUpdateDownloadProgress) {- disposers.push(- window.electronAPI.onUpdateDownloadProgress((_event, progressObj) => {- setUpdateDownloadProgress(progressObj.percent || 0);- })- );- }-- 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]);const [localReasoningProvider, setLocalReasoningProvider] = useState(() => {return localStorage.getItem("reasoningProvider") || reasoningProvider;@@ -219,38 +134,12 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPageuseEffect(() => {let mounted = true;- let unsubscribeUpdates;const timer = setTimeout(async () => {if (!mounted) return;- const versionResult = await window.electronAPI?.getAppVersion();- if (versionResult && mounted) setCurrentVersion(versionResult.version);-- const statusResult = await window.electronAPI?.getUpdateStatus();- if (statusResult && mounted) {- setUpdateStatus((prev) => ({- ...prev,- ...statusResult,- updateAvailable: prev.updateAvailable || statusResult.updateAvailable,- updateDownloaded: prev.updateDownloaded || statusResult.updateDownloaded,- }));- if (- (statusResult.updateAvailable || statusResult.updateDownloaded) &&- window.electronAPI?.getUpdateInfo- ) {- const info = await window.electronAPI.getUpdateInfo();- if (info) {- setUpdateInfo({- version: info.version || "unknown",- releaseDate: info.releaseDate,- releaseNotes: info.releaseNotes ?? undefined,- });- }- }- }-- unsubscribeUpdates = subscribeToUpdates();+ const version = await getAppVersion();+ if (version && mounted) setCurrentVersion(version);if (mounted) {whisperHook.checkWhisperInstallation();@@ -260,9 +149,20 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPagereturn () => {mounted = false;clearTimeout(timer);- unsubscribeUpdates?.();};- }, [whisperHook, subscribeToUpdates]);+ }, [whisperHook, getAppVersion]);++ // Show alert dialog on update errors+ useEffect(() => {+ if (updateError) {+ showAlertDialog({+ title: "Update Error",+ description:+ updateError.message ||+ "The updater encountered a problem. Please try again or download the latest release manually.",+ });+ }+ }, [updateError, showAlertDialog]);useEffect(() => {if (installInitiated) {@@ -270,7 +170,6 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPageclearTimeout(installTimeoutRef.current);}installTimeoutRef.current = setTimeout(() => {- setInstallInitiated(false);showAlertDialog({title: "Still Running",description:@@ -527,20 +426,9 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage<div className="space-y-3"><ButtononClick={async () => {- setCheckingForUpdates(true);try {- const result = await window.electronAPI?.checkForUpdates();+ const result = await checkForUpdates();if (result?.updateAvailable) {- setUpdateInfo({- version: result.version || "unknown",- releaseDate: result.releaseDate,- releaseNotes: result.releaseNotes,- });- setUpdateStatus((prev) => ({- ...prev,- updateAvailable: true,- updateDownloaded: false,- }));showAlertDialog({title: "Update Available",description: `Update available: v${result.version || "new version"}`,@@ -556,8 +444,6 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPagetitle: "Update Check Failed",description: `Error checking for updates: ${error.message}`,});- } finally {- setCheckingForUpdates(false);}}}disabled={checkingForUpdates || updateStatus.isDevelopment}@@ -580,12 +466,9 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage<div className="space-y-2"><ButtononClick={async () => {- setDownloadingUpdate(true);- setUpdateDownloadProgress(0);try {- await window.electronAPI?.downloadUpdate();+ await downloadUpdate();} catch (error: any) {- setDownloadingUpdate(false);showAlertDialog({title: "Download Failed",description: `Failed to download update: ${error.message}`,@@ -603,7 +486,7 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage) : (<><Download size={16} className="mr-2" />- Download Update{updateInfo.version ? ` v${updateInfo.version}` : ""}+ Download Update{updateInfo?.version ? ` v${updateInfo.version}` : ""}</>)}</Button>@@ -631,30 +514,17 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPageonClick={() => {showConfirmDialog({title: "Install Update",- description: `Ready to install update${updateInfo.version ? ` v${updateInfo.version}` : ""}. The app will restart to complete installation.`,+ description: `Ready to install update${updateInfo?.version ? ` v${updateInfo.version}` : ""}. The app will restart to complete installation.`,confirmText: "Install & Restart",onConfirm: async () => {try {- setInstallInitiated(true);- const result = await window.electronAPI?.installUpdate?.();- if (!result?.success) {- setInstallInitiated(false);- showAlertDialog({- title: "Install Failed",- description:- result?.message ||- "Failed to start the installer. Please try again.",- });- return;- }-+ await installUpdateAction();showAlertDialog({title: "Installing Update",description:"OpenWhispr will restart automatically to finish installing the newest version.",});} catch (error: any) {- setInstallInitiated(false);showAlertDialog({title: "Install Failed",description: `Failed to install update: ${error.message}`,diff --git a/src/hooks/useUpdater.ts b/src/hooks/useUpdater.tsnew file mode 100644index 000000000..4139a3864--- /dev/null+++ b/src/hooks/useUpdater.ts@@ -0,0 +1,310 @@+import { useState, useEffect, useCallback, useRef } from "react";++/**+ * Centralized hook for managing app updates.+ * Prevents EventEmitter memory leaks by ensuring update listeners+ * are only registered once globally using a singleton pattern.+ */++interface UpdateStatus {+ updateAvailable: boolean;+ updateDownloaded: boolean;+ isDevelopment: boolean;+}++interface UpdateInfo {+ version?: string;+ releaseDate?: string;+ releaseNotes?: string;+ files?: any[];+}++interface UpdateProgress {+ percent: number;+ transferred: number;+ total: number;+}++interface UpdateState {+ status: UpdateStatus;+ info: UpdateInfo | null;+ downloadProgress: number;+ isChecking: boolean;+ isDownloading: boolean;+ isInstalling: boolean;+ error: Error | null;+}++// Global state shared across all hook instances+let globalState: UpdateState = {+ status: {+ updateAvailable: false,+ updateDownloaded: false,+ isDevelopment: false,+ },+ info: null,+ downloadProgress: 0,+ isChecking: false,+ isDownloading: false,+ isInstalling: false,+ error: null,+};++// Listeners registry for global state updates+const stateListeners = new Set<(state: UpdateState) => void>();++// Flag to track if event listeners have been registered+let listenersRegistered = false;+const cleanupFunctions: Array<() => void> = [];++/**+ * Notify all hook instances of state changes+ */+function notifyListeners() {+ stateListeners.forEach((listener) => listener({ ...globalState }));+}++/**+ * Update global state and notify all listeners+ */+function updateGlobalState(updates: Partial<UpdateState>) {+ globalState = { ...globalState, ...updates };+ notifyListeners();+}++/**+ * Register IPC event listeners (only once globally)+ */+function registerEventListeners() {+ if (listenersRegistered || !window.electronAPI) {+ return;+ }++ listenersRegistered = true;++ // Update available+ if (window.electronAPI.onUpdateAvailable) {+ const dispose = window.electronAPI.onUpdateAvailable((_event, info) => {+ updateGlobalState({+ status: { ...globalState.status, updateAvailable: true },+ info: info || globalState.info,+ });+ });+ if (dispose) cleanupFunctions.push(dispose);+ }++ // Update not available+ if (window.electronAPI.onUpdateNotAvailable) {+ const dispose = window.electronAPI.onUpdateNotAvailable(() => {+ updateGlobalState({+ status: {+ ...globalState.status,+ updateAvailable: false,+ updateDownloaded: false,+ },+ info: null,+ isChecking: false,+ });+ });+ if (dispose) cleanupFunctions.push(dispose);+ }++ // Update downloaded+ if (window.electronAPI.onUpdateDownloaded) {+ const dispose = window.electronAPI.onUpdateDownloaded((_event, info) => {+ updateGlobalState({+ status: { ...globalState.status, updateDownloaded: true },+ info: info || globalState.info,+ downloadProgress: 100,+ isDownloading: false,+ isInstalling: false,+ });+ });+ if (dispose) cleanupFunctions.push(dispose);+ }++ // Download progress+ if (window.electronAPI.onUpdateDownloadProgress) {+ const dispose = window.electronAPI.onUpdateDownloadProgress((_event, progressObj) => {+ updateGlobalState({+ downloadProgress: progressObj?.percent || 0,+ isDownloading: true,+ });+ });+ if (dispose) cleanupFunctions.push(dispose);+ }++ // Update error+ if (window.electronAPI.onUpdateError) {+ const dispose = window.electronAPI.onUpdateError((_event, error) => {+ updateGlobalState({+ isChecking: false,+ isDownloading: false,+ isInstalling: false,+ error: error instanceof Error ? error : new Error(String(error)),+ });+ });+ if (dispose) cleanupFunctions.push(dispose);+ }+}++/**+ * Cleanup function (called when last hook instance unmounts)+ */+function cleanup() {+ if (stateListeners.size === 0 && listenersRegistered) {+ cleanupFunctions.forEach((fn) => fn());+ cleanupFunctions.length = 0;+ listenersRegistered = false;+ }+}++/**+ * Custom hook for app update management+ *+ * Features:+ * - Singleton pattern prevents duplicate event listeners+ * - Shared state across all component instances+ * - Automatic cleanup when no components are using it+ *+ * @returns Update state and control functions+ */+export function useUpdater() {+ const [state, setState] = useState<UpdateState>(globalState);+ const isInstallingRef = useRef(false);++ useEffect(() => {+ // Register this component as a state listener+ stateListeners.add(setState);++ // Register global event listeners (only once)+ registerEventListeners();++ // Initialize update status from main process+ const initializeUpdateStatus = async () => {+ try {+ if (window.electronAPI?.getUpdateStatus) {+ const status = await window.electronAPI.getUpdateStatus();+ updateGlobalState({ status });+ }++ if (window.electronAPI?.getUpdateInfo) {+ const info = await window.electronAPI.getUpdateInfo();+ if (info) {+ updateGlobalState({ info });+ }+ }+ } catch (error) {+ console.error("Failed to initialize update status:", error);+ }+ };++ initializeUpdateStatus();++ // Cleanup on unmount+ return () => {+ stateListeners.delete(setState);+ cleanup();+ };+ }, []);++ /**+ * Check for updates manually+ */+ const checkForUpdates = useCallback(async () => {+ updateGlobalState({ isChecking: true, error: null });+ try {+ const result = await window.electronAPI.checkForUpdates();+ updateGlobalState({ isChecking: false });+ return result;+ } catch (error) {+ updateGlobalState({+ isChecking: false,+ error: error instanceof Error ? error : new Error(String(error)),+ });+ throw error;+ }+ }, []);++ /**+ * Download the available update+ */+ const downloadUpdate = useCallback(async () => {+ if (state.status.updateDownloaded) {+ return { success: true, message: "Update already downloaded" };+ }++ updateGlobalState({ isDownloading: true, downloadProgress: 0, error: null });+ try {+ const result = await window.electronAPI.downloadUpdate();+ return result;+ } catch (error) {+ updateGlobalState({+ isDownloading: false,+ error: error instanceof Error ? error : new Error(String(error)),+ });+ throw error;+ }+ }, [state.status.updateDownloaded]);++ /**+ * Install the downloaded update and restart the app+ */+ const installUpdate = useCallback(async () => {+ if (!state.status.updateDownloaded) {+ throw new Error("No update available to install");+ }++ updateGlobalState({ isInstalling: true, error: null });+ isInstallingRef.current = true;++ try {+ await window.electronAPI.installUpdate();++ // Set a timeout to reset state if app doesn't quit+ setTimeout(() => {+ if (isInstallingRef.current) {+ isInstallingRef.current = false;+ updateGlobalState({ isInstalling: false });+ }+ }, 10000);+ } catch (error) {+ isInstallingRef.current = false;+ updateGlobalState({+ isInstalling: false,+ error: error instanceof Error ? error : new Error(String(error)),+ });+ throw error;+ }+ }, [state.status.updateDownloaded]);++ /**+ * Get the current app version+ */+ const getAppVersion = useCallback(async () => {+ try {+ const result = await window.electronAPI.getAppVersion();+ return result.version;+ } catch (error) {+ console.error("Failed to get app version:", error);+ return null;+ }+ }, []);++ return {+ // State+ status: state.status,+ info: state.info,+ downloadProgress: state.downloadProgress,+ isChecking: state.isChecking,+ isDownloading: state.isDownloading,+ isInstalling: state.isInstalling,+ error: state.error,++ // Actions+ checkForUpdates,+ downloadUpdate,+ installUpdate,+ getAppVersion,+ };+}