Skip to content

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

feat: added reasoming model selection to online processing

Gabriel Stein597dddb6dcd6
diff --git a/src/App.jsx b/src/App.jsx
index 1cbb19df4..e5fea7b41 100644
--- a/src/App.jsx
+++ b/src/App.jsx
@@ -144,235 +144,56 @@ export default function App() {
const processAudio = async (audioBlob) => {
try {
- // Cache preferences to avoid repeated localStorage calls
- const useLocalWhisper =
- localStorage.getItem("useLocalWhisper") === "true";
- const whisperModel = localStorage.getItem("whisperModel") || "base";
-
- if (useLocalWhisper) {
- await processWithLocalWhisper(audioBlob, whisperModel);
- } else {
- await processWithOpenAIAPI(audioBlob);
- }
- } catch (err) {
- console.error("Transcription error:", err);
- toast({
- title: "Transcription Error",
- description: "Transcription failed: " + err.message,
- variant: "destructive",
- });
- } finally {
- setIsProcessing(false);
- }
- };
-
- const processWithLocalWhisper = async (audioBlob, model = "base") => {
- try {
- // Convert Blob to ArrayBuffer for IPC transfer - do this early
- const arrayBuffer = await audioBlob.arrayBuffer();
- const options = { model };
- const result = await window.electronAPI.transcribeLocalWhisper(
- arrayBuffer,
- options
- );
-
- if (result.success && result.text) {
- const text = AudioManager.cleanTranscription(result.text);
-
- if (text) {
- setTranscript(text);
-
- // Paste immediately - don't wait for database save
- const pastePromise = safePaste(text);
-
- // Save to database in parallel
- const savePromise = window.electronAPI
- .saveTranscription(text)
- .catch((err) => {
- console.error("Failed to save transcription:", err);
- });
-
- // Wait for paste to complete, but don't block on database save
- await pastePromise;
- } else {
+ console.log(`🎧 [App] 🎬 Starting audio processing...`);
+
+ // Use our enhanced AudioManager with reasoning support
+ const audioManager = new AudioManager();
+ audioManager.setCallbacks({
+ onStateChange: ({ isRecording, isProcessing }) => {
+ setIsRecording(isRecording);
+ setIsProcessing(isProcessing);
+ },
+ onError: (error) => {
toast({
- title: "No Audio",
- description: "No text transcribed. Try again.",
+ title: error.title,
+ description: error.description,
variant: "destructive",
});
- }
- } else if (
- result.success === false &&
- result.message === "No audio detected"
- ) {
- toast({
- title: "No Audio",
- description: "No audio detected",
- variant: "destructive",
- });
- return;
- } else {
- throw new Error(result.error || "Local Whisper transcription failed");
- }
- } catch (err) {
- console.error("Local Whisper error:", err);
-
- // Check if it's a "No audio detected" error and don't retry
- if (err.message === "No audio detected") {
- throw err;
- }
-
- // Try fallback to OpenAI API ONLY if enabled AND we're in local mode
- const allowOpenAIFallback =
- localStorage.getItem("allowOpenAIFallback") === "true";
- const isLocalMode = localStorage.getItem("useLocalWhisper") === "true";
-
- if (allowOpenAIFallback && isLocalMode) {
- toast({
- title: "Fallback Mode",
- description: "Local Whisper failed. Retrying with OpenAI API...",
- variant: "default",
- });
- await processWithOpenAIAPI(audioBlob);
- } else {
- // No fallback allowed - strict local mode
- throw new Error(`Local Whisper failed: ${err.message}`);
- }
- }
- };
-
- const processWithOpenAIAPI = async (audioBlob) => {
- try {
- // Get API key early and cache it
- let apiKey = await window.electronAPI.getOpenAIKey();
- if (
- !apiKey ||
- apiKey.trim() === "" ||
- apiKey === "your_openai_api_key_here"
- ) {
- apiKey = localStorage.getItem("openaiApiKey");
- }
-
- if (
- !apiKey ||
- apiKey.trim() === "" ||
- apiKey === "your_openai_api_key_here"
- ) {
- toast({
- title: "API Key Missing",
- description:
- "OpenAI API key not found. Please set your API key in the .env file or Control Panel.",
- variant: "destructive",
- });
- return;
- }
-
- const formData = new FormData();
- formData.append("file", audioBlob, "audio.wav");
- formData.append("model", "whisper-1");
-
- const response = await fetch(
- "https://api.openai.com/v1/audio/transcriptions",
- {
- method: "POST",
- headers: {
- Authorization: `Bearer ${apiKey}`,
- },
- body: formData,
- }
- );
-
- if (!response.ok) {
- const errorText = await response.text();
- console.error("API Error:", errorText);
- toast({
- title: "API Error",
- description: `Transcription failed: ${response.status} ${errorText}`,
- variant: "destructive",
- });
- throw new Error(
- `Failed to transcribe audio: ${response.status} ${errorText}`
- );
- }
-
- const result = await response.json();
- const text = AudioManager.cleanTranscription(result.text);
-
- if (text) {
- setTranscript(text);
-
- // Paste immediately - don't wait for database save
- const pastePromise = safePaste(text);
-
- // Save to database in parallel
- const savePromise = window.electronAPI
- .saveTranscription(text)
- .catch((err) => {
- console.error("Failed to save transcription:", err);
- });
-
- // Wait for paste to complete, but don't block on database save
- await pastePromise;
- } else {
- toast({
- title: "No Audio",
- description: "No text transcribed. Try again.",
- variant: "destructive",
- });
- }
- } catch (err) {
- console.error("OpenAI API error:", err);
-
- // Try fallback to Local Whisper ONLY if enabled AND we're in OpenAI mode
- const allowLocalFallback =
- localStorage.getItem("allowLocalFallback") === "true";
- const isOpenAIMode = localStorage.getItem("useLocalWhisper") !== "true";
-
- if (allowLocalFallback && isOpenAIMode) {
- toast({
- title: "Fallback Mode",
- description: "OpenAI API failed. Retrying with Local Whisper...",
- variant: "default",
- });
- const fallbackModel =
- localStorage.getItem("fallbackWhisperModel") || "base";
- try {
- const arrayBuffer = await audioBlob.arrayBuffer();
- const options = { model: fallbackModel };
- const result = await window.electronAPI.transcribeLocalWhisper(
- arrayBuffer,
- options
+ },
+ onTranscriptionComplete: async (result) => {
+ console.log(
+ `🎧 [App] βœ… Transcription completed with source: ${result.source}`
);
-
if (result.success && result.text) {
- let text = AudioManager.cleanTranscription(result.text);
- if (text) {
- setTranscript(text);
- // Paste immediately - don't wait for database save
- const pastePromise = safePaste(text);
- // Save to database in parallel
- window.electronAPI.saveTranscription(text).catch((saveErr) => {
- console.error("Failed to save transcription:", saveErr);
+ setTranscript(result.text);
+
+ // Paste immediately - don't wait for database save
+ const pastePromise = safePaste(result.text);
+
+ // Save to database in parallel
+ const savePromise = window.electronAPI
+ .saveTranscription(result.text)
+ .catch((err) => {
+ console.error("Failed to save transcription:", err);
});
- await pastePromise;
- return; // Success with fallback
- }
+
+ // Wait for paste to complete, but don't block on database save
+ await pastePromise;
}
- // If local fallback fails, throw the original OpenAI error
- throw err;
- } catch (fallbackError) {
- console.error("Local fallback also failed:", fallbackError);
- toast({
- title: "Both Methods Failed",
- description:
- "Both OpenAI API and Local Whisper failed. Please try again.",
- variant: "destructive",
- });
- throw err; // Throw original OpenAI error
- }
- }
+ },
+ });
- throw err;
+ // Process the audio using our enhanced AudioManager
+ await audioManager.processAudio(audioBlob);
+ } catch (err) {
+ console.error(`🎧 [App] ❌ Transcription error:`, err);
+ toast({
+ title: "Transcription Error",
+ description: "Transcription failed: " + err.message,
+ variant: "destructive",
+ });
+ } finally {
+ setIsProcessing(false);
}
};
diff --git a/src/components/OnboardingFlow.tsx b/src/components/OnboardingFlow.tsx
index 10f3420f9..b474407a6 100644
--- a/src/components/OnboardingFlow.tsx
+++ b/src/components/OnboardingFlow.tsx
@@ -28,7 +28,7 @@ import { AlertDialog } from "./ui/dialog";
import { useWhisper } from "../hooks/useWhisper";
import { usePermissions } from "../hooks/usePermissions";
import { useClipboard } from "../hooks/useClipboard";
-import { getLanguageLabel } from "../utils/languages";
+import { getLanguageLabel, REASONING_MODEL_OPTIONS, getReasoningModelLabel } from "../utils/languages";
import LanguageSelector from "./ui/LanguageSelector";
interface OnboardingFlowProps {
@@ -54,6 +54,9 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
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;
@@ -100,11 +103,12 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
}, [currentStep]);
const saveSettings = async () => {
- // Save all settings
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);
localStorage.setItem(
"micPermissionGranted",
permissionsHook.micPermissionGranted.toString()
@@ -347,6 +351,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
<li>5. Copy and paste it here</li>
</ol>
</div>
+
</div>
)}
@@ -369,7 +374,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
<p className="text-xs text-gray-600 mt-1">
{useLocalWhisper
? "Helps Whisper better understand your speech"
- : "Improves OpenAI transcription speed and accuracy"}
+ : "Improves OpenAI transcription speed and accuracy. AI text enhancement is enabled by default."}
</p>
</div>
</div>
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index 9d33d5027..b4b5d25bf 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -9,6 +9,10 @@ import {
Keyboard,
Info,
ArrowLeft,
+ Mic,
+ Brain,
+ Shield,
+ ChevronRight,
} from "lucide-react";
import TitleBar from "./TitleBar";
import WhisperModelPicker from "./WhisperModelPicker";
@@ -18,7 +22,12 @@ import { ConfirmDialog, AlertDialog } from "./ui/dialog";
import { useWhisper } from "../hooks/useWhisper";
import { usePermissions } from "../hooks/usePermissions";
import { useClipboard } from "../hooks/useClipboard";
-import { getLanguageLabel } from "../utils/languages";
+import {
+ getLanguageLabel,
+ getAllReasoningModels,
+ getModelProvider,
+ REASONING_PROVIDERS,
+} from "../utils/languages";
import LanguageSelector from "./ui/LanguageSelector";
import type { TranscriptionItem } from "../types/electron";
@@ -26,7 +35,18 @@ interface SettingsPageProps {
onBack: () => void;
}
+type SettingsSection =
+ | "transcription"
+ | "reasoning"
+ | "hotkey"
+ | "updates"
+ | "about";
+
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);
@@ -36,6 +56,12 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {
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("");
+
// Update state
const [currentVersion, setCurrentVersion] = useState<string>("");
const [updateStatus, setUpdateStatus] = useState<{
@@ -51,6 +77,8 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {
releaseDate?: string;
releaseNotes?: string;
}>({});
+
+ // Dialog states
const [confirmDialog, setConfirmDialog] = useState<{
open: boolean;
title: string;
@@ -71,7 +99,7 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {
title: "",
});
- // Use custom hooks
+ // Custom hooks
const whisperHook = useWhisper(setAlertDialog);
const permissionsHook = usePermissions(setAlertDialog);
const { pasteFromClipboardWithFallback } = useClipboard(setAlertDialog);
@@ -81,7 +109,6 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {
const savedKey = localStorage.getItem("dictationKey");
if (savedKey) setKey(savedKey);
- // Load Whisper settings
const savedUseLocal = localStorage.getItem("useLocalWhisper") === "true";
const savedModel = localStorage.getItem("whisperModel") || "base";
const savedAllowOpenAIFallback =
@@ -90,50 +117,53 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {
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);
-
- // Load language preference
- const savedLanguage = localStorage.getItem("preferredLanguage") || "en";
setPreferredLanguage(savedLanguage);
+ setUseReasoningModel(savedUseReasoning);
+ setReasoningModel(savedReasoningModel);
+ setReasoningProvider(getModelProvider(savedReasoningModel));
- // Load API key from main process first, then fallback to localStorage
- const loadApiKey = async () => {
+ // Load API keys
+ const loadApiKeys = async () => {
try {
- const envApiKey = await window.electronAPI.getOpenAIKey();
+ 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);
}
};
- loadApiKey();
-
- // Check Whisper installation
+ loadApiKeys();
whisperHook.checkWhisperInstallation();
-
- // Set up progress listener for Whisper installation
whisperHook.setupProgressListener();
// Initialize update functionality
const initializeUpdateData = async () => {
try {
- // Get current app version
- const versionResult = await window.electronAPI.getAppVersion();
- setCurrentVersion(versionResult.version);
+ const versionResult = await window.electronAPI?.getAppVersion();
+ if (versionResult) setCurrentVersion(versionResult.version);
- // Get update status
- const statusResult = await window.electronAPI.getUpdateStatus();
- setUpdateStatus(statusResult);
+ const statusResult = await window.electronAPI?.getUpdateStatus();
+ if (statusResult) setUpdateStatus(statusResult);
} catch (error) {
console.error("Error initializing update data:", error);
}
@@ -142,61 +172,91 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {
initializeUpdateData();
// Set up update event listeners
- window.electronAPI.onUpdateAvailable((event, info) => {
- setUpdateStatus((prev) => ({ ...prev, updateAvailable: true }));
- setUpdateInfo({
- version: info.version,
- releaseDate: info.releaseDate,
- releaseNotes: info.releaseNotes,
+ if (window.electronAPI) {
+ window.electronAPI.onUpdateAvailable?.((event, info) => {
+ setUpdateStatus((prev) => ({ ...prev, updateAvailable: true }));
+ setUpdateInfo({
+ version: info.version,
+ releaseDate: info.releaseDate,
+ releaseNotes: info.releaseNotes,
+ });
});
- });
- window.electronAPI.onUpdateDownloaded((event, info) => {
- setUpdateStatus((prev) => ({ ...prev, updateDownloaded: true }));
- setDownloadingUpdate(false);
- });
+ window.electronAPI.onUpdateDownloaded?.((event, info) => {
+ setUpdateStatus((prev) => ({ ...prev, updateDownloaded: true }));
+ setDownloadingUpdate(false);
+ });
- window.electronAPI.onUpdateDownloadProgress((event, progressObj) => {
- setUpdateDownloadProgress(progressObj.percent || 0);
- });
+ window.electronAPI.onUpdateDownloadProgress?.((event, progressObj) => {
+ setUpdateDownloadProgress(progressObj.percent || 0);
+ });
- window.electronAPI.onUpdateError((event, error) => {
- setCheckingForUpdates(false);
- setDownloadingUpdate(false);
- console.error("Update error:", error);
- });
+ window.electronAPI.onUpdateError?.((event, error) => {
+ setCheckingForUpdates(false);
+ setDownloadingUpdate(false);
+ console.error("Update error:", error);
+ });
+ }
}, []);
- // Whisper functions now handled by hooks
+ 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"}`
+ );
- const saveKey = async () => {
- try {
- localStorage.setItem("dictationKey", key);
- await window.electronAPI.updateHotkey(key);
- setAlertDialog({
- open: true,
- title: "Key Saved",
- description: `Dictation key inscribed: ${key}`,
- });
- } catch (error) {
- console.error("Failed to update hotkey:", error);
- setAlertDialog({
- open: true,
- title: "Error",
- description: `Failed to update hotkey: ${error.message}`,
- });
+ 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}`
+ );
+
+ setAlertDialog({
+ open: true,
+ title: "Reasoning Settings Saved",
+ description: `AI text enhancement ${
+ useReasoningModel ? "enabled" : "disabled"
+ } with ${
+ REASONING_PROVIDERS[
+ reasoningProvider as keyof typeof REASONING_PROVIDERS
+ ]?.name || reasoningProvider
+ } ${reasoningModel}`,
+ });
};
const saveApiKey = async () => {
try {
- await window.electronAPI.saveOpenAIKey(apiKey);
+ await window.electronAPI?.saveOpenAIKey(apiKey);
localStorage.setItem("openaiApiKey", apiKey);
localStorage.setItem("allowLocalFallback", allowLocalFallback.toString());
localStorage.setItem("fallbackWhisperModel", fallbackWhisperModel);
try {
- await window.electronAPI.createProductionEnvFile(apiKey);
+ await window.electronAPI?.createProductionEnvFile(apiKey);
setAlertDialog({
open: true,
title: "API Key Saved",
@@ -233,11 +293,9 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {
localStorage.setItem("allowOpenAIFallback", allowOpenAIFallback.toString());
// SECURITY: Only save API key if fallback is enabled and key is provided
- // This ensures we never store unused keys
if (allowOpenAIFallback && apiKey.trim()) {
localStorage.setItem("openaiApiKey", apiKey);
} else if (!allowOpenAIFallback) {
- // Clear the key if fallback is disabled for security
localStorage.removeItem("openaiApiKey");
}
@@ -254,8 +312,6 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {
});
};
- // Permission functions now handled by hooks
-
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.`;
@@ -279,740 +335,732 @@ export default function SettingsPage({ onBack }: SettingsPageProps) {
});
};
- // Clipboard handling now done by shared hooks
+ const saveKey = async () => {
+ try {
+ localStorage.setItem("dictationKey", key);
+ await window.electronAPI?.updateHotkey(key);
+ setAlertDialog({
+ open: true,
+ title: "Key Saved",
+ description: `Dictation key inscribed: ${key}`,
+ });
+ } catch (error) {
+ console.error("Failed to update hotkey:", error);
+ setAlertDialog({
+ open: true,
+ title: "Error",
+ description: `Failed to update hotkey: ${error.message}`,
+ });
+ }
+ };
- 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}
- />
+ const sidebarItems = [
+ {
+ id: "transcription" as SettingsSection,
+ label: "Transcription Setup",
+ icon: Settings,
+ },
+ {
+ id: "reasoning" as SettingsSection,
+ 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 },
+ ];
- <AlertDialog
- open={alertDialog.open}
- onOpenChange={(open) => setAlertDialog((prev) => ({ ...prev, open }))}
- title={alertDialog.title}
- description={alertDialog.description}
- onOk={() => {}}
- />
+ const renderSectionContent = () => {
+ switch (activeSection) {
+ case "transcription":
+ return (
+ <div className="space-y-6">
+ <div>
+ <h3 className="text-lg font-semibold text-gray-900 mb-4">
+ Speech to Text Processing
+ </h3>
+ <ProcessingModeSelector
+ useLocalWhisper={useLocalWhisper}
+ setUseLocalWhisper={(value) => {
+ setUseLocalWhisper(value);
+ localStorage.setItem("useLocalWhisper", value.toString());
+ console.log(
+ `πŸ”§ [Settings] Transcription mode switched to: ${
+ value ? "LOCAL" : "OPENAI API"
+ }`
+ );
+ }}
+ />
+ </div>
- <TitleBar
- title="Settings"
- showTitle={true}
- actions={
- <Button variant="ghost" size="icon" onClick={onBack}>
- <ArrowLeft size={16} />
- </Button>
- }
- />
+ {!useLocalWhisper && (
+ <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}
+ helpText="Get your API key from platform.openai.com"
+ />
+ </div>
+ )}
+
+ {useLocalWhisper && whisperHook.whisperInstalled && (
+ <div className="space-y-4 p-4 bg-purple-50 border border-purple-200 rounded-xl">
+ <h4 className="font-medium text-purple-900">
+ Local Whisper Model
+ </h4>
+ <WhisperModelPicker
+ selectedModel={whisperModel}
+ onModelSelect={setWhisperModel}
+ variant="settings"
+ />
+ </div>
+ )}
+
+ <div className="space-y-4 p-4 bg-gray-50 border border-gray-200 rounded-xl">
+ <h4 className="font-medium text-gray-900">Preferred Language</h4>
+ <LanguageSelector
+ value={preferredLanguage}
+ onChange={(value) => {
+ setPreferredLanguage(value);
+ localStorage.setItem("preferredLanguage", value);
+ }}
+ className="w-full"
+ />
+ </div>
+
+ <Button
+ onClick={() => {
+ 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"}`
+ );
+
+ 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`
+ );
+ }
+
+ console.log(
+ `πŸ’Ύ [Settings] βœ… Transcription settings saved successfully`
+ );
+ console.log(
+ `πŸ’Ύ [Settings] βœ… Mode set to: ${
+ useLocalWhisper ? "LOCAL WHISPER" : "OPENAI API"
+ }`
+ );
+
+ setAlertDialog({
+ open: true,
+ title: "Settings Saved",
+ description: `Transcription mode: ${
+ useLocalWhisper ? "Local Whisper" : "OpenAI API"
+ }. Language: ${preferredLanguage}.`,
+ });
+ }}
+ className="w-full"
+ >
+ Save Transcription Settings
+ </Button>
+ </div>
+ );
- {/* Main content */}
- <div
- className="bg-gradient-to-br from-neutral-50 via-white to-indigo-50/30 p-6 relative"
- style={{
- backgroundImage: `repeating-linear-gradient(
- transparent,
- transparent 24px,
- #d1d5db 24px,
- #d1d5db 25px
- )`,
- }}
- >
- {/* Red margin line */}
- <div className="absolute left-12 top-0 bottom-0 w-px bg-red-300 z-0"></div>
-
- <div className="max-w-4xl mx-auto space-y-6">
- {/* Transcription Setup Card */}
- <Card className="bg-white relative z-10">
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <Settings size={18} className="text-indigo-600" />
- Transcription Setup
- </CardTitle>
- <p className="text-sm text-neutral-600 mt-2 leading-relaxed">
- Choose how you want to convert speech to text. You can always
- change this later.
+ case "reasoning":
+ return (
+ <div className="space-y-6">
+ <div>
+ <h3 className="text-lg font-semibold text-gray-900 mb-2">
+ AI Text Enhancement
+ </h3>
+ <p className="text-sm text-gray-600 mb-6">
+ Configure how AI models clean up and format your transcriptions.
+ This handles commands like "scratch that", creates proper lists,
+ and fixes obvious errors while preserving your natural tone.
</p>
- </CardHeader>
- <CardContent className="space-y-6">
- <div className="space-y-4">
- {/* Processing Choice */}
+
+ <div className="flex items-center justify-between p-4 bg-green-50 border border-green-200 rounded-xl">
<div>
- <label className="block text-sm font-medium text-neutral-700 mb-4">
- Processing Method
+ <label className="text-sm font-medium text-green-800">
+ Enable AI Text Enhancement
</label>
- <ProcessingModeSelector
- useLocalWhisper={useLocalWhisper}
- setUseLocalWhisper={setUseLocalWhisper}
+ <p className="text-xs text-green-700">
+ Use AI to automatically improve transcription quality
+ </p>
+ </div>
+ <label className="relative inline-flex items-center cursor-pointer">
+ <input
+ type="checkbox"
+ className="sr-only"
+ checked={useReasoningModel}
+ onChange={(e) => {
+ const enabled = e.target.checked;
+ setUseReasoningModel(enabled);
+ localStorage.setItem(
+ "useReasoningModel",
+ enabled.toString()
+ );
+ console.log(
+ `πŸ”§ [Settings] AI text enhancement ${
+ enabled ? "ENABLED" : "DISABLED"
+ }`
+ );
+ }}
/>
+ <div
+ className={`w-11 h-6 bg-gray-200 rounded-full transition-colors duration-200 ${
+ useReasoningModel ? "bg-green-600" : "bg-gray-300"
+ }`}
+ >
+ <div
+ className={`absolute top-0.5 left-0.5 bg-white border border-gray-300 rounded-full h-5 w-5 transition-transform duration-200 ${
+ useReasoningModel ? "translate-x-5" : "translate-x-0"
+ }`}
+ ></div>
+ </div>
+ </label>
+ </div>
+ </div>
+
+ {useReasoningModel && (
+ <>
+ <div className="space-y-4 p-4 bg-blue-50 border border-blue-200 rounded-xl">
+ <h4 className="font-medium text-blue-900">AI Provider</h4>
+ <select
+ value={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);
+ }
+ }}
+ 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"
+ >
+ {Object.entries(REASONING_PROVIDERS).map(
+ ([id, provider]) => (
+ <option key={id} value={id}>
+ {provider.name}
+ </option>
+ )
+ )}
+ </select>
</div>
- {/* Cloud Configuration */}
- {!useLocalWhisper && (
+ <div className="space-y-4 p-4 bg-indigo-50 border border-indigo-200 rounded-xl">
+ <h4 className="font-medium text-indigo-900">AI Model</h4>
+ <select
+ value={reasoningModel}
+ onChange={(e) => setReasoningModel(e.target.value)}
+ className="w-full text-sm border border-indigo-300 rounded-md p-2 bg-white focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
+ >
+ {REASONING_PROVIDERS[
+ reasoningProvider as keyof typeof REASONING_PROVIDERS
+ ]?.models.map((model) => (
+ <option key={model.value} value={model.value}>
+ {model.label} - {model.description}
+ </option>
+ ))}
+ </select>
+ <p className="text-xs text-indigo-600">
+ Different models offer varying levels of quality and speed
+ </p>
+ </div>
+
+ {reasoningProvider === "openai" && (
<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
+ OpenAI API Key
</h4>
<ApiKeyInput
apiKey={apiKey}
setApiKey={setApiKey}
- className="text-blue-800"
- helpText="Get your API key from platform.openai.com"
+ helpText="Same as your transcription API key"
/>
-
- {/* Local Whisper Fallback Toggle */}
- {whisperHook.whisperInstalled && (
- <div className="space-y-3 mt-4">
- <div className="flex items-center justify-between">
- <label className="text-sm font-medium text-blue-800">
- Fall back to Local Whisper
- </label>
- <label className="relative inline-flex items-center cursor-pointer">
- <input
- type="checkbox"
- className="sr-only"
- checked={allowLocalFallback}
- onChange={(e) =>
- setAllowLocalFallback(e.target.checked)
- }
- />
- <div
- className={`w-11 h-6 bg-gray-200 rounded-full peer peer-focus:ring-2 peer-focus:ring-blue-300 ${
- allowLocalFallback
- ? "bg-blue-600"
- : "bg-gray-300"
- } transition-colors duration-200`}
- >
- <div
- className={`absolute top-0.5 left-0.5 bg-white border border-gray-300 rounded-full h-5 w-5 transition-transform duration-200 ${
- allowLocalFallback
- ? "translate-x-5"
- : "translate-x-0"
- }`}
- ></div>
- </div>
- </label>
- </div>
- <p className="text-xs text-blue-700">
- If OpenAI API fails, try Local Whisper as backup
- </p>
-
- {/* Fallback Model Selection - only show if fallback is enabled */}
- {allowLocalFallback && (
- <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
- <label className="block text-sm font-medium text-blue-800 mb-2">
- Fallback Whisper Model
- </label>
- <select
- value={fallbackWhisperModel}
- onChange={(e) =>
- setFallbackWhisperModel(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"
- >
- <option value="tiny">
- Tiny - Fast, basic quality
- </option>
- <option value="base">
- Base - Balanced (Recommended)
- </option>
- <option value="small">
- Small - Better quality
- </option>
- <option value="medium">
- Medium - High quality
- </option>
- <option value="large">
- Large - Best quality
- </option>
- <option value="turbo">
- Turbo - Fast & high quality
- </option>
- </select>
- <p className="text-xs text-blue-600 mt-1">
- Only used if OpenAI API fails
- </p>
- </div>
- )}
- </div>
- )}
</div>
)}
- {/* Local Configuration */}
- {useLocalWhisper && (
+ {reasoningProvider === "anthropic" && (
<div className="space-y-4 p-4 bg-purple-50 border border-purple-200 rounded-xl">
- <div className="flex items-center justify-between">
- <h4 className="font-medium text-purple-900">
- Local Whisper Setup
- </h4>
- <div className="flex items-center space-x-2">
- {whisperHook.checkingWhisper ? (
- <span className="text-purple-600 text-sm">
- Checking...
- </span>
- ) : whisperHook.whisperInstalled ? (
- <span className="text-emerald-600 text-sm font-medium">
- βœ“ Ready
- </span>
- ) : (
- <span className="text-amber-600 text-sm font-medium">
- ⚠ Not installed
- </span>
- )}
- </div>
+ <h4 className="font-medium text-purple-900">
+ Anthropic API Key
+ </h4>
+ <div className="flex gap-2">
+ <Input
+ type="password"
+ placeholder="sk-ant-..."
+ value={anthropicApiKey}
+ onChange={(e) => setAnthropicApiKey(e.target.value)}
+ className="flex-1 text-sm border-purple-300 focus:border-purple-500"
+ />
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() =>
+ pasteFromClipboardWithFallback(setAnthropicApiKey)
+ }
+ className="border-purple-300 text-purple-700 hover:bg-purple-50"
+ >
+ Paste
+ </Button>
</div>
-
- {whisperHook.whisperInstalled ? (
- <div className="space-y-4">
- <div>
- <label className="block text-sm font-medium text-purple-800 mb-3">
- Choose your model quality from the list below
- </label>
- <p className="text-xs text-purple-700">
- Select the model that best fits your needs.
- </p>
- </div>
-
- {/* OpenAI Fallback Toggle */}
- <div className="space-y-3">
- <div className="flex items-center justify-between">
- <label className="text-sm font-medium text-purple-800">
- Fall back to OpenAI API
- </label>
- <label className="relative inline-flex items-center cursor-pointer">
- <input
- type="checkbox"
- className="sr-only"
- checked={allowOpenAIFallback}
- onChange={(e) =>
- setAllowOpenAIFallback(e.target.checked)
- }
- />
- <div
- className={`w-11 h-6 bg-gray-200 rounded-full peer peer-focus:ring-2 peer-focus:ring-purple-300 ${
- allowOpenAIFallback
- ? "bg-purple-600"
- : "bg-gray-300"
- } transition-colors duration-200`}
- >
- <div
- className={`absolute top-0.5 left-0.5 bg-white border border-gray-300 rounded-full h-5 w-5 transition-transform duration-200 ${
- allowOpenAIFallback
- ? "translate-x-5"
- : "translate-x-0"
- }`}
- ></div>
- </div>
- </label>
- </div>
- <p className="text-xs text-purple-700">
- If local processing fails, try OpenAI API as backup
- </p>
-
- {/* API Key field - only show if fallback is enabled */}
- {allowOpenAIFallback && (
- <div className="p-3 bg-purple-50 border border-purple-200 rounded-lg">
- <label className="block text-sm font-medium text-purple-800 mb-2">
- OpenAI API Key (for fallback)
- </label>
- <div className="flex gap-2">
- <Input
- type="password"
- placeholder="sk-..."
- value={apiKey}
- onChange={(e) => setApiKey(e.target.value)}
- className="flex-1 text-sm border-purple-300 focus:border-purple-500"
- />
- <Button
- variant="outline"
- size="sm"
- onClick={() =>
- pasteFromClipboardWithFallback(setApiKey)
- }
- className="border-purple-300 text-purple-700 hover:bg-purple-50"
- >
- Paste
- </Button>
- </div>
- <p className="text-xs text-purple-600 mt-1">
- Only used if local processing fails
- </p>
- </div>
- )}
- </div>
-
- <WhisperModelPicker
- selectedModel={whisperModel}
- onModelSelect={setWhisperModel}
- variant="settings"
- />
- </div>
- ) : (
- <div className="bg-white border border-purple-200 rounded-lg p-6">
- <div className="text-center">
- <div className="text-3xl mb-4">πŸ“¦ </div>
- <h5 className="font-medium text-purple-900 text-lg mb-2">
- Install Local Processing
- </h5>
- <p className="text-sm text-purple-700 mb-4 max-w-sm mx-auto">
- We'll install Whisper automatically. No technical
- setup required.
- </p>
-
- {whisperHook.installingWhisper ? (
- <div className="space-y-4">
- <div className="bg-purple-50 rounded-lg p-4 border border-purple-200">
- <div className="flex items-center justify-center space-x-3 mb-2">
- <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-purple-600"></div>
- <span className="font-medium text-purple-900">
- Installing...
- </span>
- </div>
- {whisperHook.installProgress && (
- <div className="text-xs text-purple-600 bg-white p-2 rounded font-mono">
- {whisperHook.installProgress}
- </div>
- )}
- </div>
- <p className="text-xs text-purple-600">
- This takes a few minutes. Keep the app open.
- </p>
- </div>
- ) : (
- <div className="space-y-4">
- <Button
- onClick={whisperHook.installWhisper}
- className="bg-purple-600 hover:bg-purple-700"
- >
- Install Whisper
- </Button>
-
- <div className="flex items-center justify-center">
- <Button
- onClick={whisperHook.checkWhisperInstallation}
- variant="outline"
- size="sm"
- className="text-purple-600 border-purple-300 hover:bg-purple-50"
- >
- Check if already installed
- </Button>
- </div>
- </div>
- )}
- </div>
- </div>
- )}
+ <p className="text-xs text-purple-600">
+ Get your API key from console.anthropic.com
+ </p>
</div>
)}
+ </>
+ )}
- {/* Language Selection - shown for both modes */}
- <div className="space-y-4 p-4 bg-gray-50 border border-gray-200 rounded-xl">
- <h4 className="font-medium text-gray-900 mb-3">
- 🌍 Preferred Language
- </h4>
- <label className="block text-sm font-medium text-gray-700 mb-2">
- Which language do you primarily speak?
- </label>
- <LanguageSelector
- value={preferredLanguage}
- onChange={(value) => {
- setPreferredLanguage(value);
- localStorage.setItem("preferredLanguage", value);
- setAlertDialog({
- open: true,
- title: "Language Updated",
- description: `Preferred language set to: ${getLanguageLabel(
- value
- )}`,
- });
- }}
- className="w-full"
- />
- <p className="text-xs text-gray-600 mt-1">
- {useLocalWhisper
- ? "Helps Whisper better understand your speech"
- : "Improves OpenAI transcription speed and accuracy"}
- </p>
- </div>
+ <Button onClick={saveReasoningSettings} className="w-full">
+ Save Reasoning Settings
+ </Button>
+ </div>
+ );
- <Button
- onClick={useLocalWhisper ? saveWhisperSettings : saveApiKey}
- className="w-full"
- disabled={!useLocalWhisper && !apiKey.trim()}
- >
- {useLocalWhisper ? "Save Whisper Settings" : "Save API Key"}
- </Button>
- </div>
- </CardContent>
- </Card>
-
- {/* Dictation Settings Card */}
- <Card className="bg-white relative z-10">
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <Keyboard size={18} className="text-indigo-600" />
- Dictation Setup
- </CardTitle>
- <p className="text-sm text-neutral-600 mt-2 leading-relaxed">
- Configure how you want to activate voice transcription.
+ case "hotkey":
+ return (
+ <div className="space-y-6">
+ <div>
+ <h3 className="text-lg font-semibold text-gray-900 mb-2">
+ Dictation Hotkey
+ </h3>
+ <p className="text-sm text-gray-600 mb-6">
+ Configure the key you press to start and stop voice dictation.
</p>
- </CardHeader>
- <CardContent className="space-y-5">
- <div className="space-y-5">
- <div>
- <label className="block text-sm font-medium text-neutral-700 mb-2">
- Activation Key
- </label>
- <Input
- placeholder="Current: ` (backtick)"
- value={key}
- onChange={(e) => setKey(e.target.value)}
- className="mb-3"
- />
- <Button
- onClick={saveKey}
- disabled={!key.trim()}
- variant="outline"
- size="sm"
- >
- Save Key
- </Button>
- </div>
+ </div>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
- <Button
- onClick={permissionsHook.requestMicPermission}
- variant="outline"
- >
- <span className="mr-2">🎀</span>
- Enable Microphone
- </Button>
- <Button
- onClick={permissionsHook.testAccessibilityPermission}
- variant="outline"
- >
- <span className="mr-2">πŸ”“</span>
- Check Permissions
- </Button>
- </div>
+ <div className="space-y-4 p-4 bg-blue-50 border border-blue-200 rounded-xl">
+ <h4 className="font-medium text-blue-900">Activation Key</h4>
+ <Input
+ placeholder="Current: ` (backtick)"
+ value={key}
+ onChange={(e) => setKey(e.target.value)}
+ className="text-center text-lg font-mono"
+ />
+ <Button onClick={saveKey} disabled={!key.trim()} size="sm">
+ Save Hotkey
+ </Button>
+ </div>
- <Button
- onClick={resetAccessibilityPermissions}
- variant="secondary"
- className="w-full"
- >
- <span className="mr-2">βš™οΈ</span>
- Fix Permission Issues
- </Button>
- </div>
- </CardContent>
- </Card>
-
- {/* Updates Card */}
- <Card className="bg-white relative z-10">
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <RefreshCw size={18} className="text-indigo-600" />
+ <div className="space-y-3">
+ <Button
+ onClick={permissionsHook.requestMicPermission}
+ variant="outline"
+ className="w-full"
+ >
+ <Mic className="mr-2 h-4 w-4" />
+ Test Microphone Permission
+ </Button>
+ <Button
+ onClick={permissionsHook.testAccessibilityPermission}
+ variant="outline"
+ className="w-full"
+ >
+ <Shield className="mr-2 h-4 w-4" />
+ Test Accessibility Permission
+ </Button>
+ <Button
+ onClick={resetAccessibilityPermissions}
+ variant="secondary"
+ className="w-full"
+ >
+ <span className="mr-2">βš™οΈ</span>
+ Fix Permission Issues
+ </Button>
+ </div>
+ </div>
+ );
+
+ case "updates":
+ return (
+ <div className="space-y-6">
+ <div>
+ <h3 className="text-lg font-semibold text-gray-900 mb-2">
App Updates
- </CardTitle>
- <p className="text-sm text-neutral-600 mt-2 leading-relaxed">
+ </h3>
+ <p className="text-sm text-gray-600 mb-6">
Keep OpenWispr up to date with the latest features and
improvements.
</p>
- </CardHeader>
- <CardContent className="space-y-4">
- <div className="flex items-center justify-between p-4 bg-neutral-50 rounded-lg">
- <div>
- <p className="text-sm font-medium text-neutral-800">
- Current Version
- </p>
- <p className="text-xs text-neutral-600">
- {currentVersion || "Loading..."}
- </p>
- </div>
- <div className="flex items-center gap-2">
- {updateStatus.isDevelopment ? (
- <span className="text-xs text-amber-600 bg-amber-100 px-2 py-1 rounded-full">
- Development Mode
- </span>
- ) : updateStatus.updateAvailable ? (
- <span className="text-xs text-green-600 bg-green-100 px-2 py-1 rounded-full">
- Update Available
- </span>
- ) : (
- <span className="text-xs text-neutral-600 bg-neutral-100 px-2 py-1 rounded-full">
- Up to Date
- </span>
- )}
- </div>
+ </div>
+ <div className="flex items-center justify-between p-4 bg-neutral-50 rounded-lg">
+ <div>
+ <p className="text-sm font-medium text-neutral-800">
+ Current Version
+ </p>
+ <p className="text-xs text-neutral-600">
+ {currentVersion || "Loading..."}
+ </p>
+ </div>
+ <div className="flex items-center gap-2">
+ {updateStatus.isDevelopment ? (
+ <span className="text-xs text-amber-600 bg-amber-100 px-2 py-1 rounded-full">
+ Development Mode
+ </span>
+ ) : updateStatus.updateAvailable ? (
+ <span className="text-xs text-green-600 bg-green-100 px-2 py-1 rounded-full">
+ Update Available
+ </span>
+ ) : (
+ <span className="text-xs text-neutral-600 bg-neutral-100 px-2 py-1 rounded-full">
+ Up to Date
+ </span>
+ )}
</div>
+ </div>
- <div className="space-y-3">
- <Button
- onClick={async () => {
- setCheckingForUpdates(true);
- try {
- const result = await window.electronAPI.checkForUpdates();
- if (result.updateAvailable) {
- setUpdateInfo({
- version: result.version,
- releaseDate: result.releaseDate,
- releaseNotes: result.releaseNotes,
- });
+ <div className="space-y-3">
+ <Button
+ onClick={async () => {
+ setCheckingForUpdates(true);
+ try {
+ const result = await window.electronAPI?.checkForUpdates();
+ if (result?.updateAvailable) {
+ setUpdateInfo({
+ version: result.version,
+ releaseDate: result.releaseDate,
+ releaseNotes: result.releaseNotes,
+ });
+ setUpdateStatus((prev) => ({
+ ...prev,
+ updateAvailable: true,
+ }));
+ setAlertDialog({
+ open: true,
+ title: "Update Available",
+ description: `Update available: v${result.version}`,
+ });
+ } else {
+ setAlertDialog({
+ open: true,
+ title: "No Updates",
+ description: result?.message || "No updates available",
+ });
+ }
+ } catch (error: any) {
+ setAlertDialog({
+ open: true,
+ title: "Update Check Failed",
+ description: `Error checking for updates: ${error.message}`,
+ });
+ } finally {
+ setCheckingForUpdates(false);
+ }
+ }}
+ disabled={checkingForUpdates || updateStatus.isDevelopment}
+ className="w-full"
+ >
+ {checkingForUpdates ? (
+ <>
+ <RefreshCw size={16} className="animate-spin mr-2" />
+ Checking for Updates...
+ </>
+ ) : (
+ <>
+ <RefreshCw size={16} className="mr-2" />
+ Check for Updates
+ </>
+ )}
+ </Button>
+
+ {updateStatus.updateAvailable &&
+ !updateStatus.updateDownloaded && (
+ <Button
+ onClick={async () => {
+ setDownloadingUpdate(true);
+ try {
+ await window.electronAPI?.downloadUpdate();
setUpdateStatus((prev) => ({
...prev,
- updateAvailable: true,
+ updateDownloaded: true,
}));
setAlertDialog({
open: true,
- title: "Update Available",
- description: `Update available: v${result.version}`,
+ title: "Update Downloaded",
+ description:
+ "Update downloaded successfully! You can now install it.",
});
- } else {
+ } catch (error: any) {
setAlertDialog({
open: true,
- title: "No Updates",
- description: result.message || "No updates available",
+ title: "Download Failed",
+ description: `Error downloading update: ${error.message}`,
});
+ } finally {
+ setDownloadingUpdate(false);
}
- } catch (error) {
+ }}
+ disabled={downloadingUpdate || updateStatus.isDevelopment}
+ className="w-full"
+ >
+ {downloadingUpdate ? (
+ <>
+ <Download size={16} className="animate-bounce mr-2" />
+ Downloading Update...
+ </>
+ ) : (
+ <>
+ <Download size={16} className="mr-2" />
+ Download Update
+ </>
+ )}
+ </Button>
+ )}
+
+ {updateStatus.updateDownloaded && (
+ <Button
+ onClick={async () => {
+ try {
+ await window.electronAPI?.installUpdate();
+ } catch (error: any) {
setAlertDialog({
open: true,
- title: "Update Check Failed",
- description: `Error checking for updates: ${error.message}`,
+ title: "Install Failed",
+ description: `Error installing update: ${error.message}`,
});
- } finally {
- setCheckingForUpdates(false);
}
}}
- disabled={checkingForUpdates || updateStatus.isDevelopment}
- className="w-full"
+ disabled={updateStatus.isDevelopment}
+ className="w-full bg-green-600 hover:bg-green-700"
>
- {checkingForUpdates ? (
- <>
- <RefreshCw size={16} className="animate-spin mr-2" />
- Checking for Updates...
- </>
- ) : (
- <>
- <RefreshCw size={16} className="mr-2" />
- Check for Updates
- </>
- )}
+ <span className="mr-2">πŸ”„</span>
+ Install Update & Restart
</Button>
+ )}
- {updateStatus.updateAvailable &&
- !updateStatus.updateDownloaded && (
- <Button
- onClick={async () => {
- setDownloadingUpdate(true);
- try {
- await window.electronAPI.downloadUpdate();
- setUpdateStatus((prev) => ({
- ...prev,
- updateDownloaded: true,
- }));
- setAlertDialog({
- open: true,
- title: "Update Downloaded",
- description:
- "Update downloaded successfully! You can now install it.",
- });
- } catch (error) {
- setAlertDialog({
- open: true,
- title: "Download Failed",
- description: `Error downloading update: ${error.message}`,
- });
- } finally {
- setDownloadingUpdate(false);
- }
- }}
- disabled={downloadingUpdate || updateStatus.isDevelopment}
- className="w-full"
- >
- {downloadingUpdate ? (
- <>
- <Download size={16} className="animate-bounce mr-2" />
- Downloading Update...
- </>
- ) : (
- <>
- <Download size={16} className="mr-2" />
- Download Update
- </>
- )}
- </Button>
+ {updateInfo.version && (
+ <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
+ <h4 className="font-medium text-blue-900 mb-1">
+ Update Details
+ </h4>
+ <p className="text-sm text-blue-800 mb-1">
+ Version: {updateInfo.version}
+ </p>
+ {updateInfo.releaseDate && (
+ <p className="text-sm text-blue-700 mb-2">
+ Released:{" "}
+ {new Date(updateInfo.releaseDate).toLocaleDateString()}
+ </p>
)}
+ {updateInfo.releaseNotes && (
+ <details className="text-sm text-blue-700">
+ <summary className="cursor-pointer font-medium">
+ Release Notes
+ </summary>
+ <div className="mt-2 whitespace-pre-wrap">
+ {updateInfo.releaseNotes}
+ </div>
+ </details>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
- {updateStatus.updateDownloaded && (
- <Button
- onClick={async () => {
- try {
- await window.electronAPI.installUpdate();
- } catch (error) {
- setAlertDialog({
- open: true,
- title: "Install Failed",
- description: `Error installing update: ${error.message}`,
- });
- }
- }}
- disabled={updateStatus.isDevelopment}
- className="w-full bg-green-600 hover:bg-green-700"
- >
- <span className="mr-2">πŸ”„</span>
- Install Update & Restart
- </Button>
- )}
-
- {updateInfo.version && (
- <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
- <h4 className="font-medium text-blue-900 mb-1">
- Update Details
- </h4>
- <p className="text-sm text-blue-800 mb-1">
- Version: {updateInfo.version}
- </p>
- {updateInfo.releaseDate && (
- <p className="text-sm text-blue-700 mb-2">
- Released:{" "}
- {new Date(updateInfo.releaseDate).toLocaleDateString()}
- </p>
- )}
- {updateInfo.releaseNotes && (
- <details className="text-sm text-blue-700">
- <summary className="cursor-pointer font-medium">
- Release Notes
- </summary>
- <div className="mt-2 whitespace-pre-wrap">
- {updateInfo.releaseNotes}
- </div>
- </details>
- )}
- </div>
- )}
- </div>
- </CardContent>
- </Card>
-
- {/* About Card */}
- <Card className="bg-white relative z-10">
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <Info size={18} className="text-indigo-600" />
- About
- </CardTitle>
- </CardHeader>
- <CardContent>
- <p className="text-neutral-600 text-sm leading-relaxed mb-6">
+ case "about":
+ return (
+ <div className="space-y-6">
+ <div>
+ <h3 className="text-lg font-semibold text-gray-900 mb-2">
+ About OpenWispr
+ </h3>
+ <p className="text-sm text-gray-600 mb-6">
OpenWispr converts your speech to text using AI. Press your
hotkey, speak, and we'll type what you said wherever your cursor
is.
</p>
- <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
- <div className="text-center p-4 border border-neutral-200 rounded-xl bg-white">
- <div className="w-8 h-8 mx-auto mb-2 bg-indigo-600 rounded-lg flex items-center justify-center">
- <span className="text-white text-sm">⌨️</span>
- </div>
- <p className="font-medium text-neutral-800 mb-1">
- Default Hotkey
- </p>
- <p className="text-neutral-600 font-mono text-xs">
- ` (backtick)
- </p>
+ </div>
+
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
+ <div className="text-center p-4 border border-gray-200 rounded-xl bg-white">
+ <div className="w-8 h-8 mx-auto mb-2 bg-indigo-600 rounded-lg flex items-center justify-center">
+ <Keyboard className="w-4 h-4 text-white" />
</div>
- <div className="text-center p-4 border border-neutral-200 rounded-xl bg-white">
- <div className="w-8 h-8 mx-auto mb-2 bg-emerald-600 rounded-lg flex items-center justify-center">
- <span className="text-white text-sm">🏷️</span>
- </div>
- <p className="font-medium text-neutral-800 mb-1">Version</p>
- <p className="text-neutral-600 text-xs">0.1.0</p>
+ <p className="font-medium text-gray-800 mb-1">Default Hotkey</p>
+ <p className="text-gray-600 font-mono text-xs">` (backtick)</p>
+ </div>
+ <div className="text-center p-4 border border-gray-200 rounded-xl bg-white">
+ <div className="w-8 h-8 mx-auto mb-2 bg-emerald-600 rounded-lg flex items-center justify-center">
+ <span className="text-white text-sm">🏷️</span>
</div>
- <div className="text-center p-4 border border-neutral-200 rounded-xl bg-white">
- <div className="w-8 h-8 mx-auto mb-2 bg-green-600 rounded-lg flex items-center justify-center">
- <span className="text-white text-sm">βœ“</span>
- </div>
- <p className="font-medium text-neutral-800 mb-1">Status</p>
- <p className="text-green-600 text-xs font-medium">Active</p>
+ <p className="font-medium text-gray-800 mb-1">Version</p>
+ <p className="text-gray-600 text-xs">
+ {currentVersion || "0.1.0"}
+ </p>
+ </div>
+ <div className="text-center p-4 border border-gray-200 rounded-xl bg-white">
+ <div className="w-8 h-8 mx-auto mb-2 bg-green-600 rounded-lg flex items-center justify-center">
+ <span className="text-white text-sm">βœ“</span>
</div>
+ <p className="font-medium text-gray-800 mb-1">Status</p>
+ <p className="text-green-600 text-xs font-medium">Active</p>
</div>
- {/* Reset Onboarding */}
- <div className="border-t border-neutral-200 pt-4 space-y-3">
- <Button
- onClick={() => {
- 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"
- >
- <span className="mr-2">πŸ”„</span>
- Reset Onboarding
- </Button>
+ </div>
- {/* Cleanup App Data */}
- <Button
- onClick={() => {
- 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}`,
- });
+ {/* Reset Onboarding and Cleanup */}
+ <div className="border-t border-gray-200 pt-4 space-y-3">
+ <Button
+ onClick={() => {
+ 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"
+ >
+ <span className="mr-2">πŸ”„</span>
+ Reset Onboarding
+ </Button>
+
+ <Button
+ onClick={() => {
+ 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.",
});
- },
- variant: "destructive",
- });
- }}
- variant="outline"
- className="w-full text-red-600 border-red-300 hover:bg-red-50 hover:border-red-400"
+ 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"
+ >
+ <span className="mr-2">πŸ—‘οΈ</span>
+ Clean Up All App Data
+ </Button>
+ </div>
+ </div>
+ );
+
+ default:
+ return null;
+ }
+ };
+
+ 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}
+ actions={
+ <Button variant="ghost" size="icon" onClick={onBack}>
+ <ArrowLeft size={16} />
+ </Button>
+ }
+ />
+
+ <div className="flex h-[calc(100vh-60px)]">
+ {/* Sidebar */}
+ <div className="w-64 bg-gray-50 border-r border-gray-200 p-4">
+ <nav className="space-y-2">
+ {sidebarItems.map((item) => {
+ const Icon = item.icon;
+ return (
+ <button
+ key={item.id}
+ onClick={() => setActiveSection(item.id)}
+ className={`w-full flex items-center gap-3 px-3 py-2 text-left text-sm rounded-lg transition-colors ${
+ activeSection === item.id
+ ? "bg-indigo-100 text-indigo-700"
+ : "text-gray-700 hover:bg-gray-100"
+ }`}
>
- <span className="mr-2">πŸ—‘οΈ</span>
- Clean Up All App Data
- </Button>
- </div>
- </CardContent>
- </Card>
-
- {/* Footer */}
- <div className="text-center py-6">
- <p className="text-neutral-500 text-sm">
- Built for thinkers who move at the speed of thought
- </p>
+ <Icon className="h-4 w-4" />
+ {item.label}
+ {activeSection === item.id && (
+ <ChevronRight className="h-4 w-4 ml-auto" />
+ )}
+ </button>
+ );
+ })}
+ </nav>
+ </div>
+
+ {/* Main Content */}
+ <div className="flex-1 overflow-y-auto">
+ <div className="max-w-2xl mx-auto p-6">
+ <Card>
+ <CardContent className="p-6">
+ {renderSectionContent()}
+ </CardContent>
+ </Card>
</div>
</div>
</div>
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index 4fb60e3fc..f310c5684 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -1,4 +1,5 @@
import TextCleanup from "../utils/textCleanup";
+import ReasoningService from "../services/ReasoningService";
class AudioManager {
constructor() {
@@ -77,6 +78,9 @@ class AudioManager {
const useLocalWhisper =
localStorage.getItem("useLocalWhisper") === "true";
const whisperModel = localStorage.getItem("whisperModel") || "base";
+ const useReasoning = localStorage.getItem("useReasoningModel") === "true";
+ const reasoningModel =
+ localStorage.getItem("reasoningModel") || "gpt-3.5-turbo";
let result;
if (useLocalWhisper) {
@@ -84,10 +88,9 @@ class AudioManager {
} else {
result = await this.processWithOpenAIAPI(audioBlob);
}
-
this.onTranscriptionComplete?.(result);
} catch (error) {
- console.error("Transcription error:", error);
+ console.error(`🎧 [AudioManager] ❌ Transcription error:`, error);
this.onError?.({
title: "Transcription Error",
description: `Transcription failed: ${error.message}`,
@@ -98,20 +101,31 @@ class AudioManager {
}
}
- // Clean text transcription using comprehensive utility
static cleanTranscription(text, options = {}) {
return TextCleanup.cleanTranscription(text, {
removeArtifacts: true,
normalizeSpaces: true,
fixPunctuation: true,
- removeFillers: true, // Enable filler removal by default
+ removeFillers: true,
removeRepetitions: true,
capitalizeFirst: true,
- addPeriod: false, // Don't auto-add periods to preserve user intent
+ addPeriod: false,
...options,
});
}
+ static cleanTranscriptionForAPI(text) {
+ return TextCleanup.cleanTranscription(text, {
+ removeArtifacts: true,
+ normalizeSpaces: true,
+ fixPunctuation: false, // Let reasoning model handle this
+ removeFillers: false, // Preserve context for reasoning model
+ removeRepetitions: false, // Let reasoning model decide
+ capitalizeFirst: false, // Let reasoning model handle
+ addPeriod: false,
+ });
+ }
+
async processWithLocalWhisper(audioBlob, model = "base") {
try {
const arrayBuffer = await audioBlob.arrayBuffer();
@@ -291,6 +305,16 @@ class AudioManager {
return new Blob([arrayBuffer], { type: "audio/wav" });
}
+ async processWithReasoningModel(text) {
+ try {
+ const model = localStorage.getItem("reasoningModel") || "gpt-3.5-turbo";
+ return await ReasoningService.processText(text, model);
+ } catch (error) {
+ console.warn(`Reasoning failed, using basic cleanup:`, error.message);
+ return AudioManager.cleanTranscription(text);
+ }
+ }
+
async processWithOpenAIAPI(audioBlob) {
try {
// Parallel: get API key (cached) and optimize audio
@@ -326,10 +350,24 @@ class AudioManager {
}
const result = await response.json();
- const text = AudioManager.cleanTranscription(result.text);
-
- if (text) {
- return { success: true, text, source: "openai" };
+ const rawText = AudioManager.cleanTranscriptionForAPI(result.text);
+
+ if (rawText) {
+ // Apply reasoning model if enabled
+ const useReasoning =
+ localStorage.getItem("useReasoningModel") === "true";
+
+ if (useReasoning) {
+ const reasonedText = await this.processWithReasoningModel(rawText);
+ return {
+ success: true,
+ text: reasonedText,
+ source: "openai-reasoned",
+ };
+ } else {
+ const finalText = AudioManager.cleanTranscription(rawText);
+ return { success: true, text: finalText, source: "openai" };
+ }
} else {
throw new Error("No text transcribed");
}
diff --git a/src/services/ReasoningService.js b/src/services/ReasoningService.js
new file mode 100644
index 000000000..506219aa0
--- /dev/null
+++ b/src/services/ReasoningService.js
@@ -0,0 +1,151 @@
+import { getModelProvider } from "../utils/languages.ts";
+
+const REASONING_PROMPT = `You are a text formatting assistant. Your job is to clean up and format voice-to-text transcriptions while preserving the speaker's natural tone and intent.
+
+Rules:
+1. If the speaker gives instructions like "scratch that", "ignore that", "delete the previous part", "never mind", or similar - follow them and remove the referenced content
+2. If the speaker says "put this in a list" or starts listing items, format as a proper list
+3. Fix obvious speech-to-text errors, punctuation, and capitalization
+4. Maintain the speaker's natural tone and style
+5. Don't add content - only clean up what's there
+6. If unclear, err on the side of minimal changes
+
+Transcript to format:
+"{{text}}"
+
+Formatted text:`;
+
+class ReasoningService {
+ constructor() {
+ this.apiKeyCache = new Map();
+ }
+
+ async processText(text, model = "gpt-3.5-turbo") {
+ const provider = getModelProvider(model);
+
+ try {
+ switch (provider) {
+ case "openai":
+ return await this.processWithOpenAI(text, model);
+ case "anthropic":
+ return await this.processWithAnthropic(text, model);
+ default:
+ throw new Error(`Unsupported reasoning provider: ${provider}`);
+ }
+ } catch (error) {
+ console.error(`ReasoningService error (${provider}):`, error.message);
+ throw error;
+ }
+ }
+
+ async processWithOpenAI(text, model) {
+ const apiKey = await this.getAPIKey("openai");
+ const prompt = REASONING_PROMPT.replace("{{text}}", text);
+ const maxTokens = Math.max(100, text.length * 2);
+
+ const response = await fetch("https://api.openai.com/v1/chat/completions", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${apiKey}`,
+ },
+ body: JSON.stringify({
+ model,
+ messages: [{ role: "user", content: prompt }],
+ max_tokens: maxTokens,
+ temperature: 0.3,
+ }),
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ throw new Error(`OpenAI API Error: ${response.status} - ${errorText}`);
+ }
+
+ const result = await response.json();
+ const reasonedText = result.choices[0]?.message?.content?.trim();
+
+ if (!reasonedText) {
+ throw new Error("Empty response from OpenAI");
+ }
+
+ return reasonedText;
+ }
+
+ async processWithAnthropic(text, model) {
+ const apiKey = await this.getAPIKey("anthropic");
+ const prompt = REASONING_PROMPT.replace("{{text}}", text);
+ const maxTokens = Math.max(100, text.length * 2);
+
+ const response = await fetch("https://api.anthropic.com/v1/messages", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "x-api-key": apiKey,
+ "anthropic-version": "2023-06-01",
+ },
+ body: JSON.stringify({
+ model,
+ max_tokens: maxTokens,
+ messages: [{ role: "user", content: prompt }],
+ temperature: 0.3,
+ }),
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ throw new Error(`Anthropic API Error: ${response.status} - ${errorText}`);
+ }
+
+ const result = await response.json();
+ const reasonedText = result.content[0]?.text?.trim();
+
+ if (!reasonedText) {
+ throw new Error("Empty response from Anthropic");
+ }
+
+ return reasonedText;
+ }
+
+ async getAPIKey(provider) {
+ // Check cache first
+ if (this.apiKeyCache.has(provider)) {
+ return this.apiKeyCache.get(provider);
+ }
+
+ let apiKey;
+
+ switch (provider) {
+ case "openai":
+ apiKey =
+ (await window.electronAPI?.getOpenAIKey()) ||
+ localStorage.getItem("openaiApiKey");
+ break;
+ case "anthropic":
+ apiKey =
+ (await window.electronAPI?.getAnthropicKey()) ||
+ localStorage.getItem("anthropicApiKey");
+ break;
+ default:
+ throw new Error(`Unknown provider: ${provider}`);
+ }
+
+ if (
+ !apiKey ||
+ apiKey.trim() === "" ||
+ apiKey === "your_openai_api_key_here"
+ ) {
+ throw new Error(`${provider} API key not found`);
+ }
+
+ // Cache the key
+ this.apiKeyCache.set(provider, apiKey);
+ return apiKey;
+ }
+
+ clearCache() {
+ this.apiKeyCache.clear();
+ }
+}
+
+export default new ReasoningService();
diff --git a/src/utils/languages.ts b/src/utils/languages.ts
index f96a29d81..ddfc9f19a 100644
--- a/src/utils/languages.ts
+++ b/src/utils/languages.ts
@@ -63,3 +63,47 @@ export const getLanguageLabel = (code: string): string => {
const option = LANGUAGE_OPTIONS.find(lang => lang.value === code);
return option?.label || code;
};
+
+// Reasoning model configuration with provider abstraction
+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" },
+ ]
+ },
+ 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" },
+ ]
+ }
+};
+
+// Get all available models across providers
+export const getAllReasoningModels = () => {
+ return Object.entries(REASONING_PROVIDERS).flatMap(([providerId, provider]) =>
+ provider.models.map(model => ({
+ ...model,
+ provider: providerId,
+ 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);
+ 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';
+};