Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

refactor: refactored system dialogs to custom component

Gabriel Stein97d98fc910c7
diff --git a/package.json b/package.json
index ba5ab8978..b4d5f5041 100644
--- a/package.json
+++ b/package.json
@@ -51,6 +51,7 @@
"vite": "^6.3.5"
},
"dependencies": {
+ "@radix-ui/react-dialog": "^1.1.14",
"@radix-ui/react-slot": "^1.2.3",
"better-sqlite3": "^11.10.0",
"class-variance-authority": "^0.7.1",
diff --git a/preload.js b/preload.js
index 386505e3d..429a793a1 100644
--- a/preload.js
+++ b/preload.js
@@ -1,55 +1,70 @@
-const { contextBridge, ipcRenderer } = require('electron');
+const { contextBridge, ipcRenderer } = require("electron");
+
+contextBridge.exposeInMainWorld("electronAPI", {
+ pasteText: (text) => ipcRenderer.invoke("paste-text", text),
+ hideWindow: () => ipcRenderer.invoke("hide-window"),
+ onToggleDictation: (callback) => ipcRenderer.on("toggle-dictation", callback),
-contextBridge.exposeInMainWorld('electronAPI', {
- pasteText: (text) => ipcRenderer.invoke('paste-text', text),
- hideWindow: () => ipcRenderer.invoke('hide-window'),
- onToggleDictation: (callback) => ipcRenderer.on('toggle-dictation', callback),
-
// Database functions
- saveTranscription: (text) => ipcRenderer.invoke('db-save-transcription', text),
- getTranscriptions: (limit) => ipcRenderer.invoke('db-get-transcriptions', limit),
- clearTranscriptions: () => ipcRenderer.invoke('db-clear-transcriptions'),
- deleteTranscription: (id) => ipcRenderer.invoke('db-delete-transcription', id),
-
+ saveTranscription: (text) =>
+ ipcRenderer.invoke("db-save-transcription", text),
+ getTranscriptions: (limit) =>
+ ipcRenderer.invoke("db-get-transcriptions", limit),
+ clearTranscriptions: () => ipcRenderer.invoke("db-clear-transcriptions"),
+ deleteTranscription: (id) =>
+ ipcRenderer.invoke("db-delete-transcription", id),
+
// Environment variables
- getOpenAIKey: () => ipcRenderer.invoke('get-openai-key'),
- saveOpenAIKey: (key) => ipcRenderer.invoke('save-openai-key', key),
- createProductionEnvFile: (key) => ipcRenderer.invoke('create-production-env-file', key),
-
+ getOpenAIKey: () => ipcRenderer.invoke("get-openai-key"),
+ saveOpenAIKey: (key) => ipcRenderer.invoke("save-openai-key", key),
+ createProductionEnvFile: (key) =>
+ ipcRenderer.invoke("create-production-env-file", key),
+
// Clipboard functions
- readClipboard: () => ipcRenderer.invoke('read-clipboard'),
-
+ readClipboard: () => ipcRenderer.invoke("read-clipboard"),
+
// Local Whisper functions
- transcribeLocalWhisper: (audioBlob, options) => ipcRenderer.invoke('transcribe-local-whisper', audioBlob, options),
- checkWhisperInstallation: () => ipcRenderer.invoke('check-whisper-installation'),
- installWhisper: () => ipcRenderer.invoke('install-whisper'),
- onWhisperInstallProgress: (callback) => ipcRenderer.on('whisper-install-progress', callback),
- downloadWhisperModel: (modelName) => ipcRenderer.invoke('download-whisper-model', modelName),
- onWhisperDownloadProgress: (callback) => ipcRenderer.on('whisper-download-progress', callback),
- checkModelStatus: (modelName) => ipcRenderer.invoke('check-model-status', modelName),
- listWhisperModels: () => ipcRenderer.invoke('list-whisper-models'),
- deleteWhisperModel: (modelName) => ipcRenderer.invoke('delete-whisper-model', modelName),
-
+ transcribeLocalWhisper: (audioBlob, options) =>
+ ipcRenderer.invoke("transcribe-local-whisper", audioBlob, options),
+ checkWhisperInstallation: () =>
+ ipcRenderer.invoke("check-whisper-installation"),
+ installWhisper: () => ipcRenderer.invoke("install-whisper"),
+ onWhisperInstallProgress: (callback) =>
+ ipcRenderer.on("whisper-install-progress", callback),
+ downloadWhisperModel: (modelName) =>
+ ipcRenderer.invoke("download-whisper-model", modelName),
+ onWhisperDownloadProgress: (callback) =>
+ ipcRenderer.on("whisper-download-progress", callback),
+ checkModelStatus: (modelName) =>
+ ipcRenderer.invoke("check-model-status", modelName),
+ listWhisperModels: () => ipcRenderer.invoke("list-whisper-models"),
+ deleteWhisperModel: (modelName) =>
+ ipcRenderer.invoke("delete-whisper-model", modelName),
+ cancelWhisperDownload: () => ipcRenderer.invoke("cancel-whisper-download"),
+
// Window control functions
- windowMinimize: () => ipcRenderer.invoke('window-minimize'),
- windowMaximize: () => ipcRenderer.invoke('window-maximize'),
- windowClose: () => ipcRenderer.invoke('window-close'),
- windowIsMaximized: () => ipcRenderer.invoke('window-is-maximized'),
-
+ windowMinimize: () => ipcRenderer.invoke("window-minimize"),
+ windowMaximize: () => ipcRenderer.invoke("window-maximize"),
+ windowClose: () => ipcRenderer.invoke("window-close"),
+ windowIsMaximized: () => ipcRenderer.invoke("window-is-maximized"),
+
// Cleanup function
- cleanupApp: () => ipcRenderer.invoke('cleanup-app'),
-
+ cleanupApp: () => ipcRenderer.invoke("cleanup-app"),
+
// Update functions
- checkForUpdates: () => ipcRenderer.invoke('check-for-updates'),
- downloadUpdate: () => ipcRenderer.invoke('download-update'),
- installUpdate: () => ipcRenderer.invoke('install-update'),
- getAppVersion: () => ipcRenderer.invoke('get-app-version'),
- getUpdateStatus: () => ipcRenderer.invoke('get-update-status'),
-
+ checkForUpdates: () => ipcRenderer.invoke("check-for-updates"),
+ downloadUpdate: () => ipcRenderer.invoke("download-update"),
+ installUpdate: () => ipcRenderer.invoke("install-update"),
+ getAppVersion: () => ipcRenderer.invoke("get-app-version"),
+ getUpdateStatus: () => ipcRenderer.invoke("get-update-status"),
+
// 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: (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),
});
diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsx
index a59dad1a4..1466c6840 100644
--- a/src/components/ControlPanel.tsx
+++ b/src/components/ControlPanel.tsx
@@ -5,16 +5,8 @@ import { Trash2, RefreshCw, Settings, FileText, Mic } from "lucide-react";
import SettingsPage from "./SettingsPage";
import TitleBar from "./TitleBar";
import TranscriptionItem from "./ui/TranscriptionItem";
-import type {
- TranscriptionItem as TranscriptionItemType,
- ElectronAPI,
-} from "../types/electron";
-
-declare global {
- interface Window {
- electronAPI: ElectronAPI;
- }
-}
+import { ConfirmDialog, AlertDialog } from "./ui/dialog";
+import type { TranscriptionItem as TranscriptionItemType } from "../types/electron";
export default function ControlPanel() {
const [history, setHistory] = useState<TranscriptionItemType[]>([]);
@@ -25,6 +17,25 @@ 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: "",
+ });
useEffect(() => {
// Load transcription history from database
@@ -70,50 +81,73 @@ export default function ControlPanel() {
const copyToClipboard = async (text: string) => {
try {
await navigator.clipboard.writeText(text);
- alert("Text copied to your clipboard!");
+ setAlertDialog({
+ open: true,
+ title: "Copied!",
+ description: "Text copied to your clipboard!",
+ });
} catch (err) {}
};
const clearHistory = async () => {
- if (
- confirm(
- "Are you certain you wish to clear all inscribed records? This action cannot be undone."
- )
- ) {
- try {
- const result = await window.electronAPI.clearTranscriptions();
- setHistory([]);
- alert(
- `Successfully cleared ${result.cleared} transcriptions from your chronicles.`
- );
- } catch (error) {
- alert("Failed to clear history. Please try again.");
- }
- }
+ setConfirmDialog({
+ open: true,
+ title: "Clear History",
+ description:
+ "Are you certain you wish to clear all inscribed records? This action cannot be undone.",
+ onConfirm: async () => {
+ try {
+ const result = await window.electronAPI.clearTranscriptions();
+ setHistory([]);
+ setAlertDialog({
+ open: true,
+ title: "History Cleared",
+ description: `Successfully cleared ${result.cleared} transcriptions from your chronicles.`,
+ });
+ } catch (error) {
+ setAlertDialog({
+ open: true,
+ title: "Error",
+ description: "Failed to clear history. Please try again.",
+ });
+ }
+ },
+ variant: "destructive",
+ });
};
const deleteTranscription = async (id: number) => {
- if (
- confirm(
- "Are you certain you wish to remove this inscription from your records?"
- )
- ) {
- try {
- const result = await window.electronAPI.deleteTranscription(id);
- if (result.success) {
- // Remove from local state
- setHistory((prev) => prev.filter((item) => item.id !== id));
- console.log(`πŸ—‘οΈ Deleted transcription ${id}`);
- } else {
- alert(
- "Failed to delete transcription. It may have already been removed."
- );
+ setConfirmDialog({
+ open: true,
+ title: "Delete Transcription",
+ description:
+ "Are you certain you wish to remove this inscription from your records?",
+ onConfirm: async () => {
+ try {
+ const result = await window.electronAPI.deleteTranscription(id);
+ if (result.success) {
+ // Remove from local state
+ setHistory((prev) => prev.filter((item) => item.id !== id));
+ console.log(`πŸ—‘οΈ Deleted transcription ${id}`);
+ } else {
+ setAlertDialog({
+ open: true,
+ title: "Delete Failed",
+ description:
+ "Failed to delete transcription. It may have already been removed.",
+ });
+ }
+ } catch (error) {
+ console.error("❌ Failed to delete transcription:", error);
+ setAlertDialog({
+ open: true,
+ title: "Delete Failed",
+ description: "Failed to delete transcription. Please try again.",
+ });
}
- } catch (error) {
- console.error("❌ Failed to delete transcription:", error);
- alert("Failed to delete transcription. Please try again.");
- }
- }
+ },
+ variant: "destructive",
+ });
};
const refreshHistory = async () => {
@@ -123,6 +157,23 @@ export default function ControlPanel() {
return (
<div className="min-h-screen bg-white">
+ <ConfirmDialog
+ open={confirmDialog.open}
+ onOpenChange={(open) => setConfirmDialog((prev) => ({ ...prev, open }))}
+ title={confirmDialog.title}
+ description={confirmDialog.description}
+ onConfirm={confirmDialog.onConfirm}
+ variant={confirmDialog.variant}
+ />
+
+ <AlertDialog
+ open={alertDialog.open}
+ onOpenChange={(open) => setAlertDialog((prev) => ({ ...prev, open }))}
+ title={alertDialog.title}
+ description={alertDialog.description}
+ onOk={() => {}}
+ />
+
<TitleBar
actions={
<>
diff --git a/src/components/OnboardingFlow.tsx b/src/components/OnboardingFlow.tsx
index 36ff24c3a..48d5d620f 100644
--- a/src/components/OnboardingFlow.tsx
+++ b/src/components/OnboardingFlow.tsx
@@ -23,16 +23,10 @@ import ProcessingModeSelector from "./ui/ProcessingModeSelector";
import ApiKeyInput from "./ui/ApiKeyInput";
import PermissionCard from "./ui/PermissionCard";
import StepProgress from "./ui/StepProgress";
+import { AlertDialog } from "./ui/dialog";
import { useWhisper } from "../hooks/useWhisper";
import { usePermissions } from "../hooks/usePermissions";
import { useClipboard } from "../hooks/useClipboard";
-import type { TranscriptionItem, ElectronAPI } from "../types/electron";
-
-declare global {
- interface Window {
- electronAPI: ElectronAPI;
- }
-}
interface OnboardingFlowProps {
onComplete: () => void;
@@ -60,6 +54,14 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
null
);
const [audioChunks, setAudioChunks] = useState<Blob[]>([]);
+ const [alertDialog, setAlertDialog] = useState<{
+ open: boolean;
+ title: string;
+ description?: string;
+ }>({
+ open: false,
+ title: "",
+ });
// Use our custom hooks
const whisperHook = useWhisper();
@@ -172,7 +174,11 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
await window.electronAPI.pasteText(text);
}
} catch (error) {
- alert("Transcription failed. Please try again.");
+ setAlertDialog({
+ open: true,
+ title: "Transcription Failed",
+ description: "Transcription failed. Please try again.",
+ });
} finally {
setIsProcessing(false);
stream.getTracks().forEach((track) => track.stop());
@@ -184,7 +190,12 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
recorder.start();
setIsRecording(true);
} catch (error) {
- alert("Failed to start recording. Please check microphone permissions.");
+ setAlertDialog({
+ open: true,
+ title: "Recording Failed",
+ description:
+ "Failed to start recording. Please check microphone permissions.",
+ });
}
};
@@ -790,6 +801,13 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
fontFamily: "Noto Sans, sans-serif",
}}
>
+ <AlertDialog
+ open={alertDialog.open}
+ onOpenChange={(open) => setAlertDialog((prev) => ({ ...prev, open }))}
+ title={alertDialog.title}
+ description={alertDialog.description}
+ onOk={() => {}}
+ />
{/* Left margin line for entire page */}
<div className="fixed left-6 md:left-12 top-0 bottom-0 w-px bg-red-300/40 z-0"></div>
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index a3b950f22..d82f8c7ec 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -14,16 +14,11 @@ import TitleBar from "./TitleBar";
import WhisperModelPicker from "./WhisperModelPicker";
import ProcessingModeSelector from "./ui/ProcessingModeSelector";
import ApiKeyInput from "./ui/ApiKeyInput";
+import { ConfirmDialog, AlertDialog } from "./ui/dialog";
import { useWhisper } from "../hooks/useWhisper";
import { usePermissions } from "../hooks/usePermissions";
import { useClipboard } from "../hooks/useClipboard";
-import type { TranscriptionItem, ElectronAPI } from "../types/electron";
-
-declare global {
- interface Window {
- electronAPI: ElectronAPI;
- }
-}
+import type { TranscriptionItem } from "../types/electron";
interface SettingsPageProps {
onBack: () => void;
@@ -56,6 +51,25 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {
releaseDate?: string;
releaseNotes?: string;
}>({});
+ 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: "",
+ });
useEffect(() => {
// Load saved settings
@@ -142,7 +156,11 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {
const saveKey = () => {
localStorage.setItem("dictationKey", key);
- alert(`Dictation key inscribed: ${key}`);
+ setAlertDialog({
+ open: true,
+ title: "Key Saved",
+ description: `Dictation key inscribed: ${key}`,
+ });
};
const saveApiKey = async () => {
@@ -152,19 +170,29 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {
try {
await window.electronAPI.createProductionEnvFile(apiKey);
- alert(
- "OpenAI API key inscribed successfully! Your credentials have been securely recorded for transcription services."
- );
+ setAlertDialog({
+ open: true,
+ title: "API Key Saved",
+ description:
+ "OpenAI API key inscribed successfully! Your credentials have been securely recorded for transcription services.",
+ });
} catch (envError) {
console.log("Could not create production .env file:", envError);
- alert(
- "OpenAI API key saved successfully and will be available for transcription"
- );
+ setAlertDialog({
+ open: true,
+ title: "API Key Saved",
+ description:
+ "OpenAI API key saved successfully and will be available for transcription",
+ });
}
} catch (error) {
console.error("Failed to save API key:", error);
localStorage.setItem("openaiApiKey", apiKey);
- alert("OpenAI API key saved to localStorage (fallback mode)");
+ setAlertDialog({
+ open: true,
+ title: "API Key Saved",
+ description: "OpenAI API key saved to localStorage (fallback mode)",
+ });
}
};
@@ -178,15 +206,17 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {
localStorage.setItem("openaiApiKey", apiKey);
}
- alert(
- `Whisper settings saved! ${
+ setAlertDialog({
+ open: true,
+ title: "Settings Saved",
+ description: `Whisper settings saved! ${
useLocalWhisper
? `Using local model: ${whisperModel}${
allowOpenAIFallback ? " with OpenAI fallback" : ""
}`
: "Using OpenAI API"
- }`
- );
+ }`,
+ });
};
// Permission functions now handled by hooks
@@ -194,22 +224,47 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {
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.`;
- if (confirm(message)) {
- alert(
- "Opening System Settings... Look for the Accessibility section under Privacy & Security."
- );
-
- window.open(
- "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility",
- "_blank"
- );
- }
+ setConfirmDialog({
+ open: true,
+ title: "Reset Accessibility Permissions",
+ description: message,
+ onConfirm: () => {
+ setAlertDialog({
+ open: true,
+ title: "Opening System Settings",
+ description:
+ "Opening System Settings... Look for the Accessibility section under Privacy & Security.",
+ });
+
+ window.open(
+ "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility",
+ "_blank"
+ );
+ },
+ });
};
// Clipboard handling now done by shared hooks
return (
<div className="min-h-screen bg-white">
+ <ConfirmDialog
+ open={confirmDialog.open}
+ onOpenChange={(open) => setConfirmDialog((prev) => ({ ...prev, open }))}
+ title={confirmDialog.title}
+ description={confirmDialog.description}
+ onConfirm={confirmDialog.onConfirm}
+ variant={confirmDialog.variant}
+ />
+
+ <AlertDialog
+ open={alertDialog.open}
+ onOpenChange={(open) => setAlertDialog((prev) => ({ ...prev, open }))}
+ title={alertDialog.title}
+ description={alertDialog.description}
+ onOk={() => {}}
+ />
+
<TitleBar
title="Settings"
showTitle={true}
@@ -571,12 +626,24 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {
...prev,
updateAvailable: true,
}));
- alert(`Update available: v${result.version}`);
+ setAlertDialog({
+ open: true,
+ title: "Update Available",
+ description: `Update available: v${result.version}`,
+ });
} else {
- alert(result.message || "No updates available");
+ setAlertDialog({
+ open: true,
+ title: "No Updates",
+ description: result.message || "No updates available",
+ });
}
} catch (error) {
- alert(`Error checking for updates: ${error.message}`);
+ setAlertDialog({
+ open: true,
+ title: "Update Check Failed",
+ description: `Error checking for updates: ${error.message}`,
+ });
} finally {
setCheckingForUpdates(false);
}
@@ -608,11 +675,18 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {
...prev,
updateDownloaded: true,
}));
- alert(
- "Update downloaded successfully! You can now install it."
- );
+ setAlertDialog({
+ open: true,
+ title: "Update Downloaded",
+ description:
+ "Update downloaded successfully! You can now install it.",
+ });
} catch (error) {
- alert(`Error downloading update: ${error.message}`);
+ setAlertDialog({
+ open: true,
+ title: "Download Failed",
+ description: `Error downloading update: ${error.message}`,
+ });
} finally {
setDownloadingUpdate(false);
}
@@ -640,7 +714,11 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {
try {
await window.electronAPI.installUpdate();
} catch (error) {
- alert(`Error installing update: ${error.message}`);
+ setAlertDialog({
+ open: true,
+ title: "Install Failed",
+ description: `Error installing update: ${error.message}`,
+ });
}
}}
disabled={updateStatus.isDevelopment}
@@ -726,14 +804,17 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {
<div className="border-t border-neutral-200 pt-4 space-y-3">
<Button
onClick={() => {
- if (
- confirm(
- "Are you sure you want to reset the onboarding process? This will clear your setup and show the welcome flow again."
- )
- ) {
- localStorage.removeItem("onboardingCompleted");
- window.location.reload();
- }
+ setConfirmDialog({
+ open: true,
+ 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.",
+ onConfirm: () => {
+ localStorage.removeItem("onboardingCompleted");
+ window.location.reload();
+ },
+ variant: "destructive",
+ });
}}
variant="outline"
className="w-full text-amber-600 border-amber-300 hover:bg-amber-50 hover:border-amber-400"
@@ -745,25 +826,35 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {
{/* Cleanup App Data */}
<Button
onClick={() => {
- if (
- confirm(
- "⚠️ DANGER: 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?"
- )
- ) {
- window.electronAPI
- .cleanupApp()
- .then(() => {
- alert(
- "βœ… Cleanup completed! All app data has been removed."
- );
- setTimeout(() => {
- window.location.reload();
- }, 1000);
- })
- .catch((error) => {
- alert(`❌ Cleanup failed: ${error.message}`);
- });
- }
+ setConfirmDialog({
+ open: true,
+ 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?",
+ onConfirm: () => {
+ window.electronAPI
+ .cleanupApp()
+ .then(() => {
+ setAlertDialog({
+ open: true,
+ title: "Cleanup Completed",
+ description:
+ "βœ… Cleanup completed! All app data has been removed.",
+ });
+ setTimeout(() => {
+ window.location.reload();
+ }, 1000);
+ })
+ .catch((error) => {
+ setAlertDialog({
+ open: true,
+ title: "Cleanup Failed",
+ description: `❌ Cleanup failed: ${error.message}`,
+ });
+ });
+ },
+ variant: "destructive",
+ });
}}
variant="outline"
className="w-full text-red-600 border-red-300 hover:bg-red-50 hover:border-red-400"
diff --git a/src/components/WhisperModelPicker.tsx b/src/components/WhisperModelPicker.tsx
index 0a9c54519..194516781 100644
--- a/src/components/WhisperModelPicker.tsx
+++ b/src/components/WhisperModelPicker.tsx
@@ -1,13 +1,7 @@
import React, { useState, useEffect, useCallback, useMemo } from "react";
import { Button } from "./ui/button";
-import { RefreshCw, Download, Trash2 } from "lucide-react";
-
-// Type assertion for window.electronAPI
-declare global {
- interface Window {
- electronAPI: any;
- }
-}
+import { RefreshCw, Download, Trash2, X } from "lucide-react";
+import { ConfirmDialog, AlertDialog } from "./ui/dialog";
interface WhisperModel {
model: string;
@@ -109,6 +103,25 @@ 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: "",
+ });
const styles = useMemo(() => VARIANT_STYLES[variant], [variant]);
@@ -163,11 +176,20 @@ export default function WhisperModelPicker({
if (data.error?.includes("interrupted by user")) {
console.log("Model download was cancelled by user");
} else if (data.error?.includes("timeout")) {
- alert(
- "❌ Model download timed out. Please check your internet connection and try again."
- );
+ setAlertDialog({
+ open: true,
+ title: "Download Timeout",
+ description:
+ "Model download timed out. Please check your internet connection and try again.",
+ });
} else {
- alert(`❌ Model download failed: ${data.error || "Unknown error"}`);
+ setAlertDialog({
+ open: true,
+ title: "Download Failed",
+ description: `Model download failed: ${
+ data.error || "Unknown error"
+ }`,
+ });
}
}
},
@@ -194,10 +216,24 @@ export default function WhisperModelPicker({
if (result.success) {
await loadModelList();
} else {
- alert(`❌ Failed to download model "${modelName}": ${result.error}`);
+ // Only show error if it's not a cancellation
+ if (!result.error?.includes("interrupted by user")) {
+ setAlertDialog({
+ open: true,
+ title: "Download Failed",
+ description: `Failed to download model "${modelName}": ${result.error}`,
+ });
+ }
}
} catch (error) {
- alert(`❌ Failed to download model "${modelName}": ${error}`);
+ // Only show error if it's not a cancellation
+ if (!error.toString().includes("interrupted by user")) {
+ setAlertDialog({
+ open: true,
+ title: "Download Failed",
+ description: `Failed to download model "${modelName}": ${error}`,
+ });
+ }
} finally {
setDownloadingModel(null);
setDownloadProgress({
@@ -210,28 +246,78 @@ export default function WhisperModelPicker({
[loadModelList]
);
- const deleteModel = useCallback(
- async (modelName: string) => {
- if (
- confirm(
- `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.`
- )
- ) {
+ 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.deleteWhisperModel(modelName);
+ const result = await window.electronAPI.cancelWhisperDownload();
if (result.success) {
- alert(
- `βœ… Model "${modelName}" deleted successfully! Freed ${result.freed_mb}MB of disk space.`
- );
- loadModelList();
+ setDownloadingModel(null);
+ setDownloadProgress({
+ percentage: 0,
+ downloadedBytes: 0,
+ totalBytes: 0,
+ });
+ console.log(`Download of "${modelName}" cancelled successfully`);
} else {
- alert(`❌ Failed to delete model "${modelName}": ${result.error}`);
+ setAlertDialog({
+ open: true,
+ title: "Cancel Failed",
+ description: `Failed to cancel download: ${result.error}`,
+ });
}
} catch (error) {
- alert(`❌ Failed to delete model "${modelName}": ${error}`);
+ console.error(`Failed to cancel download of "${modelName}":`, error);
+ setAlertDialog({
+ open: true,
+ title: "Cancel Failed",
+ description: `Failed to cancel download: ${error}`,
+ });
}
- }
+ },
+ });
+ }, []);
+
+ const deleteModel = useCallback(
+ async (modelName: string) => {
+ setConfirmDialog({
+ open: true,
+ 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 () => {
+ try {
+ const result = await window.electronAPI.deleteWhisperModel(
+ modelName
+ );
+
+ if (result.success) {
+ setAlertDialog({
+ open: true,
+ title: "Model Deleted",
+ description: `Model "${modelName}" deleted successfully! Freed ${result.freed_mb}MB of disk space.`,
+ });
+ loadModelList();
+ } else {
+ setAlertDialog({
+ open: true,
+ title: "Delete Failed",
+ description: `Failed to delete model "${modelName}": ${result.error}`,
+ });
+ }
+ } catch (error) {
+ setAlertDialog({
+ open: true,
+ title: "Delete Failed",
+ description: `Failed to delete model "${modelName}": ${error}`,
+ });
+ }
+ },
+ variant: "destructive",
+ });
},
[loadModelList]
);
@@ -271,6 +357,24 @@ export default function WhisperModelPicker({
{progressDisplay}
<div className="p-4">
+ <ConfirmDialog
+ open={confirmDialog.open}
+ onOpenChange={(open) =>
+ setConfirmDialog((prev) => ({ ...prev, open }))
+ }
+ title={confirmDialog.title}
+ description={confirmDialog.description}
+ onConfirm={confirmDialog.onConfirm}
+ variant={confirmDialog.variant}
+ />
+
+ <AlertDialog
+ open={alertDialog.open}
+ onOpenChange={(open) => setAlertDialog((prev) => ({ ...prev, open }))}
+ title={alertDialog.title}
+ description={alertDialog.description}
+ onOk={() => {}}
+ />
<div className="flex items-center justify-between mb-3">
<h5 className={styles.header}>Available Models</h5>
<Button
@@ -359,23 +463,36 @@ export default function WhisperModelPicker({
</Button>
</>
)}
- {!model.downloaded && (
+ {!model.downloaded && !isDownloading && (
<Button
onClick={() => downloadModel(model.model)}
- disabled={isDownloading}
size="sm"
className={styles.buttons.download}
>
- {isDownloading ? (
- `${Math.round(downloadProgress.percentage)}%`
- ) : (
- <>
- <Download size={14} />
- <span className="ml-1">Download</span>
- </>
- )}
+ <Download size={14} />
+ <span className="ml-1">Download</span>
</Button>
)}
+ {isDownloading && (
+ <div className="flex gap-2">
+ <Button
+ disabled
+ size="sm"
+ className={styles.buttons.download}
+ >
+ {`${Math.round(downloadProgress.percentage)}%`}
+ </Button>
+ <Button
+ onClick={() => cancelDownload(model.model)}
+ size="sm"
+ variant="outline"
+ className="text-red-600 hover:text-red-700 hover:bg-red-50 border-red-200"
+ >
+ <X size={14} />
+ <span className="ml-1">Cancel</span>
+ </Button>
+ </div>
+ )}
</div>
</div>
);
diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsx
new file mode 100644
index 000000000..b6b6bf5b0
--- /dev/null
+++ b/src/components/ui/dialog.tsx
@@ -0,0 +1,228 @@
+import * as React from "react";
+import * as DialogPrimitive from "@radix-ui/react-dialog";
+import { X } from "lucide-react";
+import { cn } from "../lib/utils";
+
+const Dialog = DialogPrimitive.Root;
+
+const DialogTrigger = DialogPrimitive.Trigger;
+
+const DialogPortal = DialogPrimitive.Portal;
+
+const DialogClose = DialogPrimitive.Close;
+
+const DialogOverlay = React.forwardRef<
+ React.ElementRef<typeof DialogPrimitive.Overlay>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
+>(({ className, ...props }, ref) => (
+ <DialogPrimitive.Overlay
+ ref={ref}
+ className={cn(
+ "fixed inset-0 z-50 bg-black/60 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
+ className
+ )}
+ {...props}
+ />
+));
+DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
+
+const DialogContent = React.forwardRef<
+ React.ElementRef<typeof DialogPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
+>(({ className, children, ...props }, ref) => (
+ <DialogPortal>
+ <DialogOverlay />
+ <DialogPrimitive.Content
+ ref={ref}
+ className={cn(
+ "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border border-[#DDD4C7] bg-white p-6 shadow-[0_8px_32px_rgba(43,31,20,0.12),0_2px_0_rgba(255,255,255,0.8)_inset] duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] rounded-xl",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ <DialogPrimitive.Close className="absolute right-4 top-4 rounded-lg opacity-70 ring-offset-background transition-all hover:opacity-100 hover:bg-[#F5F5F5] focus:outline-none focus:ring-2 focus:ring-[#4f46e5] focus:ring-offset-2 disabled:pointer-events-none p-1">
+ <X className="h-4 w-4 text-[#737373]" />
+ <span className="sr-only">Close</span>
+ </DialogPrimitive.Close>
+ </DialogPrimitive.Content>
+ </DialogPortal>
+));
+DialogContent.displayName = DialogPrimitive.Content.displayName;
+
+const DialogHeader = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={cn(
+ "flex flex-col space-y-1.5 text-center sm:text-left",
+ className
+ )}
+ {...props}
+ />
+);
+DialogHeader.displayName = "DialogHeader";
+
+const DialogFooter = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={cn(
+ "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
+ className
+ )}
+ {...props}
+ />
+);
+DialogFooter.displayName = "DialogFooter";
+
+const DialogTitle = React.forwardRef<
+ React.ElementRef<typeof DialogPrimitive.Title>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
+>(({ className, ...props }, ref) => (
+ <DialogPrimitive.Title
+ ref={ref}
+ className={cn(
+ "text-lg font-semibold leading-none tracking-tight text-[#2B1F14] brand-heading",
+ className
+ )}
+ {...props}
+ />
+));
+DialogTitle.displayName = DialogPrimitive.Title.displayName;
+
+const DialogDescription = React.forwardRef<
+ React.ElementRef<typeof DialogPrimitive.Description>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
+>(({ className, ...props }, ref) => (
+ <DialogPrimitive.Description
+ ref={ref}
+ className={cn("text-sm text-[#737373] brand-body", className)}
+ {...props}
+ />
+));
+DialogDescription.displayName = DialogPrimitive.Description.displayName;
+
+// Custom confirmation dialog component
+interface ConfirmDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ title: string;
+ description?: string;
+ confirmText?: string;
+ cancelText?: string;
+ onConfirm: () => void;
+ onCancel?: () => void;
+ variant?: "default" | "destructive";
+}
+
+const ConfirmDialog: React.FC<ConfirmDialogProps> = ({
+ open,
+ onOpenChange,
+ title,
+ description,
+ confirmText = "Confirm",
+ cancelText = "Cancel",
+ onConfirm,
+ onCancel,
+ variant = "default",
+}) => {
+ const handleConfirm = () => {
+ onConfirm();
+ onOpenChange(false);
+ };
+
+ const handleCancel = () => {
+ onCancel?.();
+ onOpenChange(false);
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle>{title}</DialogTitle>
+ {description && <DialogDescription>{description}</DialogDescription>}
+ </DialogHeader>
+ <DialogFooter>
+ <button
+ onClick={handleCancel}
+ className="inline-flex items-center justify-center rounded-lg text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#4f46e5] focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-[#DDD4C7] bg-white text-[#2B1F14] hover:bg-[#F5F5F5] hover:text-[#4B2E2B] h-10 px-4 py-2 brand-body"
+ >
+ {cancelText}
+ </button>
+ <button
+ onClick={handleConfirm}
+ className={`inline-flex items-center justify-center rounded-lg text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#4f46e5] focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 h-10 px-4 py-2 brand-body ${
+ variant === "destructive"
+ ? "bg-[#dc2626] text-white hover:bg-[#b91c1c] shadow-[0_2px_8px_rgba(220,38,38,0.3)]"
+ : "bg-[#4f46e5] text-white hover:bg-[#4338ca] shadow-[0_2px_8px_rgba(79,70,229,0.3)]"
+ }`}
+ >
+ {confirmText}
+ </button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+// Custom alert dialog component
+interface AlertDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ title: string;
+ description?: string;
+ okText?: string;
+ onOk: () => void;
+}
+
+const AlertDialog: React.FC<AlertDialogProps> = ({
+ open,
+ onOpenChange,
+ title,
+ description,
+ okText = "OK",
+ onOk,
+}) => {
+ const handleOk = () => {
+ onOk();
+ onOpenChange(false);
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle>{title}</DialogTitle>
+ {description && <DialogDescription>{description}</DialogDescription>}
+ </DialogHeader>
+ <DialogFooter>
+ <button
+ onClick={handleOk}
+ className="inline-flex items-center justify-center rounded-lg text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#4f46e5] focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 bg-[#4f46e5] text-white hover:bg-[#4338ca] shadow-[0_2px_8px_rgba(79,70,229,0.3)] h-10 px-4 py-2 brand-body"
+ >
+ {okText}
+ </button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+export {
+ Dialog,
+ DialogPortal,
+ DialogOverlay,
+ DialogClose,
+ DialogTrigger,
+ DialogContent,
+ DialogHeader,
+ DialogFooter,
+ DialogTitle,
+ DialogDescription,
+ ConfirmDialog,
+ AlertDialog,
+};
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 3b5dd7c03..eda5f3de2 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -192,6 +192,10 @@ class IPCHandlers {
return this.whisperManager.deleteWhisperModel(modelName);
});
+ ipcMain.handle("cancel-whisper-download", async (event) => {
+ return this.whisperManager.cancelDownload();
+ });
+
// Utility handlers
ipcMain.handle("cleanup-app", async (event) => {
try {
diff --git a/src/helpers/whisper.js b/src/helpers/whisper.js
index 45c54bbb6..c3db8a9aa 100644
--- a/src/helpers/whisper.js
+++ b/src/helpers/whisper.js
@@ -9,6 +9,7 @@ class WhisperManager {
this.pythonCmd = null; // Cache Python executable path
this.whisperInstalled = null; // Cache installation status
this.isInitialized = false; // Track if startup init completed
+ this.currentDownloadProcess = null; // Track current download process for cancellation
}
async initializeAtStartup() {
@@ -352,6 +353,7 @@ class WhisperManager {
return new Promise((resolve, reject) => {
const downloadProcess = spawn(pythonCmd, args);
+ this.currentDownloadProcess = downloadProcess; // Store for potential cancellation
let stdout = "";
let stderr = "";
@@ -386,6 +388,8 @@ class WhisperManager {
});
downloadProcess.on("close", (code) => {
+ this.currentDownloadProcess = null; // Clear process reference
+
if (code === 0) {
try {
const result = JSON.parse(stdout);
@@ -400,14 +404,21 @@ class WhisperManager {
);
}
} else {
- console.error("❌ Model download failed with code:", code);
- reject(
- new Error(`Model download failed (code ${code}): ${stderr}`)
- );
+ // Check if this was a cancellation (SIGTERM = 143, SIGKILL = 137)
+ if (code === 143 || code === 137) {
+ console.log(`πŸ›‘ Model ${modelName} download cancelled`);
+ reject(new Error("Download interrupted by user"));
+ } else {
+ console.error("❌ Model download failed with code:", code);
+ reject(
+ new Error(`Model download failed (code ${code}): ${stderr}`)
+ );
+ }
}
});
downloadProcess.on("error", (error) => {
+ this.currentDownloadProcess = null; // Clear process reference
console.error("❌ Model download process error:", error);
reject(new Error(`Model download process error: ${error.message}`));
});
@@ -438,6 +449,33 @@ class WhisperManager {
}
}
+ async cancelDownload() {
+ if (this.currentDownloadProcess) {
+ try {
+ console.log("πŸ›‘ Cancelling current download...");
+ this.currentDownloadProcess.kill("SIGTERM");
+
+ // Force kill after 3 seconds if still running
+ setTimeout(() => {
+ if (
+ this.currentDownloadProcess &&
+ !this.currentDownloadProcess.killed
+ ) {
+ console.log("πŸ›‘ Force killing download process...");
+ this.currentDownloadProcess.kill("SIGKILL");
+ }
+ }, 3000);
+
+ return { success: true, message: "Download cancelled" };
+ } catch (error) {
+ console.error("❌ Error cancelling download:", error);
+ return { success: false, error: error.message };
+ }
+ } else {
+ return { success: false, error: "No active download to cancel" };
+ }
+ }
+
async checkModelStatus(modelName) {
try {
console.log(`πŸ” Checking status of Whisper model: ${modelName}`);
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 84427e419..a71c351c4 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -131,6 +131,11 @@ declare global {
deleteWhisperModel: (
modelName: string
) => Promise<WhisperModelDeleteResult>;
+ cancelWhisperDownload: () => Promise<{
+ success: boolean;
+ message?: string;
+ error?: string;
+ }>;
// Window control operations
windowMinimize: () => Promise<void>;