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: code cleanup
Gabriel Stein6e6250040ac8
diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsxindex 790fe313c..b7cba1888 100644--- a/src/components/ControlPanel.tsx+++ b/src/components/ControlPanel.tsx@@ -6,6 +6,7 @@ import SettingsPage from "./SettingsPage";import TitleBar from "./TitleBar";import TranscriptionItem from "./ui/TranscriptionItem";import { ConfirmDialog, AlertDialog } from "./ui/dialog";+import { useDialogs } from "../hooks/useDialogs";import { useHotkey } from "../hooks/useHotkey";import type { TranscriptionItem as TranscriptionItemType } from "../types/electron";@@ -19,25 +20,15 @@ export default function ControlPanel() {updateDownloaded: false,isDevelopment: false,});- const [confirmDialog, setConfirmDialog] = useState<{- open: boolean;- title: string;- description?: string;- onConfirm: () => void;- variant?: "default" | "destructive";- }>({- open: false,- title: "",- onConfirm: () => {},- });- const [alertDialog, setAlertDialog] = useState<{- open: boolean;- title: string;- description?: string;- }>({- open: false,- title: "",- });++ const {+ confirmDialog,+ alertDialog,+ showConfirmDialog,+ showAlertDialog,+ hideConfirmDialog,+ hideAlertDialog,+ } = useDialogs();useEffect(() => {// Load transcription history from database@@ -83,8 +74,7 @@ export default function ControlPanel() {const copyToClipboard = async (text: string) => {try {await navigator.clipboard.writeText(text);- setAlertDialog({- open: true,+ showAlertDialog({title: "Copied!",description: "Text copied to your clipboard!",});@@ -92,8 +82,7 @@ export default function ControlPanel() {};const clearHistory = async () => {- setConfirmDialog({- open: true,+ showConfirmDialog({title: "Clear History",description:"Are you certain you wish to clear all inscribed records? This action cannot be undone.",@@ -101,14 +90,12 @@ export default function ControlPanel() {try {const result = await window.electronAPI.clearTranscriptions();setHistory([]);- setAlertDialog({- open: true,+ showAlertDialog({title: "History Cleared",description: `Successfully cleared ${result.cleared} transcriptions from your chronicles.`,});} catch (error) {- setAlertDialog({- open: true,+ showAlertDialog({title: "Error",description: "Failed to clear history. Please try again.",});@@ -119,8 +106,7 @@ export default function ControlPanel() {};const deleteTranscription = async (id: number) => {- setConfirmDialog({- open: true,+ showConfirmDialog({title: "Delete Transcription",description:"Are you certain you wish to remove this inscription from your records?",@@ -132,8 +118,7 @@ export default function ControlPanel() {setHistory((prev) => prev.filter((item) => item.id !== id));console.log(`ποΈ Deleted transcription ${id}`);} else {- setAlertDialog({- open: true,+ showAlertDialog({title: "Delete Failed",description:"Failed to delete transcription. It may have already been removed.",@@ -141,8 +126,7 @@ export default function ControlPanel() {}} catch (error) {console.error("β Failed to delete transcription:", error);- setAlertDialog({- open: true,+ showAlertDialog({title: "Delete Failed",description: "Failed to delete transcription. Please try again.",});@@ -161,7 +145,7 @@ export default function ControlPanel() {<div className="min-h-screen bg-white"><ConfirmDialogopen={confirmDialog.open}- onOpenChange={(open) => setConfirmDialog((prev) => ({ ...prev, open }))}+ onOpenChange={hideConfirmDialog}title={confirmDialog.title}description={confirmDialog.description}onConfirm={confirmDialog.onConfirm}@@ -170,7 +154,7 @@ export default function ControlPanel() {<AlertDialogopen={alertDialog.open}- onOpenChange={(open) => setAlertDialog((prev) => ({ ...prev, open }))}+ onOpenChange={hideAlertDialog}title={alertDialog.title}description={alertDialog.description}onOk={() => {}}diff --git a/src/components/OnboardingFlow.tsx b/src/components/OnboardingFlow.tsxindex b474407a6..2b23adff8 100644--- a/src/components/OnboardingFlow.tsx+++ b/src/components/OnboardingFlow.tsx@@ -25,10 +25,13 @@ import ApiKeyInput from "./ui/ApiKeyInput";import PermissionCard from "./ui/PermissionCard";import StepProgress from "./ui/StepProgress";import { AlertDialog } from "./ui/dialog";+import { useLocalStorage } from "../hooks/useLocalStorage";+import { useDialogs } from "../hooks/useDialogs";import { useWhisper } from "../hooks/useWhisper";import { usePermissions } from "../hooks/usePermissions";import { useClipboard } from "../hooks/useClipboard";-import { getLanguageLabel, REASONING_MODEL_OPTIONS, getReasoningModelLabel } from "../utils/languages";+import { useSettings } from "../hooks/useSettings";+import { getLanguageLabel, getReasoningModelLabel } from "../utils/languages";import LanguageSelector from "./ui/LanguageSelector";interface OnboardingFlowProps {@@ -36,42 +39,41 @@ interface OnboardingFlowProps {}export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {- const [currentStep, setCurrentStep] = useState(() => {- // Load the current step from localStorage on component mount- const savedStep = localStorage.getItem("onboardingCurrentStep");- return savedStep ? parseInt(savedStep, 10) : 0;- });- const [useLocalWhisper, setUseLocalWhisper] = useState(() => {- // Load saved setting or default to false- const saved = localStorage.getItem("useLocalWhisper");- return saved === "true";- });- const [apiKey, setApiKey] = useState("");- const [whisperModel, setWhisperModel] = useState("base");- const [hotkey, setHotkey] = useState("`");- const [preferredLanguage, setPreferredLanguage] = useState(() => {- // Load saved language or default to English- const saved = localStorage.getItem("preferredLanguage");- return saved || "en";- });- // Reasoning model is enabled by default (configured in settings)- const useReasoningModel = true;- const reasoningModel = "gpt-3.5-turbo";-- const [alertDialog, setAlertDialog] = useState<{- open: boolean;- title: string;- description?: string;- }>({- open: false,- title: "",- });+ const [currentStep, setCurrentStep, removeCurrentStep] = useLocalStorage(+ "onboardingCurrentStep",+ 0,+ {+ serialize: String,+ deserialize: (value) => parseInt(value, 10),+ }+ );++ const {+ useLocalWhisper,+ whisperModel,+ preferredLanguage,+ useReasoningModel,+ reasoningModel,+ openaiApiKey,+ dictationKey,+ setUseLocalWhisper,+ setWhisperModel,+ setPreferredLanguage,+ setOpenaiApiKey,+ setDictationKey,+ updateTranscriptionSettings,+ updateReasoningSettings,+ updateApiKeys,+ } = useSettings();++ const [apiKey, setApiKey] = useState(openaiApiKey);+ const [hotkey, setHotkey] = useState(dictationKey || "`");+ const { alertDialog, showAlertDialog, hideAlertDialog } = useDialogs();const practiceTextareaRef = useRef<HTMLInputElement>(null);- // Use our custom hooks- const whisperHook = useWhisper(setAlertDialog);- const permissionsHook = usePermissions(setAlertDialog);- const { pasteFromClipboard } = useClipboard(setAlertDialog);+ const whisperHook = useWhisper(showAlertDialog);+ const permissionsHook = usePermissions(showAlertDialog);+ const { pasteFromClipboard } = useClipboard(showAlertDialog);const steps = [{ title: "Welcome", icon: Sparkles },@@ -84,14 +86,11 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {];useEffect(() => {- // Set up progress listenerswhisperHook.setupProgressListener();}, [whisperHook]);- // Helper function to update processing mode and save immediatelyconst updateProcessingMode = (useLocal: boolean) => {- setUseLocalWhisper(useLocal);- localStorage.setItem("useLocalWhisper", useLocal.toString());+ updateTranscriptionSettings({ useLocalWhisper: useLocal });};useEffect(() => {@@ -102,13 +101,10 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {}}, [currentStep]);- const saveSettings = async () => {- localStorage.setItem("useLocalWhisper", useLocalWhisper.toString());- localStorage.setItem("whisperModel", whisperModel);- localStorage.setItem("dictationKey", hotkey);- localStorage.setItem("preferredLanguage", preferredLanguage);- localStorage.setItem("useReasoningModel", useReasoningModel.toString());- localStorage.setItem("reasoningModel", reasoningModel);+ const saveSettings = useCallback(async () => {+ updateTranscriptionSettings({ whisperModel, preferredLanguage });+ setDictationKey(hotkey);+localStorage.setItem("micPermissionGranted",permissionsHook.micPermissionGranted.toString()@@ -119,42 +115,50 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {);localStorage.setItem("onboardingCompleted", "true");- if (!useLocalWhisper && apiKey) {+ if (!useLocalWhisper && apiKey.trim()) {await window.electronAPI.saveOpenAIKey(apiKey);- localStorage.setItem("openaiApiKey", apiKey);+ updateApiKeys({ openaiApiKey: apiKey });}- };-- const nextStep = () => {+ }, [+ whisperModel,+ hotkey,+ preferredLanguage,+ permissionsHook.micPermissionGranted,+ permissionsHook.accessibilityPermissionGranted,+ useLocalWhisper,+ apiKey,+ updateTranscriptionSettings,+ updateApiKeys,+ setDictationKey,+ ]);++ const nextStep = useCallback(() => {if (currentStep < steps.length - 1) {const newStep = currentStep + 1;setCurrentStep(newStep);- localStorage.setItem("onboardingCurrentStep", newStep.toString());// Show dictation panel when moving from permissions step (3) to hotkey step (4)if (currentStep === 3 && newStep === 4) {- // Show dictation panel after permissions are grantedif (window.electronAPI?.showDictationPanel) {window.electronAPI.showDictationPanel();}}}- };+ }, [currentStep, setCurrentStep, steps.length]);- const prevStep = () => {+ const prevStep = useCallback(() => {if (currentStep > 0) {const newStep = currentStep - 1;setCurrentStep(newStep);- localStorage.setItem("onboardingCurrentStep", newStep.toString());}- };+ }, [currentStep, setCurrentStep]);- const finishOnboarding = async () => {+ const finishOnboarding = useCallback(async () => {await saveSettings();// Clear the onboarding step since we're done- localStorage.removeItem("onboardingCurrentStep");+ removeCurrentStep();onComplete();- };+ }, [saveSettings, removeCurrentStep, onComplete]);const renderStep = () => {switch (currentStep) {@@ -351,7 +355,6 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {<li>5. Copy and paste it here</li></ol></div>-</div>)}@@ -366,8 +369,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {<LanguageSelectorvalue={preferredLanguage}onChange={(value) => {- setPreferredLanguage(value);- localStorage.setItem("preferredLanguage", value);+ updateTranscriptionSettings({ preferredLanguage: value });}}className="w-full"/>@@ -717,7 +719,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {><AlertDialogopen={alertDialog.open}- onOpenChange={(open) => setAlertDialog((prev) => ({ ...prev, open }))}+ onOpenChange={(open) => !open && hideAlertDialog()}title={alertDialog.title}description={alertDialog.description}onOk={() => {}}diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex b4b5d25bf..2ab6d645e 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -1,7 +1,7 @@-import React, { useState, useEffect } from "react";-import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";+import React, { useState, useCallback, useEffect } from "react";import { Button } from "./ui/button";import { Input } from "./ui/input";+import { Card, CardContent } from "./ui/card";import {RefreshCw,Download,@@ -19,23 +19,19 @@ import WhisperModelPicker from "./WhisperModelPicker";import ProcessingModeSelector from "./ui/ProcessingModeSelector";import ApiKeyInput from "./ui/ApiKeyInput";import { ConfirmDialog, AlertDialog } from "./ui/dialog";+import { useSettings } from "../hooks/useSettings";+import { useDialogs } from "../hooks/useDialogs";import { useWhisper } from "../hooks/useWhisper";import { usePermissions } from "../hooks/usePermissions";import { useClipboard } from "../hooks/useClipboard";-import {- getLanguageLabel,- getAllReasoningModels,- getModelProvider,- REASONING_PROVIDERS,-} from "../utils/languages";+import { REASONING_PROVIDERS } from "../utils/languages";import LanguageSelector from "./ui/LanguageSelector";-import type { TranscriptionItem } from "../types/electron";interface SettingsPageProps {onBack: () => void;}-type SettingsSection =+type SettingsSectionType =| "transcription"| "reasoning"| "hotkey"@@ -44,23 +40,47 @@ type SettingsSection =export default function SettingsPage({ onBack }: SettingsPageProps) {const [activeSection, setActiveSection] =- useState<SettingsSection>("transcription");-- // Basic settings- const [key, setKey] = useState("");- const [apiKey, setApiKey] = useState("");- const [useLocalWhisper, setUseLocalWhisper] = useState(false);- const [whisperModel, setWhisperModel] = useState("base");- const [allowOpenAIFallback, setAllowOpenAIFallback] = useState(false);- const [allowLocalFallback, setAllowLocalFallback] = useState(false);- const [fallbackWhisperModel, setFallbackWhisperModel] = useState("base");- const [preferredLanguage, setPreferredLanguage] = useState("en");-- // Reasoning model settings- const [useReasoningModel, setUseReasoningModel] = useState(true);- const [reasoningModel, setReasoningModel] = useState("gpt-3.5-turbo");- const [reasoningProvider, setReasoningProvider] = useState("openai");- const [anthropicApiKey, setAnthropicApiKey] = useState("");+ useState<SettingsSectionType>("transcription");++ // Use custom hooks+ const {+ confirmDialog,+ alertDialog,+ showConfirmDialog,+ showAlertDialog,+ hideConfirmDialog,+ hideAlertDialog,+ } = useDialogs();++ const {+ useLocalWhisper,+ whisperModel,+ allowOpenAIFallback,+ allowLocalFallback,+ fallbackWhisperModel,+ preferredLanguage,+ useReasoningModel,+ reasoningModel,+ reasoningProvider,+ openaiApiKey,+ anthropicApiKey,+ dictationKey,+ setUseLocalWhisper,+ setWhisperModel,+ setAllowOpenAIFallback,+ setAllowLocalFallback,+ setFallbackWhisperModel,+ setPreferredLanguage,+ setUseReasoningModel,+ setReasoningModel,+ setReasoningProvider,+ setOpenaiApiKey,+ setAnthropicApiKey,+ setDictationKey,+ updateTranscriptionSettings,+ updateReasoningSettings,+ updateApiKeys,+ } = useSettings();// Update stateconst [currentVersion, setCurrentVersion] = useState<string>("");@@ -78,85 +98,14 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {releaseNotes?: string;}>({});- // Dialog states- const [confirmDialog, setConfirmDialog] = useState<{- open: boolean;- title: string;- description?: string;- onConfirm: () => void;- variant?: "default" | "destructive";- }>({- open: false,- title: "",- onConfirm: () => {},- });- const [alertDialog, setAlertDialog] = useState<{- open: boolean;- title: string;- description?: string;- }>({- open: false,- title: "",- });-- // Custom hooks- const whisperHook = useWhisper(setAlertDialog);- const permissionsHook = usePermissions(setAlertDialog);- const { pasteFromClipboardWithFallback } = useClipboard(setAlertDialog);+ const whisperHook = useWhisper(showAlertDialog);+ const permissionsHook = usePermissions(showAlertDialog);+ const { pasteFromClipboardWithFallback } = useClipboard(showAlertDialog);useEffect(() => {- // Load saved settings- const savedKey = localStorage.getItem("dictationKey");- if (savedKey) setKey(savedKey);-- const savedUseLocal = localStorage.getItem("useLocalWhisper") === "true";- const savedModel = localStorage.getItem("whisperModel") || "base";- const savedAllowOpenAIFallback =- localStorage.getItem("allowOpenAIFallback") === "true";- const savedAllowLocalFallback =- localStorage.getItem("allowLocalFallback") === "true";- const savedFallbackModel =- localStorage.getItem("fallbackWhisperModel") || "base";- const savedLanguage = localStorage.getItem("preferredLanguage") || "en";- const savedUseReasoning =- localStorage.getItem("useReasoningModel") !== "false"; // Default true- const savedReasoningModel =- localStorage.getItem("reasoningModel") || "gpt-3.5-turbo";-- setUseLocalWhisper(savedUseLocal);- setWhisperModel(savedModel);- setAllowOpenAIFallback(savedAllowOpenAIFallback);- setAllowLocalFallback(savedAllowLocalFallback);- setFallbackWhisperModel(savedFallbackModel);- setPreferredLanguage(savedLanguage);- setUseReasoningModel(savedUseReasoning);- setReasoningModel(savedReasoningModel);- setReasoningProvider(getModelProvider(savedReasoningModel));-- // Load API keys- const loadApiKeys = async () => {- try {- const envApiKey = await window.electronAPI?.getOpenAIKey();- if (envApiKey && envApiKey !== "your_openai_api_key_here") {- setApiKey(envApiKey);- } else {- const savedApiKey = localStorage.getItem("openaiApiKey");- if (savedApiKey) setApiKey(savedApiKey);- }-- const savedAnthropicKey = localStorage.getItem("anthropicApiKey");- if (savedAnthropicKey) setAnthropicApiKey(savedAnthropicKey);- } catch (error) {- const savedApiKey = localStorage.getItem("openaiApiKey");- if (savedApiKey) setApiKey(savedApiKey);- }- };-- loadApiKeys();whisperHook.checkWhisperInstallation();whisperHook.setupProgressListener();- // Initialize update functionalityconst initializeUpdateData = async () => {try {const versionResult = await window.electronAPI?.getAppVersion();@@ -171,7 +120,6 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {initializeUpdateData();- // Set up update event listenersif (window.electronAPI) {window.electronAPI.onUpdateAvailable?.((event, info) => {setUpdateStatus((prev) => ({ ...prev, updateAvailable: true }));@@ -197,46 +145,18 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {console.error("Update error:", error);});}- }, []);-- const saveReasoningSettings = () => {- console.log(`π§ [Settings] π§ Saving reasoning settings...`);- console.log(`π§ [Settings] π§ useReasoningModel: ${useReasoningModel}`);- console.log(`π§ [Settings] π§ reasoningModel: ${reasoningModel}`);- console.log(`π§ [Settings] π§ reasoningProvider: ${reasoningProvider}`);- console.log(`π§ [Settings] π§ apiKey: ${apiKey ? "SET" : "NOT SET"}`);- console.log(- `π§ [Settings] π§ anthropicApiKey: ${anthropicApiKey ? "SET" : "NOT SET"}`- );-- localStorage.setItem("useReasoningModel", useReasoningModel.toString());- localStorage.setItem("reasoningModel", reasoningModel);-- // Save provider-specific API keys- if (reasoningProvider === "openai" && apiKey.trim()) {- localStorage.setItem("openaiApiKey", apiKey);- console.log(`π§ [Settings] π§ OpenAI API key saved for reasoning`);- } else if (reasoningProvider === "anthropic" && anthropicApiKey.trim()) {- localStorage.setItem("anthropicApiKey", anthropicApiKey);- console.log(`π§ [Settings] π§ Anthropic API key saved for reasoning`);- } else {- console.log(- `π§ [Settings] β οΈ No API key provided for ${reasoningProvider}`- );- }-- console.log(`π§ [Settings] β Reasoning settings saved successfully`);- console.log(- `π§ [Settings] β AI text enhancement: ${- useReasoningModel ? "ENABLED" : "DISABLED"- }`- );- console.log(- `π§ [Settings] β Using: ${reasoningProvider} ${reasoningModel}`- );+ }, [whisperHook]);++ const saveReasoningSettings = useCallback(() => {+ updateReasoningSettings({ useReasoningModel, reasoningModel });+ updateApiKeys({+ ...(reasoningProvider === "openai" &&+ openaiApiKey.trim() && { openaiApiKey }),+ ...(reasoningProvider === "anthropic" &&+ anthropicApiKey.trim() && { anthropicApiKey }),+ });- setAlertDialog({- open: true,+ showAlertDialog({title: "Reasoning Settings Saved",description: `AI text enhancement ${useReasoningModel ? "enabled" : "disabled"@@ -246,28 +166,33 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {]?.name || reasoningProvider} ${reasoningModel}`,});- };-- const saveApiKey = async () => {+ }, [+ useReasoningModel,+ reasoningModel,+ reasoningProvider,+ openaiApiKey,+ anthropicApiKey,+ updateReasoningSettings,+ updateApiKeys,+ showAlertDialog,+ ]);++ const saveApiKey = useCallback(async () => {try {- await window.electronAPI?.saveOpenAIKey(apiKey);- localStorage.setItem("openaiApiKey", apiKey);- localStorage.setItem("allowLocalFallback", allowLocalFallback.toString());- localStorage.setItem("fallbackWhisperModel", fallbackWhisperModel);+ await window.electronAPI?.saveOpenAIKey(openaiApiKey);+ updateApiKeys({ openaiApiKey });+ updateTranscriptionSettings({ allowLocalFallback, fallbackWhisperModel });try {- await window.electronAPI?.createProductionEnvFile(apiKey);- setAlertDialog({- open: true,+ await window.electronAPI?.createProductionEnvFile(openaiApiKey);+ showAlertDialog({title: "API Key Saved",- description: `OpenAI API key inscribed successfully! Your credentials have been securely recorded for transcription services.${+ description: `OpenAI API key saved successfully! Your credentials have been securely recorded for transcription services.${allowLocalFallback ? " Local Whisper fallback is enabled." : ""}`,});} catch (envError) {- console.log("Could not create production .env file:", envError);- setAlertDialog({- open: true,+ showAlertDialog({title: "API Key Saved",description: `OpenAI API key saved successfully and will be available for transcription${allowLocalFallback ? " with Local Whisper fallback enabled" : ""@@ -276,52 +201,30 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {}} catch (error) {console.error("Failed to save API key:", error);- localStorage.setItem("openaiApiKey", apiKey);- localStorage.setItem("allowLocalFallback", allowLocalFallback.toString());- localStorage.setItem("fallbackWhisperModel", fallbackWhisperModel);- setAlertDialog({- open: true,+ updateApiKeys({ openaiApiKey });+ updateTranscriptionSettings({ allowLocalFallback, fallbackWhisperModel });+ showAlertDialog({title: "API Key Saved",description: "OpenAI API key saved to localStorage (fallback mode)",});}- };-- const saveWhisperSettings = () => {- localStorage.setItem("useLocalWhisper", useLocalWhisper.toString());- localStorage.setItem("whisperModel", whisperModel);- localStorage.setItem("allowOpenAIFallback", allowOpenAIFallback.toString());-- // SECURITY: Only save API key if fallback is enabled and key is provided- if (allowOpenAIFallback && apiKey.trim()) {- localStorage.setItem("openaiApiKey", apiKey);- } else if (!allowOpenAIFallback) {- localStorage.removeItem("openaiApiKey");- }-- setAlertDialog({- open: true,- title: "Settings Saved",- description: `Whisper settings saved! ${- useLocalWhisper- ? `Using local model: ${whisperModel}${- allowOpenAIFallback ? " with OpenAI fallback" : ""- }`- : "Using OpenAI API"- }`,- });- };+ }, [+ openaiApiKey,+ allowLocalFallback,+ fallbackWhisperModel,+ updateApiKeys,+ updateTranscriptionSettings,+ showAlertDialog,+ ]);const resetAccessibilityPermissions = () => {const message = `π RESET ACCESSIBILITY PERMISSIONS\n\nIf you've rebuilt or reinstalled OpenWispr and automatic inscription isn't functioning, you may have obsolete permissions from the previous version.\n\nπ STEP-BY-STEP RESTORATION:\n\n1οΈβ£ Open System Settings (or System Preferences)\n β’ macOS Ventura+: Apple Menu β System Settings\n β’ Older macOS: Apple Menu β System Preferences\n\n2οΈβ£ Navigate to Privacy & Security β Accessibility\n\n3οΈβ£ Look for obsolete OpenWispr entries:\n β’ Any entries named "OpenWispr"\n β’ Any entries named "Electron"\n β’ Any entries with unclear or generic names\n β’ Entries pointing to old application locations\n\n4οΈβ£ Remove ALL obsolete entries:\n β’ Select each old entry\n β’ Click the minus (-) button\n β’ Enter your password if prompted\n\n5οΈβ£ Add the current OpenWispr:\n β’ Click the plus (+) button\n β’ Navigate to and select the CURRENT OpenWispr app\n β’ Ensure the checkbox is ENABLED\n\n6οΈβ£ Restart OpenWispr completely\n\nπ‘ This is very common during development when rebuilding applications!\n\nClick OK when you're ready to open System Settings.`;- setConfirmDialog({- open: true,+ showConfirmDialog({title: "Reset Accessibility Permissions",description: message,onConfirm: () => {- setAlertDialog({- open: true,+ showAlertDialog({title: "Opening System Settings",description:"Opening System Settings... Look for the Accessibility section under Privacy & Security.",@@ -337,17 +240,14 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {const saveKey = async () => {try {- localStorage.setItem("dictationKey", key);- await window.electronAPI?.updateHotkey(key);- setAlertDialog({- open: true,+ await window.electronAPI?.updateHotkey(dictationKey);+ showAlertDialog({title: "Key Saved",- description: `Dictation key inscribed: ${key}`,+ description: `Dictation key saved: ${dictationKey}`,});} catch (error) {console.error("Failed to update hotkey:", error);- setAlertDialog({- open: true,+ showAlertDialog({title: "Error",description: `Failed to update hotkey: ${error.message}`,});@@ -356,18 +256,26 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {const sidebarItems = [{- id: "transcription" as SettingsSection,+ id: "transcription" as SettingsSectionType,label: "Transcription Setup",icon: Settings,},{- id: "reasoning" as SettingsSection,+ id: "reasoning" as SettingsSectionType,label: "Reasoning Setup",icon: Brain,},- { id: "hotkey" as SettingsSection, label: "Hotkey Setup", icon: Keyboard },- { id: "updates" as SettingsSection, label: "App Updates", icon: RefreshCw },- { id: "about" as SettingsSection, label: "About", icon: Info },+ {+ id: "hotkey" as SettingsSectionType,+ label: "Hotkey Setup",+ icon: Keyboard,+ },+ {+ id: "updates" as SettingsSectionType,+ label: "App Updates",+ icon: RefreshCw,+ },+ { id: "about" as SettingsSectionType, label: "About", icon: Info },];const renderSectionContent = () => {@@ -383,12 +291,7 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {useLocalWhisper={useLocalWhisper}setUseLocalWhisper={(value) => {setUseLocalWhisper(value);- localStorage.setItem("useLocalWhisper", value.toString());- console.log(- `π§ [Settings] Transcription mode switched to: ${- value ? "LOCAL" : "OPENAI API"- }`- );+ updateTranscriptionSettings({ useLocalWhisper: value });}}/></div>@@ -397,8 +300,8 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {<div className="space-y-4 p-4 bg-blue-50 border border-blue-200 rounded-xl"><h4 className="font-medium text-blue-900">OpenAI API Setup</h4><ApiKeyInput- apiKey={apiKey}- setApiKey={setApiKey}+ apiKey={openaiApiKey}+ setApiKey={setOpenaiApiKey}helpText="Get your API key from platform.openai.com"/></div>@@ -423,7 +326,7 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {value={preferredLanguage}onChange={(value) => {setPreferredLanguage(value);- localStorage.setItem("preferredLanguage", value);+ updateTranscriptionSettings({ preferredLanguage: value });}}className="w-full"/>@@ -431,50 +334,17 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {<ButtononClick={() => {- console.log(- `πΎ [Settings] πΎ Saving transcription settings...`- );- console.log(- `πΎ [Settings] πΎ useLocalWhisper: ${useLocalWhisper}`- );- console.log(`πΎ [Settings] πΎ whisperModel: ${whisperModel}`);- console.log(- `πΎ [Settings] πΎ preferredLanguage: ${preferredLanguage}`- );- console.log(- `πΎ [Settings] πΎ apiKey: ${apiKey ? "SET" : "NOT SET"}`- );+ updateTranscriptionSettings({+ useLocalWhisper,+ whisperModel,+ preferredLanguage,+ });- localStorage.setItem(- "useLocalWhisper",- useLocalWhisper.toString()- );- localStorage.setItem("whisperModel", whisperModel);- localStorage.setItem("preferredLanguage", preferredLanguage);- if (!useLocalWhisper && apiKey.trim()) {- localStorage.setItem("openaiApiKey", apiKey);- console.log(`πΎ [Settings] πΎ OpenAI API key saved`);- } else if (useLocalWhisper) {- console.log(- `πΎ [Settings] πΎ Local Whisper mode - no API key needed`- );- } else {- console.log(- `πΎ [Settings] β οΈ No API key provided for OpenAI mode`- );+ if (!useLocalWhisper && openaiApiKey.trim()) {+ updateApiKeys({ openaiApiKey });}- console.log(- `πΎ [Settings] β Transcription settings saved successfully`- );- console.log(- `πΎ [Settings] β Mode set to: ${- useLocalWhisper ? "LOCAL WHISPER" : "OPENAI API"- }`- );-- setAlertDialog({- open: true,+ showAlertDialog({title: "Settings Saved",description: `Transcription mode: ${useLocalWhisper ? "Local Whisper" : "OpenAI API"@@ -518,15 +388,7 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {onChange={(e) => {const enabled = e.target.checked;setUseReasoningModel(enabled);- localStorage.setItem(- "useReasoningModel",- enabled.toString()- );- console.log(- `π§ [Settings] AI text enhancement ${- enabled ? "ENABLED" : "DISABLED"- }`- );+ updateReasoningSettings({ useReasoningModel: enabled });}}/><div@@ -551,17 +413,7 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {<selectvalue={reasoningProvider}onChange={(e) => {- const newProvider = e.target.value;- setReasoningProvider(newProvider);-- // Set default model for the provider- const providerModels =- REASONING_PROVIDERS[- newProvider as keyof typeof REASONING_PROVIDERS- ]?.models;- if (providerModels && providerModels.length > 0) {- setReasoningModel(providerModels[0].value);- }+ setReasoningProvider(e.target.value);}}className="w-full text-sm border border-blue-300 rounded-md p-2 bg-white focus:border-blue-500 focus:ring-1 focus:ring-blue-500">@@ -601,8 +453,8 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {OpenAI API Key</h4><ApiKeyInput- apiKey={apiKey}- setApiKey={setApiKey}+ apiKey={openaiApiKey}+ setApiKey={setOpenaiApiKey}helpText="Same as your transcription API key"/></div>@@ -662,11 +514,15 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {<h4 className="font-medium text-blue-900">Activation Key</h4><Inputplaceholder="Current: ` (backtick)"- value={key}- onChange={(e) => setKey(e.target.value)}+ value={dictationKey}+ onChange={(e) => setDictationKey(e.target.value)}className="text-center text-lg font-mono"/>- <Button onClick={saveKey} disabled={!key.trim()} size="sm">+ <Button+ onClick={saveKey}+ disabled={!dictationKey.trim()}+ size="sm"+ >Save Hotkey</Button></div>@@ -754,21 +610,18 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {...prev,updateAvailable: true,}));- setAlertDialog({- open: true,+ showAlertDialog({title: "Update Available",description: `Update available: v${result.version}`,});} else {- setAlertDialog({- open: true,+ showAlertDialog({title: "No Updates",description: result?.message || "No updates available",});}} catch (error: any) {- setAlertDialog({- open: true,+ showAlertDialog({title: "Update Check Failed",description: `Error checking for updates: ${error.message}`,});@@ -803,15 +656,13 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {...prev,updateDownloaded: true,}));- setAlertDialog({- open: true,+ showAlertDialog({title: "Update Downloaded",description:"Update downloaded successfully! You can now install it.",});} catch (error: any) {- setAlertDialog({- open: true,+ showAlertDialog({title: "Download Failed",description: `Error downloading update: ${error.message}`,});@@ -842,8 +693,7 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {try {await window.electronAPI?.installUpdate();} catch (error: any) {- setAlertDialog({- open: true,+ showAlertDialog({title: "Install Failed",description: `Error installing update: ${error.message}`,});@@ -931,8 +781,7 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {<div className="border-t border-gray-200 pt-4 space-y-3"><ButtononClick={() => {- setConfirmDialog({- open: true,+ showConfirmDialog({title: "Reset Onboarding",description:"Are you sure you want to reset the onboarding process? This will clear your setup and show the welcome flow again.",@@ -952,8 +801,7 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {<ButtononClick={() => {- setConfirmDialog({- open: true,+ showConfirmDialog({title: "β οΈ DANGER: Cleanup App Data",description:"This will permanently delete ALL OpenWispr data including:\n\nβ’ Database and transcriptions\nβ’ Local storage settings\nβ’ Downloaded Whisper models\nβ’ Environment files\n\nYou will need to manually remove app permissions in System Settings.\n\nThis action cannot be undone. Are you sure?",@@ -961,8 +809,7 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {window.electronAPI?.cleanupApp().then(() => {- setAlertDialog({- open: true,+ showAlertDialog({title: "Cleanup Completed",description:"β Cleanup completed! All app data has been removed.",@@ -972,8 +819,7 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {}, 1000);}).catch((error) => {- setAlertDialog({- open: true,+ showAlertDialog({title: "Cleanup Failed",description: `β Cleanup failed: ${error.message}`,});@@ -1001,7 +847,7 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {<div className="min-h-screen bg-white"><ConfirmDialogopen={confirmDialog.open}- onOpenChange={(open) => setConfirmDialog((prev) => ({ ...prev, open }))}+ onOpenChange={(open) => !open && hideConfirmDialog()}title={confirmDialog.title}description={confirmDialog.description}onConfirm={confirmDialog.onConfirm}@@ -1010,7 +856,7 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {<AlertDialogopen={alertDialog.open}- onOpenChange={(open) => setAlertDialog((prev) => ({ ...prev, open }))}+ onOpenChange={(open) => !open && hideAlertDialog()}title={alertDialog.title}description={alertDialog.description}onOk={() => {}}diff --git a/src/components/WhisperModelPicker.tsx b/src/components/WhisperModelPicker.tsxindex 2bef9a6b0..e72dfc4bb 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 { useDialogs } from "../hooks/useDialogs";import { useToast } from "./ui/Toast";interface WhisperModel {@@ -104,26 +105,16 @@ export default function WhisperModelPicker({totalBytes: 0,});const [loadingModels, setLoadingModels] = useState(false);- const [confirmDialog, setConfirmDialog] = useState<{- open: boolean;- title: string;- description?: string;- onConfirm: () => void;- variant?: "default" | "destructive";- }>({- open: false,- title: "",- onConfirm: () => {},- });- const [alertDialog, setAlertDialog] = useState<{- open: boolean;- title: string;- description?: string;- }>({- open: false,- title: "",- });+ // Use custom hooks+ const {+ confirmDialog,+ alertDialog,+ showConfirmDialog,+ showAlertDialog,+ hideConfirmDialog,+ hideAlertDialog,+ } = useDialogs();const { toast } = useToast();const styles = useMemo(() => VARIANT_STYLES[variant], [variant]);@@ -176,17 +167,14 @@ export default function WhisperModelPicker({});if (data.error?.includes("interrupted by user")) {- // Toast is handled by the cancel button - don't show duplicate here} else if (data.error?.includes("timeout")) {- setAlertDialog({- open: true,+ showAlertDialog({title: "Download Timeout",description:"Model download timed out. Please check your internet connection and try again.",});} else {- setAlertDialog({- open: true,+ showAlertDialog({title: "Download Failed",description: `Model download failed: ${data.error || "Unknown error"@@ -195,7 +183,7 @@ export default function WhisperModelPicker({}}},- [loadModelList]+ [loadModelList, showAlertDialog]);useEffect(() => {@@ -223,8 +211,7 @@ export default function WhisperModelPicker({} else {// Only show error if it's not a cancellationif (!result.error?.includes("interrupted by user")) {- setAlertDialog({- open: true,+ showAlertDialog({title: "Download Failed",description: `Failed to download model "${modelName}": ${result.error}`,});@@ -234,8 +221,7 @@ export default function WhisperModelPicker({} catch (error) {// Only show error if it's not a cancellationif (!error.toString().includes("interrupted by user")) {- setAlertDialog({- open: true,+ showAlertDialog({title: "Download Failed",description: `Failed to download model "${modelName}": ${error}`,});@@ -250,59 +236,61 @@ export default function WhisperModelPicker({});}},- [loadModelList, onModelSelect]+ [loadModelList, onModelSelect, showAlertDialog]);- const cancelDownload = useCallback(async (modelName: string) => {- setConfirmDialog({- open: true,- title: "Cancel Download",- description: `Are you sure you want to cancel the download of "${modelName}"?`,- onConfirm: async () => {- try {- const result = await window.electronAPI.cancelWhisperDownload();+ const cancelDownload = useCallback(+ async (modelName: string) => {+ showConfirmDialog({+ title: "Cancel Download",+ description: `Are you sure you want to cancel the download of "${modelName}"?`,+ onConfirm: async () => {+ try {+ const result = await window.electronAPI.cancelWhisperDownload();- if (result.success) {- setDownloadingModel(null);- setDownloadProgress({- percentage: 0,- downloadedBytes: 0,- totalBytes: 0,- });- 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}`,+ if (result.success) {+ setDownloadingModel(null);+ setDownloadProgress({+ percentage: 0,+ downloadedBytes: 0,+ totalBytes: 0,+ });+ 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")+ ) {+ showAlertDialog({+ title: "Cancel Failed",+ description: `Failed to cancel download: ${result.error}`,+ });+ }}+ } catch (error) {+ console.error(+ `Failed to cancel download of "${modelName}":`,+ error+ );+ showAlertDialog({+ title: "Cancel Failed",+ description: `Failed to cancel download: ${error}`,+ });}- } catch (error) {- console.error(`Failed to cancel download of "${modelName}":`, error);- setAlertDialog({- open: true,- title: "Cancel Failed",- description: `Failed to cancel download: ${error}`,- });- }- },- });- }, []);+ },+ });+ },+ [showConfirmDialog, showAlertDialog, toast]+ );const deleteModel = useCallback(async (modelName: string) => {- setConfirmDialog({- open: true,+ showConfirmDialog({title: "Delete Model",description: `Are you sure you want to delete the "${modelName}" model? This will free up disk space but you'll need to re-download it if you want to use it again.`,onConfirm: async () => {@@ -312,22 +300,19 @@ export default function WhisperModelPicker({);if (result.success) {- setAlertDialog({- open: true,+ showAlertDialog({title: "Model Deleted",description: `Model "${modelName}" deleted successfully! Freed ${result.freed_mb}MB of disk space.`,});loadModelList();} else {- setAlertDialog({- open: true,+ showAlertDialog({title: "Delete Failed",description: `Failed to delete model "${modelName}": ${result.error}`,});}} catch (error) {- setAlertDialog({- open: true,+ showAlertDialog({title: "Delete Failed",description: `Failed to delete model "${modelName}": ${error}`,});@@ -336,7 +321,7 @@ export default function WhisperModelPicker({variant: "destructive",});},- [loadModelList]+ [loadModelList, showConfirmDialog, showAlertDialog]);const progressDisplay = useMemo(() => {@@ -376,9 +361,7 @@ export default function WhisperModelPicker({<div className="p-4"><ConfirmDialogopen={confirmDialog.open}- onOpenChange={(open) =>- setConfirmDialog((prev) => ({ ...prev, open }))- }+ onOpenChange={(open) => !open && hideConfirmDialog()}title={confirmDialog.title}description={confirmDialog.description}onConfirm={confirmDialog.onConfirm}@@ -387,7 +370,7 @@ export default function WhisperModelPicker({<AlertDialogopen={alertDialog.open}- onOpenChange={(open) => setAlertDialog((prev) => ({ ...prev, open }))}+ onOpenChange={(open) => !open && hideAlertDialog()}title={alertDialog.title}description={alertDialog.description}onOk={() => {}}diff --git a/src/components/ui/SettingsSection.tsx b/src/components/ui/SettingsSection.tsxnew file mode 100644index 000000000..db1bf6208--- /dev/null+++ b/src/components/ui/SettingsSection.tsx@@ -0,0 +1,54 @@+import React from "react";++interface SettingsSectionProps {+ title: string;+ description?: string;+ children: React.ReactNode;+ className?: string;+}++export const SettingsSection: React.FC<SettingsSectionProps> = ({+ title,+ description,+ children,+ className = "",+}) => {+ return (+ <div className={`space-y-4 ${className}`}>+ <div>+ <h3 className="text-lg font-semibold text-gray-900 mb-2">{title}</h3>+ {description && (+ <p className="text-sm text-gray-600 mb-4">{description}</p>+ )}+ </div>+ {children}+ </div>+ );+};++interface SettingsGroupProps {+ title?: string;+ children: React.ReactNode;+ variant?: "default" | "highlighted";+ className?: string;+}++export const SettingsGroup: React.FC<SettingsGroupProps> = ({+ title,+ children,+ variant = "default",+ className = "",+}) => {+ const baseClasses = "space-y-4 p-4 rounded-xl border";+ const variantClasses = {+ default: "bg-gray-50 border-gray-200",+ highlighted: "bg-blue-50 border-blue-200",+ };++ return (+ <div className={`${baseClasses} ${variantClasses[variant]} ${className}`}>+ {title && <h4 className="font-medium text-gray-900">{title}</h4>}+ {children}+ </div>+ );+};diff --git a/src/hooks/useClipboard.ts b/src/hooks/useClipboard.tsindex 4032beaca..9827f7cd5 100644--- a/src/hooks/useClipboard.ts+++ b/src/hooks/useClipboard.ts@@ -8,15 +8,11 @@ export interface UseClipboardReturn {}export interface UseClipboardProps {- setAlertDialog: (dialog: {- open: boolean;- title: string;- description?: string;- }) => void;+ showAlertDialog: (dialog: { title: string; description?: string }) => void;}export const useClipboard = (- setAlertDialog?: UseClipboardProps["setAlertDialog"]+ showAlertDialog?: UseClipboardProps["showAlertDialog"]): UseClipboardReturn => {const pasteFromClipboard = useCallback(async (setter: (value: string) => void) => {@@ -59,9 +55,8 @@ export const useClipboard = (console.error("Web clipboard also failed:", err);}- if (setAlertDialog) {- setAlertDialog({- open: true,+ if (showAlertDialog) {+ showAlertDialog({title: "Clipboard Paste Failed",description:"Could not paste from clipboard. Please try typing or using Cmd+V/Ctrl+V.",@@ -72,7 +67,7 @@ export const useClipboard = ();}},- [setAlertDialog]+ [showAlertDialog]);return {diff --git a/src/hooks/useDialogs.ts b/src/hooks/useDialogs.tsnew file mode 100644index 000000000..662dd315e--- /dev/null+++ b/src/hooks/useDialogs.ts@@ -0,0 +1,64 @@+import { useState, useCallback } from "react";++export interface ConfirmDialogState {+ open: boolean;+ title: string;+ description?: string;+ onConfirm: () => void;+ variant?: "default" | "destructive";+}++export interface AlertDialogState {+ open: boolean;+ title: string;+ description?: string;+}++const defaultConfirmDialog: ConfirmDialogState = {+ open: false,+ title: "",+ onConfirm: () => {},+};++const defaultAlertDialog: AlertDialogState = {+ open: false,+ title: "",+};++// Custom hook for managing dialog states+export function useDialogs() {+ const [confirmDialog, setConfirmDialog] = useState<ConfirmDialogState>(defaultConfirmDialog);+ const [alertDialog, setAlertDialog] = useState<AlertDialogState>(defaultAlertDialog);++ const showConfirmDialog = useCallback(+ (options: Omit<ConfirmDialogState, "open">) => {+ setConfirmDialog({ ...options, open: true });+ },+ []+ );++ const showAlertDialog = useCallback(+ (options: Omit<AlertDialogState, "open">) => {+ setAlertDialog({ ...options, open: true });+ },+ []+ );++ const hideConfirmDialog = useCallback(() => {+ setConfirmDialog(defaultConfirmDialog);+ }, []);++ const hideAlertDialog = useCallback(() => {+ setAlertDialog(defaultAlertDialog);+ }, []);++ return {+ confirmDialog,+ alertDialog,+ showConfirmDialog,+ showAlertDialog,+ hideConfirmDialog,+ hideAlertDialog,+ setAlertDialog,+ };+}diff --git a/src/hooks/useLocalStorage.ts b/src/hooks/useLocalStorage.tsnew file mode 100644index 000000000..39b624c63--- /dev/null+++ b/src/hooks/useLocalStorage.ts@@ -0,0 +1,47 @@+import { useState, useCallback } from "react";++export function useLocalStorage<T>(+ key: string,+ defaultValue: T,+ options?: {+ serialize?: (value: T) => string;+ deserialize?: (value: string) => T;+ }+) {+ const serialize = options?.serialize || JSON.stringify;+ const deserialize = options?.deserialize || JSON.parse;++ const [state, setState] = useState<T>(() => {+ try {+ const item = localStorage.getItem(key);+ if (item === null) return defaultValue;+ return deserialize(item);+ } catch {+ return defaultValue;+ }+ });++ const setValue = useCallback(+ (value: T | ((prevState: T) => T)) => {+ try {+ const valueToStore = value instanceof Function ? value(state) : value;+ setState(valueToStore);+ localStorage.setItem(key, serialize(valueToStore));+ } catch (error) {+ console.error(`Error setting localStorage key "${key}":`, error);+ }+ },+ [key, serialize]+ );++ const remove = useCallback(() => {+ try {+ localStorage.removeItem(key);+ setState(defaultValue);+ } catch (error) {+ console.error(`Error removing localStorage key "${key}":`, error);+ }+ }, [key, defaultValue]);++ return [state, setValue, remove] as const;+}diff --git a/src/hooks/usePermissions.ts b/src/hooks/usePermissions.tsindex 495114d77..384fc86fe 100644--- a/src/hooks/usePermissions.ts+++ b/src/hooks/usePermissions.ts@@ -5,7 +5,6 @@ export interface UsePermissionsReturn {micPermissionGranted: boolean;accessibilityPermissionGranted: boolean;- // FunctionsrequestMicPermission: () => Promise<void>;testAccessibilityPermission: () => Promise<void>;setMicPermissionGranted: (granted: boolean) => void;@@ -13,15 +12,11 @@ export interface UsePermissionsReturn {}export interface UsePermissionsProps {- setAlertDialog: (dialog: {- open: boolean;- title: string;- description?: string;- }) => void;+ showAlertDialog: (dialog: { title: string; description?: string }) => void;}export const usePermissions = (- setAlertDialog?: UsePermissionsProps["setAlertDialog"]+ showAlertDialog?: UsePermissionsProps["showAlertDialog"]): UsePermissionsReturn => {const [micPermissionGranted, setMicPermissionGranted] = useState(false);const [accessibilityPermissionGranted, setAccessibilityPermissionGranted] =@@ -33,9 +28,8 @@ export const usePermissions = (setMicPermissionGranted(true);} catch (err) {console.error("Microphone permission denied:", err);- if (setAlertDialog) {- setAlertDialog({- open: true,+ if (showAlertDialog) {+ showAlertDialog({title: "Microphone Permission Required",description:"Please grant microphone permissions to use voice dictation.",@@ -44,15 +38,14 @@ export const usePermissions = (alert("Please grant microphone permissions to use voice dictation.");}}- }, [setAlertDialog]);+ }, [showAlertDialog]);const testAccessibilityPermission = useCallback(async () => {try {await window.electronAPI.pasteText("OpenWispr accessibility test");setAccessibilityPermissionGranted(true);- if (setAlertDialog) {- setAlertDialog({- open: true,+ if (showAlertDialog) {+ showAlertDialog({title: "β Accessibility Test Successful",description:"Accessibility permissions working! Check if the test text appeared in another app.",@@ -64,9 +57,8 @@ export const usePermissions = (}} catch (err) {console.error("Accessibility permission test failed:", err);- if (setAlertDialog) {- setAlertDialog({- open: true,+ if (showAlertDialog) {+ showAlertDialog({title: "β Accessibility Permissions Needed",description:"Please grant accessibility permissions in System Settings to enable automatic text pasting.",@@ -77,7 +69,7 @@ export const usePermissions = ();}}- }, [setAlertDialog]);+ }, [showAlertDialog]);return {micPermissionGranted,diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.tsnew file mode 100644index 000000000..2d8e7a608--- /dev/null+++ b/src/hooks/useSettings.ts@@ -0,0 +1,210 @@+import { useCallback } from "react";+import { useLocalStorage } from "./useLocalStorage";+import { getModelProvider } from "../utils/languages";++export interface TranscriptionSettings {+ useLocalWhisper: boolean;+ whisperModel: string;+ allowOpenAIFallback: boolean;+ allowLocalFallback: boolean;+ fallbackWhisperModel: string;+ preferredLanguage: string;+}++export interface ReasoningSettings {+ useReasoningModel: boolean;+ reasoningModel: string;+ reasoningProvider: string;+}++export interface HotkeySettings {+ dictationKey: string;+}++export interface ApiKeySettings {+ openaiApiKey: string;+ anthropicApiKey: string;+}++export function useSettings() {+ const [useLocalWhisper, setUseLocalWhisper] = useLocalStorage(+ "useLocalWhisper",+ false,+ {+ serialize: String,+ deserialize: (value) => value === "true",+ }+ );++ const [whisperModel, setWhisperModel] = useLocalStorage(+ "whisperModel",+ "base",+ {+ serialize: String,+ deserialize: String,+ }+ );++ const [allowOpenAIFallback, setAllowOpenAIFallback] = useLocalStorage(+ "allowOpenAIFallback",+ false,+ {+ serialize: String,+ deserialize: (value) => value === "true",+ }+ );++ const [allowLocalFallback, setAllowLocalFallback] = useLocalStorage(+ "allowLocalFallback",+ false,+ {+ serialize: String,+ deserialize: (value) => value === "true",+ }+ );++ const [fallbackWhisperModel, setFallbackWhisperModel] = useLocalStorage(+ "fallbackWhisperModel",+ "base",+ {+ serialize: String,+ deserialize: String,+ }+ );++ const [preferredLanguage, setPreferredLanguage] = useLocalStorage(+ "preferredLanguage",+ "en",+ {+ serialize: String,+ deserialize: String,+ }+ );++ // Reasoning settings+ const [useReasoningModel, setUseReasoningModel] = useLocalStorage(+ "useReasoningModel",+ true,+ {+ serialize: String,+ deserialize: (value) => value !== "false", // Default true+ }+ );++ const [reasoningModel, setReasoningModel] = useLocalStorage(+ "reasoningModel",+ "gpt-3.5-turbo",+ {+ serialize: String,+ deserialize: String,+ }+ );++ // API keys+ const [openaiApiKey, setOpenaiApiKey] = useLocalStorage("openaiApiKey", "", {+ serialize: String,+ deserialize: String,+ });++ const [anthropicApiKey, setAnthropicApiKey] = useLocalStorage(+ "anthropicApiKey",+ "",+ {+ serialize: String,+ deserialize: String,+ }+ );++ // Hotkey+ const [dictationKey, setDictationKey] = useLocalStorage("dictationKey", "", {+ serialize: String,+ deserialize: String,+ });++ // Computed values+ const reasoningProvider = getModelProvider(reasoningModel);++ // Batch operations+ const updateTranscriptionSettings = useCallback(+ (settings: Partial<TranscriptionSettings>) => {+ if (settings.useLocalWhisper !== undefined)+ setUseLocalWhisper(settings.useLocalWhisper);+ if (settings.whisperModel !== undefined)+ setWhisperModel(settings.whisperModel);+ if (settings.allowOpenAIFallback !== undefined)+ setAllowOpenAIFallback(settings.allowOpenAIFallback);+ if (settings.allowLocalFallback !== undefined)+ setAllowLocalFallback(settings.allowLocalFallback);+ if (settings.fallbackWhisperModel !== undefined)+ setFallbackWhisperModel(settings.fallbackWhisperModel);+ if (settings.preferredLanguage !== undefined)+ setPreferredLanguage(settings.preferredLanguage);+ },+ [+ setUseLocalWhisper,+ setWhisperModel,+ setAllowOpenAIFallback,+ setAllowLocalFallback,+ setFallbackWhisperModel,+ setPreferredLanguage,+ ]+ );++ const updateReasoningSettings = useCallback(+ (settings: Partial<ReasoningSettings>) => {+ if (settings.useReasoningModel !== undefined)+ setUseReasoningModel(settings.useReasoningModel);+ if (settings.reasoningModel !== undefined)+ setReasoningModel(settings.reasoningModel);+ },+ [setUseReasoningModel, setReasoningModel]+ );++ const updateApiKeys = useCallback(+ (keys: Partial<ApiKeySettings>) => {+ if (keys.openaiApiKey !== undefined) setOpenaiApiKey(keys.openaiApiKey);+ if (keys.anthropicApiKey !== undefined)+ setAnthropicApiKey(keys.anthropicApiKey);+ },+ [setOpenaiApiKey, setAnthropicApiKey]+ );++ return {+ useLocalWhisper,+ whisperModel,+ allowOpenAIFallback,+ allowLocalFallback,+ fallbackWhisperModel,+ preferredLanguage,+ useReasoningModel,+ reasoningModel,+ reasoningProvider,+ openaiApiKey,+ anthropicApiKey,+ dictationKey,+ setUseLocalWhisper,+ setWhisperModel,+ setAllowOpenAIFallback,+ setAllowLocalFallback,+ setFallbackWhisperModel,+ setPreferredLanguage,+ setUseReasoningModel,+ setReasoningModel,+ setReasoningProvider: (provider: string) => {+ const providerModels = {+ openai: "gpt-3.5-turbo",+ anthropic: "claude-3-haiku-20240307",+ };+ setReasoningModel(+ providerModels[provider as keyof typeof providerModels] ||+ "gpt-3.5-turbo"+ );+ },+ setOpenaiApiKey,+ setAnthropicApiKey,+ setDictationKey,+ updateTranscriptionSettings,+ updateReasoningSettings,+ updateApiKeys,+ };+}diff --git a/src/hooks/useWhisper.ts b/src/hooks/useWhisper.tsindex 709db7708..25f001e0d 100644--- a/src/hooks/useWhisper.ts+++ b/src/hooks/useWhisper.ts@@ -8,24 +8,17 @@ export interface UseWhisperReturn {installingWhisper: boolean;installProgress: string;- // FunctionscheckWhisperInstallation: () => Promise<void>;installWhisper: () => Promise<void>;-- // Setup progress listenersetupProgressListener: () => void;}export interface UseWhisperProps {- setAlertDialog: (dialog: {- open: boolean;- title: string;- description?: string;- }) => void;+ showAlertDialog: (dialog: { title: string; description?: string }) => void;}export const useWhisper = (- setAlertDialog?: UseWhisperProps["setAlertDialog"]+ showAlertDialog?: UseWhisperProps["showAlertDialog"]): UseWhisperReturn => {const [whisperInstalled, setWhisperInstalled] = useState(false);const [checkingWhisper, setCheckingWhisper] = useState(false);@@ -58,9 +51,8 @@ export const useWhisper = (setWhisperInstalled(true);setInstallProgress("Installation complete!");} else {- if (setAlertDialog) {- setAlertDialog({- open: true,+ if (showAlertDialog) {+ showAlertDialog({title: "β Whisper Installation Failed",description: `Failed to install Whisper: ${result.message}`,});@@ -70,9 +62,8 @@ export const useWhisper = (}} catch (error) {console.error("Error installing Whisper:", error);- if (setAlertDialog) {- setAlertDialog({- open: true,+ if (showAlertDialog) {+ showAlertDialog({title: "β Whisper Installation Failed",description: `Failed to install Whisper: ${error}`,});@@ -83,7 +74,7 @@ export const useWhisper = (setInstallingWhisper(false);setTimeout(() => setInstallProgress(""), 2000); // Clear progress after 2 seconds}- }, [setAlertDialog]);+ }, [showAlertDialog]);const setupProgressListener = useCallback(() => {window.electronAPI.onWhisperInstallProgress((_, data) => {diff --git a/src/utils/languages.ts b/src/utils/languages.tsindex ddfc9f19a..f168d257a 100644--- a/src/utils/languages.ts+++ b/src/utils/languages.ts@@ -60,7 +60,7 @@ export const LANGUAGE_OPTIONS = [];export const getLanguageLabel = (code: string): string => {- const option = LANGUAGE_OPTIONS.find(lang => lang.value === code);+ const option = LANGUAGE_OPTIONS.find((lang) => lang.value === code);return option?.label || code;};@@ -69,41 +69,53 @@ export const REASONING_PROVIDERS = {openai: {name: "OpenAI",models: [- { value: "gpt-3.5-turbo", label: "GPT-3.5 Turbo", description: "Fast and efficient" },- { value: "gpt-4o-mini", label: "GPT-4o Mini", description: "Higher quality" },- ]+ {+ value: "gpt-3.5-turbo",+ label: "GPT-3.5 Turbo",+ description: "Fast and efficient",+ },+ {+ value: "gpt-4o-mini",+ label: "GPT-4o Mini",+ description: "Higher quality",+ },+ ],},anthropic: {name: "Anthropic",models: [- { value: "claude-3-haiku-20240307", label: "Claude 3 Haiku", description: "Fast and affordable" },- { value: "claude-3-sonnet-20240229", label: "Claude 3 Sonnet", description: "Balanced performance" },- ]- }+ {+ value: "claude-3-haiku-20240307",+ label: "Claude 3 Haiku",+ description: "Fast and affordable",+ },+ {+ value: "claude-3-sonnet-20240229",+ label: "Claude 3 Sonnet",+ description: "Balanced performance",+ },+ ],+ },};-// Get all available models across providersexport const getAllReasoningModels = () => {return Object.entries(REASONING_PROVIDERS).flatMap(([providerId, provider]) =>- provider.models.map(model => ({+ provider.models.map((model) => ({...model,provider: providerId,- fullLabel: `${provider.name} ${model.label}`+ fullLabel: `${provider.name} ${model.label}`,})));};-// Legacy compatibility - returns only OpenAI models for now-export const REASONING_MODEL_OPTIONS = REASONING_PROVIDERS.openai.models;-export const getReasoningModelLabel = (modelId: string): string => {const allModels = getAllReasoningModels();- const model = allModels.find(m => m.value === modelId);+ const model = allModels.find((m) => m.value === modelId);return model?.fullLabel || modelId;};export const getModelProvider = (modelId: string): string => {const allModels = getAllReasoningModels();- const model = allModels.find(m => m.value === modelId);- return model?.provider || 'openai';+ const model = allModels.find((m) => m.value === modelId);+ return model?.provider || "openai";};