Skip to content

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

feat: adds support for custom LLM and transcription endpoints

ayalda7202feaf683d
diff --git a/src/components/AIModelSelectorEnhanced.tsx b/src/components/AIModelSelectorEnhanced.tsx
index ebc90084f..78ad81454 100644
--- a/src/components/AIModelSelectorEnhanced.tsx
+++ b/src/components/AIModelSelectorEnhanced.tsx
@@ -1,12 +1,59 @@
-import React, { useState, useEffect } from 'react';
+import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { Button } from './ui/button';
import { Input } from './ui/input';
-import { Cloud, Lock, Brain, Zap, Globe, Cpu, Download, Check } from 'lucide-react';
+import { Cloud, Lock, Brain, Zap, Globe, Cpu, Download, Check, Wrench } from 'lucide-react';
import ApiKeyInput from './ui/ApiKeyInput';
import { UnifiedModelPickerCompact } from './UnifiedModelPicker';
+import { API_ENDPOINTS, buildApiUrl, normalizeBaseUrl } from '../config/constants';
import { REASONING_PROVIDERS } from '../utils/languages';
import { modelRegistry } from '../models/ModelRegistry';
+type CloudModelOption = {
+ value: string;
+ label: string;
+ description?: string;
+ icon?: string;
+ ownedBy?: string;
+};
+
+const ICON_BASE_PATH = '/assets/icons/providers';
+
+const PROVIDER_ICON_MAP: Record<string, string> = {
+ openai: 'openai',
+ anthropic: 'anthropic',
+ gemini: 'gemini',
+ llama: 'llama',
+ mistral: 'mistral',
+ qwen: 'qwen',
+ 'openai-oss': 'openai-oss',
+};
+
+const OWNED_BY_ICON_RULES: Array<{ match: RegExp; icon: string }> = [
+ { match: /(openai|system|default|gpt|davinci)/, icon: 'openai' },
+ { match: /(azure)/, icon: 'openai' },
+ { match: /(anthropic|claude)/, icon: 'anthropic' },
+ { match: /(google|gemini)/, icon: 'gemini' },
+ { match: /(meta|llama)/, icon: 'llama' },
+ { match: /(mistral)/, icon: 'mistral' },
+ { match: /(qwen|ali|tongyi)/, icon: 'qwen' },
+ { match: /(openrouter|oss)/, icon: 'openai-oss' },
+];
+
+const getProviderIconPath = (providerId: string): string => {
+ const iconId = PROVIDER_ICON_MAP[providerId] || 'openai';
+ return `${ICON_BASE_PATH}/${iconId}.svg`;
+};
+
+const resolveOwnedByIcon = (ownedBy?: string): string | undefined => {
+ if (!ownedBy) return undefined;
+ const normalized = ownedBy.toLowerCase();
+ const rule = OWNED_BY_ICON_RULES.find(({ match }) => match.test(normalized));
+ if (rule) {
+ return `${ICON_BASE_PATH}/${rule.icon}.svg`;
+ }
+ return undefined;
+};
+
interface AIModelSelectorEnhancedProps {
useReasoningModel: boolean;
setUseReasoningModel: (value: boolean) => void;
@@ -14,6 +61,8 @@ interface AIModelSelectorEnhancedProps {
setReasoningModel: (model: string) => void;
localReasoningProvider: string;
setLocalReasoningProvider: (provider: string) => void;
+ cloudReasoningBaseUrl: string;
+ setCloudReasoningBaseUrl: (value: string) => void;
openaiApiKey: string;
setOpenaiApiKey: (key: string) => void;
anthropicApiKey: string;
@@ -28,7 +77,11 @@ interface AIModelSelectorEnhancedProps {
const ProviderIcon = ({ provider }: { provider: string }) => {
const iconClass = "w-5 h-5";
const [svgError, setSvgError] = React.useState(false);
-
+
+ if (provider === 'custom') {
+ return <Wrench className={iconClass} />;
+ }
+
// Default fallback icons for each provider
const getFallbackIcon = () => {
switch (provider) {
@@ -41,6 +94,7 @@ const ProviderIcon = ({ provider }: { provider: string }) => {
case 'mistral': return <Zap className={iconClass} />;
case 'llama': return <Cpu className={iconClass} />;
case 'openai-oss': return <Globe className={iconClass} />;
+ case 'custom': return <Wrench className={iconClass} />;
default: return <Brain className={iconClass} />;
}
};
@@ -71,6 +125,8 @@ export default function AIModelSelectorEnhanced({
setReasoningModel,
localReasoningProvider,
setLocalReasoningProvider,
+ cloudReasoningBaseUrl,
+ setCloudReasoningBaseUrl,
openaiApiKey,
setOpenaiApiKey,
anthropicApiKey,
@@ -85,9 +141,240 @@ export default function AIModelSelectorEnhanced({
const [selectedLocalProvider, setSelectedLocalProvider] = useState('qwen');
const [downloadedModels, setDownloadedModels] = useState<Set<string>>(new Set());
const [downloadingModel, setDownloadingModel] = useState<string | null>(null);
+ const [customModelOptions, setCustomModelOptions] = useState<CloudModelOption[]>([]);
+ const [customModelsLoading, setCustomModelsLoading] = useState(false);
+ const [customModelsError, setCustomModelsError] = useState<string | null>(null);
+ const [customBaseInput, setCustomBaseInput] = useState(cloudReasoningBaseUrl);
+ const lastLoadedBaseRef = useRef<string | null>(null);
+ const pendingBaseRef = useRef<string | null>(null);
+ const isMountedRef = useRef(true);
+
+ useEffect(() => {
+ return () => {
+ isMountedRef.current = false;
+ };
+ }, []);
+ useEffect(() => {
+ setCustomBaseInput(cloudReasoningBaseUrl);
+ }, [cloudReasoningBaseUrl]);
+
+ const defaultOpenAIBase = useMemo(() => normalizeBaseUrl(API_ENDPOINTS.OPENAI_BASE), []);
+ const normalizedCustomReasoningBase = useMemo(
+ () => normalizeBaseUrl(cloudReasoningBaseUrl),
+ [cloudReasoningBaseUrl]
+ );
+ const latestReasoningBaseRef = useRef(normalizedCustomReasoningBase);
+ useEffect(() => {
+ latestReasoningBaseRef.current = normalizedCustomReasoningBase;
+ }, [normalizedCustomReasoningBase]);
+
+ const hasCustomBase = normalizedCustomReasoningBase !== '';
+ const effectiveReasoningBase = hasCustomBase
+ ? normalizedCustomReasoningBase
+ : defaultOpenAIBase;
+
+ const loadRemoteModels = useCallback(
+ async (baseOverride?: string, force = false) => {
+ const rawBase = (baseOverride ?? cloudReasoningBaseUrl) || '';
+ const normalizedBase = normalizeBaseUrl(rawBase);
+
+ if (!normalizedBase) {
+ if (isMountedRef.current) {
+ setCustomModelsLoading(false);
+ setCustomModelsError(null);
+ setCustomModelOptions([]);
+ }
+ return;
+ }
+
+ if (!force && lastLoadedBaseRef.current === normalizedBase) {
+ return;
+ }
+
+ if (!force && pendingBaseRef.current === normalizedBase) {
+ return;
+ }
- const cloudProviders = ['openai', 'anthropic', 'gemini'];
- const localProviders = modelRegistry.getAllProviders().map(p => p.id);
+ if (baseOverride !== undefined) {
+ latestReasoningBaseRef.current = normalizedBase;
+ }
+
+ pendingBaseRef.current = normalizedBase;
+
+ if (isMountedRef.current) {
+ setCustomModelsLoading(true);
+ setCustomModelsError(null);
+ setCustomModelOptions([]);
+ }
+
+ let apiKey: string | undefined;
+
+ try {
+ const keyFromState = openaiApiKey?.trim();
+ apiKey =
+ keyFromState && keyFromState.length > 0
+ ? keyFromState
+ : await window.electronAPI?.getOpenAIKey?.();
+
+ if (!normalizedBase.includes('://')) {
+ if (isMountedRef.current && latestReasoningBaseRef.current === normalizedBase) {
+ setCustomModelsError('Enter a full base URL including protocol (e.g. https://server/v1).');
+ setCustomModelsLoading(false);
+ }
+ return;
+ }
+
+ const headers: Record<string, string> = {};
+ if (apiKey) {
+ headers.Authorization = `Bearer ${apiKey}`;
+ }
+
+ const response = await fetch(buildApiUrl(normalizedBase, '/models'), {
+ method: 'GET',
+ headers,
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => '');
+ const summary = errorText
+ ? `${response.status} ${errorText.slice(0, 200)}`
+ : `${response.status} ${response.statusText}`;
+ throw new Error(summary.trim());
+ }
+
+ const payload = await response.json().catch(() => ({}));
+ const rawModels = Array.isArray(payload?.data)
+ ? payload.data
+ : Array.isArray(payload?.models)
+ ? payload.models
+ : [];
+
+ const mappedModels = (rawModels as Array<any>)
+ .map((item) => {
+ const value = item?.id || item?.name;
+ if (!value) {
+ return null;
+ }
+ const ownedBy = typeof item?.owned_by === 'string' ? item.owned_by : undefined;
+ const icon = resolveOwnedByIcon(ownedBy);
+ return {
+ value,
+ label: item?.id || item?.name || value,
+ description:
+ item?.description || (ownedBy ? `Owner: ${ownedBy}` : undefined),
+ icon,
+ ownedBy,
+ } as CloudModelOption;
+ })
+ .filter(Boolean) as CloudModelOption[];
+
+ if (isMountedRef.current && latestReasoningBaseRef.current === normalizedBase) {
+ setCustomModelOptions(mappedModels);
+ if (
+ mappedModels.length > 0 &&
+ !mappedModels.some((model) => model.value === reasoningModel)
+ ) {
+ setReasoningModel(mappedModels[0].value);
+ }
+ setCustomModelsError(null);
+ lastLoadedBaseRef.current = normalizedBase;
+ }
+ } catch (error) {
+ if (isMountedRef.current && latestReasoningBaseRef.current === normalizedBase) {
+ const message =
+ (error as Error).message || 'Unable to load models from endpoint.';
+ const unauthorized = /\b(401|403)\b/.test(message);
+ if (unauthorized && !apiKey) {
+ setCustomModelsError(
+ 'Endpoint rejected the request (401/403). Add an API key or adjust server auth settings.'
+ );
+ } else {
+ setCustomModelsError(message);
+ }
+ setCustomModelOptions([]);
+ }
+ } finally {
+ if (pendingBaseRef.current === normalizedBase) {
+ pendingBaseRef.current = null;
+ }
+ if (isMountedRef.current && latestReasoningBaseRef.current === normalizedBase) {
+ setCustomModelsLoading(false);
+ }
+ }
+ },
+ [cloudReasoningBaseUrl, openaiApiKey, reasoningModel, setReasoningModel]
+ );
+ const trimmedCustomBase = customBaseInput.trim();
+ const hasSavedCustomBase = Boolean((cloudReasoningBaseUrl || '').trim());
+ const isCustomBaseDirty =
+ trimmedCustomBase !== (cloudReasoningBaseUrl || '').trim();
+ const displayedCustomModels = useMemo<CloudModelOption[]>(() => {
+ if (isCustomBaseDirty) {
+ return [];
+ }
+ return customModelOptions;
+ }, [isCustomBaseDirty, customModelOptions]);
+
+ const cloudProviders = ['openai', 'anthropic', 'gemini', 'custom'];
+ const localProviders = modelRegistry.getAllProviders().map((p) => p.id);
+
+ const openaiModelOptions = useMemo<CloudModelOption[]>(() => {
+ const iconPath = getProviderIconPath('openai');
+ return REASONING_PROVIDERS.openai.models.map((model) => ({
+ ...model,
+ icon: iconPath,
+ }));
+ }, []);
+
+ const selectedCloudModels = useMemo<CloudModelOption[]>(() => {
+ if (selectedCloudProvider === 'openai') {
+ return openaiModelOptions;
+ }
+
+ if (selectedCloudProvider === 'custom') {
+ return displayedCustomModels;
+ }
+
+ const provider = REASONING_PROVIDERS[selectedCloudProvider as keyof typeof REASONING_PROVIDERS];
+ if (!provider?.models) {
+ return [];
+ }
+
+ const iconPath = getProviderIconPath(selectedCloudProvider);
+ return provider.models.map((model) => ({
+ ...model,
+ icon: iconPath,
+ }));
+ }, [selectedCloudProvider, openaiModelOptions, customModelOptions]);
+
+ const handleApplyCustomBase = useCallback(() => {
+ const trimmedBase = customBaseInput.trim();
+ setCustomBaseInput(trimmedBase);
+ setCloudReasoningBaseUrl(trimmedBase);
+ lastLoadedBaseRef.current = null;
+ loadRemoteModels(trimmedBase, true);
+ }, [customBaseInput, setCustomBaseInput, setCloudReasoningBaseUrl, loadRemoteModels]);
+
+ const handleResetCustomBase = useCallback(() => {
+ const defaultBase = API_ENDPOINTS.OPENAI_BASE;
+ setCustomBaseInput(defaultBase);
+ setCloudReasoningBaseUrl(defaultBase);
+ lastLoadedBaseRef.current = null;
+ loadRemoteModels(defaultBase, true);
+ }, [setCustomBaseInput, setCloudReasoningBaseUrl, loadRemoteModels]);
+
+ const handleRefreshCustomModels = useCallback(() => {
+ if (isCustomBaseDirty) {
+ handleApplyCustomBase();
+ return;
+ }
+
+ if (!trimmedCustomBase) {
+ return;
+ }
+
+ loadRemoteModels(undefined, true);
+ }, [handleApplyCustomBase, isCustomBaseDirty, trimmedCustomBase, loadRemoteModels]);
// Initialize based on current provider
useEffect(() => {
@@ -103,6 +390,31 @@ export default function AIModelSelectorEnhanced({
checkDownloadedModels();
}, []);
+ useEffect(() => {
+ if (selectedCloudProvider !== 'custom') {
+ return;
+ }
+
+ if (!hasCustomBase) {
+ setCustomModelsError(null);
+ setCustomModelOptions([]);
+ setCustomModelsLoading(false);
+ lastLoadedBaseRef.current = null;
+ return;
+ }
+
+ const normalizedBase = normalizedCustomReasoningBase;
+ if (!normalizedBase) {
+ return;
+ }
+
+ if (pendingBaseRef.current === normalizedBase || lastLoadedBaseRef.current === normalizedBase) {
+ return;
+ }
+
+ loadRemoteModels();
+ }, [selectedCloudProvider, hasCustomBase, normalizedCustomReasoningBase, loadRemoteModels]);
+
// Check which models are downloaded
const checkDownloadedModels = async () => {
try {
@@ -136,6 +448,20 @@ export default function AIModelSelectorEnhanced({
if (newMode === 'cloud') {
// Switch to cloud mode
setLocalReasoningProvider(selectedCloudProvider);
+
+ if (selectedCloudProvider === 'custom') {
+ setCustomBaseInput(cloudReasoningBaseUrl);
+ lastLoadedBaseRef.current = null;
+ pendingBaseRef.current = null;
+
+ if (customModelOptions.length > 0) {
+ setReasoningModel(customModelOptions[0].value);
+ } else if (hasCustomBase) {
+ loadRemoteModels();
+ }
+ return;
+ }
+
const provider = REASONING_PROVIDERS[selectedCloudProvider as keyof typeof REASONING_PROVIDERS];
if (provider?.models?.length > 0) {
setReasoningModel(provider.models[0].value);
@@ -153,7 +479,21 @@ export default function AIModelSelectorEnhanced({
const handleCloudProviderChange = (provider: string) => {
setSelectedCloudProvider(provider);
setLocalReasoningProvider(provider);
+
// Update model to first available
+ if (provider === 'custom') {
+ setCustomBaseInput(cloudReasoningBaseUrl);
+ lastLoadedBaseRef.current = null;
+ pendingBaseRef.current = null;
+
+ if (customModelOptions.length > 0) {
+ setReasoningModel(customModelOptions[0].value);
+ } else if (hasCustomBase) {
+ loadRemoteModels();
+ }
+ return;
+ }
+
const providerData = REASONING_PROVIDERS[provider as keyof typeof REASONING_PROVIDERS];
if (providerData?.models?.length > 0) {
setReasoningModel(providerData.models[0].value);
@@ -178,7 +518,8 @@ export default function AIModelSelectorEnhanced({
'qwen': 'indigo',
'mistral': 'orange',
'llama': 'blue',
- 'openai-oss': 'teal'
+ 'openai-oss': 'teal',
+ 'custom': 'cyan'
};
return colors[provider] || 'gray';
};
@@ -270,6 +611,10 @@ export default function AIModelSelectorEnhanced({
{cloudProviders.map((provider) => {
const isSelected = selectedCloudProvider === provider;
const color = getProviderColor(provider);
+ const providerDisplayName =
+ provider === 'custom'
+ ? 'Custom'
+ : REASONING_PROVIDERS[provider as keyof typeof REASONING_PROVIDERS]?.name || provider;
return (
<button
key={provider}
@@ -285,7 +630,7 @@ export default function AIModelSelectorEnhanced({
} : {}}
>
<ProviderIcon provider={provider} />
- <span>{REASONING_PROVIDERS[provider as keyof typeof REASONING_PROVIDERS]?.name}</span>
+ <span>{providerDisplayName}</span>
</button>
);
})}
@@ -293,78 +638,157 @@ export default function AIModelSelectorEnhanced({
<div className="p-4">
{/* Use UnifiedModelPickerCompact for cloud models */}
- <div className="space-y-3">
- <h4 className="text-sm font-medium text-gray-700">Select Model</h4>
- <UnifiedModelPickerCompact
- models={REASONING_PROVIDERS[selectedCloudProvider as keyof typeof REASONING_PROVIDERS]?.models || []}
- selectedModel={reasoningModel}
- onModelSelect={setReasoningModel}
- />
- </div>
-
- {/* API Key Configuration */}
- <div className="mt-4 pt-4 border-t border-gray-200">
- {selectedCloudProvider === 'openai' && (
+ {selectedCloudProvider === 'custom' ? (
+ <>
<div className="space-y-3">
- <h4 className="font-medium text-gray-900">API Configuration</h4>
- <ApiKeyInput
- apiKey={openaiApiKey}
- setApiKey={setOpenaiApiKey}
- helpText="Get your API key from platform.openai.com"
+ <h4 className="font-medium text-gray-900">Endpoint Settings</h4>
+ <Input
+ value={customBaseInput}
+ onChange={(event) => setCustomBaseInput(event.target.value)}
+ placeholder="https://api.openai.com/v1"
+ className="text-sm"
/>
- </div>
- )}
-
- {selectedCloudProvider === 'anthropic' && (
- <div className="space-y-3">
- <h4 className="font-medium text-gray-900">API Configuration</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"
- />
+ <div className="flex flex-wrap gap-2">
<Button
- variant="outline"
+ type="button"
size="sm"
- onClick={() => pasteFromClipboard(setAnthropicApiKey)}
+ variant="outline"
+ onClick={handleResetCustomBase}
>
- Paste
+ Reset to Default
</Button>
- </div>
- <p className="text-xs text-gray-600">
- Get your API key from console.anthropic.com
- </p>
- </div>
- )}
-
- {selectedCloudProvider === 'gemini' && (
- <div className="space-y-3">
- <h4 className="font-medium text-gray-900">API Configuration</h4>
- <div className="flex gap-2">
- <Input
- type="password"
- placeholder="AIza..."
- value={geminiApiKey}
- onChange={(e) => setGeminiApiKey(e.target.value)}
- className="flex-1 text-sm"
- />
<Button
- variant="outline"
+ type="button"
size="sm"
- onClick={() => pasteFromClipboard(setGeminiApiKey)}
+ variant="outline"
+ onClick={handleRefreshCustomModels}
+ disabled={customModelsLoading || (!trimmedCustomBase && !hasSavedCustomBase)}
>
- Paste
+ {customModelsLoading ? 'Loading models...' : isCustomBaseDirty ? 'Apply & Refresh' : 'Refresh Models'}
</Button>
</div>
+ {isCustomBaseDirty && (
+ <p className="text-xs text-amber-600">Apply the new base URL to refresh models.</p>
+ )}
<p className="text-xs text-gray-600">
- Get your API key from makersuite.google.com/app/apikey
+ We'll query <code>{hasCustomBase ? `${effectiveReasoningBase}/models` : `${defaultOpenAIBase}/models`}</code> for available models.
</p>
</div>
- )}
- </div>
+
+ <div className="space-y-3 pt-4 border-t border-gray-200">
+ <h4 className="font-medium text-gray-900">Authentication</h4>
+ <ApiKeyInput
+ apiKey={openaiApiKey}
+ setApiKey={setOpenaiApiKey}
+ helpText="Optional. Added as a Bearer token for your custom endpoint."
+ />
+ </div>
+
+ <div className="space-y-3 pt-4 border-t border-gray-200">
+ <h4 className="text-sm font-medium text-gray-700">Available Models</h4>
+ {!hasCustomBase && (
+ <p className="text-xs text-amber-600">
+ Enter a base URL to load models.
+ </p>
+ )}
+ {hasCustomBase && (
+ <>
+ {customModelsLoading && (
+ <p className="text-xs text-blue-600">Fetching model list...</p>
+ )}
+ {customModelsError && (
+ <p className="text-xs text-red-600">{customModelsError}</p>
+ )}
+ {!customModelsLoading && !customModelsError && customModelOptions.length === 0 && (
+ <p className="text-xs text-amber-600">
+ No models returned by this endpoint.
+ </p>
+ )}
+ </>
+ )}
+ <UnifiedModelPickerCompact
+ models={selectedCloudModels}
+ selectedModel={reasoningModel}
+ onModelSelect={setReasoningModel}
+ />
+ </div>
+ </>
+ ) : (
+ <>
+ <div className="space-y-3">
+ <h4 className="text-sm font-medium text-gray-700">Select Model</h4>
+ <UnifiedModelPickerCompact
+ models={selectedCloudModels}
+ selectedModel={reasoningModel}
+ onModelSelect={setReasoningModel}
+ />
+ </div>
+
+ {/* API Key Configuration */}
+ <div className="mt-4 pt-4 border-t border-gray-200">
+ {selectedCloudProvider === 'openai' && (
+ <div className="space-y-3">
+ <h4 className="font-medium text-gray-900">API Configuration</h4>
+ <ApiKeyInput
+ apiKey={openaiApiKey}
+ setApiKey={setOpenaiApiKey}
+ helpText="Get your API key from platform.openai.com"
+ />
+ </div>
+ )}
+
+ {selectedCloudProvider === 'anthropic' && (
+ <div className="space-y-3">
+ <h4 className="font-medium text-gray-900">API Configuration</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"
+ />
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => pasteFromClipboard(setAnthropicApiKey)}
+ >
+ Paste
+ </Button>
+ </div>
+ <p className="text-xs text-gray-600">
+ Get your API key from console.anthropic.com
+ </p>
+ </div>
+ )}
+
+ {selectedCloudProvider === 'gemini' && (
+ <div className="space-y-3">
+ <h4 className="font-medium text-gray-900">API Configuration</h4>
+ <div className="flex gap-2">
+ <Input
+ type="password"
+ placeholder="AIza..."
+ value={geminiApiKey}
+ onChange={(e) => setGeminiApiKey(e.target.value)}
+ className="flex-1 text-sm"
+ />
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => pasteFromClipboard(setGeminiApiKey)}
+ >
+ Paste
+ </Button>
+ </div>
+ <p className="text-xs text-gray-600">
+ Get your API key from makersuite.google.com/app/apikey
+ </p>
+ </div>
+ )}
+ </div>
+ </>
+ )}
</div>
</div>
</div>
diff --git a/src/components/OnboardingFlow.tsx b/src/components/OnboardingFlow.tsx
index 249180ed4..f233c81d8 100644
--- a/src/components/OnboardingFlow.tsx
+++ b/src/components/OnboardingFlow.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect, useCallback, useRef } from "react";
+import React, { useState, useEffect, useCallback, useRef, useMemo } from "react";
import { Card, CardContent } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
@@ -33,16 +33,26 @@ import { usePython } from "../hooks/usePython";
import { usePermissions } from "../hooks/usePermissions";
import { useClipboard } from "../hooks/useClipboard";
import { useSettings } from "../hooks/useSettings";
-import { getLanguageLabel, getReasoningModelLabel } from "../utils/languages";
+import { getLanguageLabel, REASONING_PROVIDERS } from "../utils/languages";
import LanguageSelector from "./ui/LanguageSelector";
+import { UnifiedModelPickerCompact } from "./UnifiedModelPicker";
const InteractiveKeyboard = React.lazy(() => import("./ui/Keyboard"));
import { setAgentName as saveAgentName } from "../utils/agentName";
import { formatHotkeyLabel } from "../utils/hotkeys";
+import { API_ENDPOINTS, buildApiUrl, normalizeBaseUrl } from "../config/constants";
interface OnboardingFlowProps {
onComplete: () => void;
}
+
+type ReasoningModelOption = {
+ value: string;
+ label: string;
+ description?: string;
+ icon?: string;
+};
+
export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
const [currentStep, setCurrentStep, removeCurrentStep] = useLocalStorage(
"onboardingCurrentStep",
@@ -57,6 +67,8 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
useLocalWhisper,
whisperModel,
preferredLanguage,
+ cloudTranscriptionBaseUrl,
+ cloudReasoningBaseUrl,
useReasoningModel,
reasoningModel,
openaiApiKey,
@@ -64,6 +76,8 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
setUseLocalWhisper,
setWhisperModel,
setPreferredLanguage,
+ setCloudTranscriptionBaseUrl,
+ setCloudReasoningBaseUrl,
setOpenaiApiKey,
setDictationKey,
updateTranscriptionSettings,
@@ -73,11 +87,172 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
const [apiKey, setApiKey] = useState(openaiApiKey);
const [hotkey, setHotkey] = useState(dictationKey || "`");
+ const [transcriptionBaseUrl, setTranscriptionBaseUrl] = useState(cloudTranscriptionBaseUrl);
+ const [reasoningBaseUrl, setReasoningBaseUrl] = useState(cloudReasoningBaseUrl);
const [agentName, setAgentName] = useState("Agent");
const readableHotkey = formatHotkeyLabel(hotkey);
const { alertDialog, showAlertDialog, hideAlertDialog } = useDialogs();
const practiceTextareaRef = useRef<HTMLInputElement>(null);
+ const trimmedReasoningBase = (reasoningBaseUrl || "").trim();
+ const normalizedReasoningBaseUrl = useMemo(
+ () => normalizeBaseUrl(trimmedReasoningBase),
+ [trimmedReasoningBase]
+ );
+ const hasEnteredReasoningBase = trimmedReasoningBase.length > 0;
+ const isValidReasoningBase = Boolean(
+ normalizedReasoningBaseUrl && normalizedReasoningBaseUrl.includes("://")
+ );
+ const usingCustomReasoningBase = hasEnteredReasoningBase && isValidReasoningBase;
+
+ const [customReasoningModels, setCustomReasoningModels] = useState<ReasoningModelOption[]>([]);
+ const [customModelsLoading, setCustomModelsLoading] = useState(false);
+ const [customModelsError, setCustomModelsError] = useState<string | null>(null);
+
+ const defaultReasoningModels = useMemo<ReasoningModelOption[]>(() => {
+ const provider = REASONING_PROVIDERS.openai;
+ return (
+ provider?.models?.map((model) => ({
+ value: model.value,
+ label: model.label,
+ description: model.description,
+ })) ?? []
+ );
+ }, []);
+
+ const displayedReasoningModels = usingCustomReasoningBase
+ ? customReasoningModels
+ : defaultReasoningModels;
+
+ const reasoningModelsEndpoint = useMemo(() => {
+ const base =
+ usingCustomReasoningBase && normalizedReasoningBaseUrl
+ ? normalizedReasoningBaseUrl
+ : API_ENDPOINTS.OPENAI_BASE;
+ return buildApiUrl(base, "/models");
+ }, [usingCustomReasoningBase, normalizedReasoningBaseUrl]);
+
+ const reasoningModelRef = useRef(reasoningModel);
+ useEffect(() => {
+ reasoningModelRef.current = reasoningModel;
+ }, [reasoningModel]);
+
+ useEffect(() => {
+ if (!usingCustomReasoningBase) {
+ setCustomModelsLoading(false);
+ setCustomReasoningModels([]);
+ setCustomModelsError(null);
+ return;
+ }
+
+ if (!normalizedReasoningBaseUrl) {
+ return;
+ }
+
+ let isCancelled = false;
+ const controller = new AbortController();
+
+ const loadModels = async () => {
+ setCustomModelsLoading(true);
+ setCustomModelsError(null);
+ try {
+ const headers: Record<string, string> = {};
+ const trimmedKey = apiKey.trim();
+ if (trimmedKey) {
+ headers.Authorization = `Bearer ${trimmedKey}`;
+ }
+
+ const response = await fetch(buildApiUrl(normalizedReasoningBaseUrl, "/models"), {
+ method: "GET",
+ headers,
+ signal: controller.signal,
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => "");
+ throw new Error(
+ errorText
+ ? `${response.status} ${errorText.slice(0, 200)}`
+ : `${response.status} ${response.statusText}`
+ );
+ }
+
+ const payload = await response.json().catch(() => ({}));
+ const rawModels = Array.isArray(payload?.data)
+ ? payload.data
+ : Array.isArray(payload?.models)
+ ? payload.models
+ : [];
+
+ const mappedModels = (rawModels as Array<any>)
+ .map((item) => {
+ const value = item?.id || item?.name;
+ if (!value) {
+ return null;
+ }
+
+ const description =
+ typeof item?.description === "string" && item.description.trim()
+ ? item.description.trim()
+ : undefined;
+ const ownedBy = typeof item?.owned_by === "string" ? item.owned_by : undefined;
+
+ return {
+ value,
+ label: item?.id || item?.name || value,
+ description: description || (ownedBy ? `Owner: ${ownedBy}` : undefined),
+ } as ReasoningModelOption;
+ })
+ .filter(Boolean) as ReasoningModelOption[];
+
+ if (isCancelled) {
+ return;
+ }
+
+ setCustomReasoningModels(mappedModels);
+
+ if (mappedModels.length === 0) {
+ setCustomModelsError("No models returned by this endpoint.");
+ } else if (!mappedModels.some((model) => model.value === reasoningModelRef.current)) {
+ updateReasoningSettings({ reasoningModel: mappedModels[0].value });
+ }
+ } catch (error) {
+ if (isCancelled) {
+ return;
+ }
+ if ((error as Error).name === "AbortError") {
+ return;
+ }
+ setCustomModelsError((error as Error).message || "Unable to load models from endpoint.");
+ setCustomReasoningModels([]);
+ } finally {
+ if (!isCancelled) {
+ setCustomModelsLoading(false);
+ }
+ }
+ };
+
+ loadModels();
+
+ return () => {
+ isCancelled = true;
+ controller.abort();
+ };
+ }, [usingCustomReasoningBase, normalizedReasoningBaseUrl, apiKey, updateReasoningSettings]);
+
+ useEffect(() => {
+ if (!usingCustomReasoningBase && defaultReasoningModels.length > 0) {
+ if (!defaultReasoningModels.some((model) => model.value === reasoningModel)) {
+ updateReasoningSettings({ reasoningModel: defaultReasoningModels[0].value });
+ }
+ }
+ }, [usingCustomReasoningBase, defaultReasoningModels, reasoningModel, updateReasoningSettings]);
+
+ const activeReasoningModelLabel = useMemo(() => {
+ const match = displayedReasoningModels.find((model) => model.value === reasoningModel);
+ return match?.label || reasoningModel;
+ }, [displayedReasoningModels, reasoningModel]);
+
const whisperHook = useWhisper(showAlertDialog);
const pythonHook = usePython(showAlertDialog);
const permissionsHook = usePermissions(showAlertDialog);
@@ -115,7 +290,22 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
}, [currentStep]);
const saveSettings = useCallback(async () => {
- updateTranscriptionSettings({ whisperModel, preferredLanguage });
+ const normalizedTranscriptionBase = (transcriptionBaseUrl || '').trim();
+ const normalizedReasoningBaseValue = (reasoningBaseUrl || '').trim();
+
+ setCloudTranscriptionBaseUrl(normalizedTranscriptionBase);
+ setCloudReasoningBaseUrl(normalizedReasoningBaseValue);
+
+ updateTranscriptionSettings({
+ whisperModel,
+ preferredLanguage,
+ cloudTranscriptionBaseUrl: normalizedTranscriptionBase,
+ });
+ updateReasoningSettings({
+ useReasoningModel,
+ reasoningModel,
+ cloudReasoningBaseUrl: normalizedReasoningBaseValue,
+ });
setDictationKey(hotkey);
try {
const result = await window.electronAPI?.updateHotkey?.(hotkey);
@@ -159,8 +349,13 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
permissionsHook.accessibilityPermissionGranted,
useLocalWhisper,
apiKey,
+ transcriptionBaseUrl,
+ reasoningBaseUrl,
updateTranscriptionSettings,
+ updateReasoningSettings,
updateApiKeys,
+ setCloudTranscriptionBaseUrl,
+ setCloudReasoningBaseUrl,
setDictationKey,
]);
@@ -407,6 +602,70 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
helpText="Get your API key from platform.openai.com"
/>
+ <div className="space-y-2">
+ <label className="block text-sm font-medium text-blue-900">Custom transcription base URL (optional)</label>
+ <Input
+ value={transcriptionBaseUrl}
+ onChange={(event) => setTranscriptionBaseUrl(event.target.value)}
+ placeholder="https://api.openai.com/v1"
+ className="text-sm"
+ />
+ <p className="text-xs text-blue-800">Cloud transcription requests default to <code>{API_ENDPOINTS.TRANSCRIPTION_BASE}</code>. Enter an OpenAI-compatible base URL to override.</p>
+ </div>
+
+ <div className="space-y-2">
+ <label className="block text-sm font-medium text-blue-900">Custom reasoning base URL (optional)</label>
+ <Input
+ value={reasoningBaseUrl}
+ onChange={(event) => setReasoningBaseUrl(event.target.value)}
+ placeholder="https://api.openai.com/v1"
+ className="text-sm"
+ />
+ <p className="text-xs text-blue-800">We'll load AI models from this endpoint's /v1/models route during setup. Leave empty to use the default OpenAI endpoint.</p>
+ </div>
+
+ <div className="space-y-3 pt-4 border-t border-blue-100">
+ <h4 className="font-medium text-blue-900">Reasoning Model</h4>
+ {hasEnteredReasoningBase ? (
+ <>
+ {isValidReasoningBase ? (
+ <p className="text-xs text-blue-800 break-all">
+ Models load from <code>{reasoningModelsEndpoint}</code>.
+ </p>
+ ) : (
+ <p className="text-xs text-amber-600">
+ Enter a full base URL including protocol (e.g. https://server/v1).
+ </p>
+ )}
+ {isValidReasoningBase && customModelsLoading && (
+ <p className="text-xs text-blue-600">Fetching models...</p>
+ )}
+ {isValidReasoningBase && customModelsError && (
+ <p className="text-xs text-red-600">{customModelsError}</p>
+ )}
+ {isValidReasoningBase &&
+ !customModelsLoading &&
+ !customModelsError &&
+ displayedReasoningModels.length === 0 && (
+ <p className="text-xs text-amber-600">
+ No models returned by this endpoint.
+ </p>
+ )}
+ </>
+ ) : (
+ <p className="text-xs text-blue-800">
+ Using OpenAI defaults from <code>{reasoningModelsEndpoint}</code>.
+ </p>
+ )}
+ <UnifiedModelPickerCompact
+ models={displayedReasoningModels}
+ selectedModel={reasoningModel}
+ onModelSelect={(modelId) =>
+ updateReasoningSettings({ reasoningModel: modelId })
+ }
+ />
+ </div>
+
<div className="bg-blue-50 p-4 rounded-lg">
<h4 className="font-medium text-blue-900 mb-2">
How to get your API key:
@@ -723,6 +982,20 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
: "OpenAI Cloud"}
</span>
</div>
+ {!useLocalWhisper && (
+ <div className="flex justify-between">
+ <span>Reasoning Model:</span>
+ <span className="font-medium">{activeReasoningModelLabel}</span>
+ </div>
+ )}
+ {!useLocalWhisper && hasEnteredReasoningBase && (
+ <div className="flex justify-between">
+ <span>Custom Endpoint:</span>
+ <span className="font-medium break-all">
+ {normalizedReasoningBaseUrl || trimmedReasoningBase}
+ </span>
+ </div>
+ )}
<div className="flex justify-between">
<span>Hotkey:</span>
<kbd className="bg-white px-2 py-1 rounded text-xs font-mono">
@@ -775,7 +1048,21 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
if (useLocalWhisper) {
return pythonHook.pythonInstalled && whisperHook.whisperInstalled;
} else {
- return apiKey.trim() !== "";
+ const trimmedKey = apiKey.trim();
+ if (!trimmedKey) {
+ return false;
+ }
+ if (!hasEnteredReasoningBase) {
+ return true;
+ }
+ if (!isValidReasoningBase) {
+ return false;
+ }
+ return (
+ customReasoningModels.length > 0 &&
+ !customModelsLoading &&
+ !customModelsError
+ );
}
case 3:
return (
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index dce7dff1e..46715a8c4 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -16,6 +16,7 @@ import { REASONING_PROVIDERS } from "../utils/languages";
import { formatHotkeyLabel } from "../utils/hotkeys";
import LanguageSelector from "./ui/LanguageSelector";
import PromptStudio from "./ui/PromptStudio";
+import { API_ENDPOINTS } from "../config/constants";
import AIModelSelectorEnhanced from "./AIModelSelectorEnhanced";
const InteractiveKeyboard = React.lazy(() => import("./ui/Keyboard"));
@@ -50,6 +51,8 @@ export default function SettingsPage({
allowLocalFallback,
fallbackWhisperModel,
preferredLanguage,
+ cloudTranscriptionBaseUrl,
+ cloudReasoningBaseUrl,
useReasoningModel,
reasoningModel,
reasoningProvider,
@@ -63,6 +66,8 @@ export default function SettingsPage({
setAllowLocalFallback,
setFallbackWhisperModel,
setPreferredLanguage,
+ setCloudTranscriptionBaseUrl,
+ setCloudReasoningBaseUrl,
setUseReasoningModel,
setReasoningModel,
setReasoningProvider,
@@ -188,10 +193,14 @@ export default function SettingsPage({
};
const saveReasoningSettings = useCallback(async () => {
+ const normalizedReasoningBase = (cloudReasoningBaseUrl || '').trim();
+ setCloudReasoningBaseUrl(normalizedReasoningBase);
+
// Update reasoning settings
updateReasoningSettings({
useReasoningModel,
- reasoningModel
+ reasoningModel,
+ cloudReasoningBaseUrl: normalizedReasoningBase
});
// Save API keys to backend based on provider
@@ -217,14 +226,19 @@ export default function SettingsPage({
// Save the provider separately since it's computed from the model
localStorage.setItem("reasoningProvider", localReasoningProvider);
+ const providerLabel =
+ localReasoningProvider === 'custom'
+ ? 'Custom'
+ : REASONING_PROVIDERS[
+ localReasoningProvider as keyof typeof REASONING_PROVIDERS
+ ]?.name || localReasoningProvider;
+
showAlertDialog({
title: "Reasoning Settings Saved",
description: `AI text enhancement ${
useReasoningModel ? "enabled" : "disabled"
} with ${
- REASONING_PROVIDERS[
- localReasoningProvider as keyof typeof REASONING_PROVIDERS
- ]?.name || localReasoningProvider
+ providerLabel
} ${reasoningModel}`,
});
}, [
@@ -794,12 +808,37 @@ export default function SettingsPage({
{!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>
+ <h4 className="font-medium text-blue-900">OpenAI-Compatible Cloud Setup</h4>
<ApiKeyInput
apiKey={openaiApiKey}
setApiKey={setOpenaiApiKey}
- helpText="Get your API key from platform.openai.com"
+ helpText="Supports OpenAI or compatible endpoints"
/>
+ <div className="space-y-2">
+ <label className="block text-sm font-medium text-blue-900">
+ Custom Base URL (optional)
+ </label>
+ <Input
+ value={cloudTranscriptionBaseUrl}
+ onChange={(event) => setCloudTranscriptionBaseUrl(event.target.value)}
+ placeholder="https://api.openai.com/v1"
+ className="text-sm"
+ />
+ <div className="flex items-center gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => setCloudTranscriptionBaseUrl(API_ENDPOINTS.TRANSCRIPTION_BASE)}
+ >
+ Reset to Default
+ </Button>
+ </div>
+ <p className="text-xs text-blue-800">
+ Requests for cloud transcription use this OpenAI-compatible base URL. Leave empty to fall back to
+ <code className="ml-1">{API_ENDPOINTS.TRANSCRIPTION_BASE}</code>.
+ </p>
+ </div>
</div>
)}
@@ -830,21 +869,33 @@ export default function SettingsPage({
<Button
onClick={() => {
+ const normalizedTranscriptionBase = (cloudTranscriptionBaseUrl || '').trim();
+ setCloudTranscriptionBaseUrl(normalizedTranscriptionBase);
+
updateTranscriptionSettings({
useLocalWhisper,
whisperModel,
preferredLanguage,
+ cloudTranscriptionBaseUrl: normalizedTranscriptionBase,
});
if (!useLocalWhisper && openaiApiKey.trim()) {
updateApiKeys({ openaiApiKey });
}
+ const descriptionParts = [
+ `Transcription mode: ${useLocalWhisper ? 'Local Whisper' : 'Cloud'}.`,
+ `Language: ${preferredLanguage}.`,
+ ];
+
+ if (!useLocalWhisper) {
+ const baseLabel = normalizedTranscriptionBase || API_ENDPOINTS.TRANSCRIPTION_BASE;
+ descriptionParts.push(`Endpoint: ${baseLabel}.`);
+ }
+
showAlertDialog({
title: "Settings Saved",
- description: `Transcription mode: ${
- useLocalWhisper ? "Local Whisper" : "OpenAI API"
- }. Language: ${preferredLanguage}.`,
+ description: descriptionParts.join(' '),
});
}}
className="w-full"
@@ -874,6 +925,8 @@ export default function SettingsPage({
setUseReasoningModel(value);
updateReasoningSettings({ useReasoningModel: value });
}}
+ setCloudReasoningBaseUrl={setCloudReasoningBaseUrl}
+ cloudReasoningBaseUrl={cloudReasoningBaseUrl}
reasoningModel={reasoningModel}
setReasoningModel={setReasoningModel}
localReasoningProvider={localReasoningProvider}
diff --git a/src/components/UnifiedModelPicker.tsx b/src/components/UnifiedModelPicker.tsx
index 62acbcc4a..788826033 100644
--- a/src/components/UnifiedModelPicker.tsx
+++ b/src/components/UnifiedModelPicker.tsx
@@ -7,7 +7,8 @@ import {
Download,
Trash2,
AlertCircle,
- ExternalLink
+ ExternalLink,
+ Globe
} from "lucide-react";
import { useDialogs } from "../hooks/useDialogs";
import { useToast } from "./ui/Toast";
@@ -107,7 +108,7 @@ export function UnifiedModelPickerCompact({
}: {
selectedModel: string;
onModelSelect: (modelId: string) => void;
- models: Array<{ value: string; label: string; description?: string }>;
+ models: Array<{ value: string; label: string; description?: string; icon?: string }>;
className?: string;
}) {
return (
@@ -124,7 +125,14 @@ export function UnifiedModelPickerCompact({
>
<div className="flex items-center justify-between">
<div>
- <div className="font-medium text-gray-900">{model.label}</div>
+ <div className="flex items-center gap-2">
+ {model.icon ? (
+ <img src={model.icon} alt="" className="w-4 h-4" aria-hidden="true" />
+ ) : (
+ <Globe className="w-4 h-4 text-gray-400" aria-hidden="true" />
+ )}
+ <span className="font-medium text-gray-900">{model.label}</span>
+ </div>
{model.description && (
<div className="text-xs text-gray-600 mt-1">{model.description}</div>
)}
diff --git a/src/components/ui/PromptStudio.tsx b/src/components/ui/PromptStudio.tsx
index 8e50ca597..442fb0601 100644
--- a/src/components/ui/PromptStudio.tsx
+++ b/src/components/ui/PromptStudio.tsx
@@ -24,6 +24,24 @@ interface PromptStudioProps {
}
+type ProviderConfig = {
+ label: string;
+ apiKeyStorageKey?: string;
+ baseStorageKey?: string;
+};
+
+const PROVIDER_CONFIG: Record<string, ProviderConfig> = {
+ openai: { label: "OpenAI", apiKeyStorageKey: "openaiApiKey" },
+ anthropic: { label: "Anthropic", apiKeyStorageKey: "anthropicApiKey" },
+ gemini: { label: "Gemini", apiKeyStorageKey: "geminiApiKey" },
+ custom: {
+ label: "Custom endpoint",
+ apiKeyStorageKey: "openaiApiKey",
+ baseStorageKey: "cloudReasoningBaseUrl",
+ },
+ local: { label: "Local" },
+};
+
export default function PromptStudio({ className = "" }: PromptStudioProps) {
const [activeTab, setActiveTab] = useState<"current" | "edit" | "test">("current");
const [editedAgentPrompt, setEditedAgentPrompt] = useState(DEFAULT_PROMPTS.agent);
@@ -90,18 +108,27 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
return;
}
- // Check if we have the required API key (only for cloud providers)
- if (reasoningProvider !== "local") {
- const apiKey = reasoningProvider === "openai"
- ? localStorage.getItem("openaiApiKey")
- : localStorage.getItem("anthropicApiKey");
-
+ const providerConfig = PROVIDER_CONFIG[reasoningProvider] || {
+ label: reasoningProvider.charAt(0).toUpperCase() + reasoningProvider.slice(1),
+ };
+ const providerLabel = providerConfig.label;
+
+ if (providerConfig.baseStorageKey) {
+ const baseUrl = (localStorage.getItem(providerConfig.baseStorageKey) || "").trim();
+ if (!baseUrl) {
+ setTestResult(`⚠️ ${providerLabel} base URL missing. Add it in AI Models settings.`);
+ return;
+ }
+ }
+
+ if (providerConfig.apiKeyStorageKey) {
+ const apiKey = localStorage.getItem(providerConfig.apiKeyStorageKey);
if (!apiKey || apiKey.trim() === "") {
- setTestResult(`⚠️ No ${reasoningProvider === "openai" ? "OpenAI" : "Anthropic"} API key found. Add it in AI Models settings.`);
+ setTestResult(`⚠️ No ${providerLabel} API key found. Add it in AI Models settings.`);
return;
}
}
-
+
// Save current prompts temporarily so the test uses them
const currentCustomPrompts = localStorage.getItem("customPrompts");
localStorage.setItem("customPrompts", JSON.stringify({
@@ -280,6 +307,13 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
const useReasoningModel = localStorage.getItem("useReasoningModel") === "true";
const reasoningModel = localStorage.getItem("reasoningModel") || "gpt-4o-mini";
const reasoningProvider = localStorage.getItem("reasoningProvider") || "openai";
+ const providerConfig = PROVIDER_CONFIG[reasoningProvider] || {
+ label: reasoningProvider.charAt(0).toUpperCase() + reasoningProvider.slice(1),
+ };
+ const providerLabel = providerConfig.label;
+ const providerEndpoint = providerConfig.baseStorageKey
+ ? (localStorage.getItem(providerConfig.baseStorageKey) || "").trim()
+ : "";
return (
<div className="space-y-6">
@@ -316,7 +350,12 @@ export default function PromptStudio({ className = "" }: PromptStudioProps) {
</div>
<div>
<span className="text-gray-600">Provider:</span>
- <span className="ml-2 font-medium capitalize">{reasoningProvider}</span>
+ <span className="ml-2 font-medium capitalize">{providerLabel}</span>
+ {providerConfig.baseStorageKey && (
+ <div className="text-xs text-gray-500 mt-1 break-all">
+ Endpoint: {providerEndpoint || "Not configured"}
+ </div>
+ )}
</div>
</div>
diff --git a/src/config/constants.ts b/src/config/constants.ts
index 76f5b4caa..68a00ad3d 100644
--- a/src/config/constants.ts
+++ b/src/config/constants.ts
@@ -1,8 +1,78 @@
-// API Configuration
+// API Configuration helpers
+export const normalizeBaseUrl = (value?: string | null): string => {
+ if (!value) return "";
+
+ let normalized = value.trim();
+ if (!normalized) return "";
+
+ // Remove common API endpoint suffixes to get the base URL
+ const suffixReplacements: Array<[RegExp, string]> = [
+ [/\/v1\/chat\/completions$/i, '/v1'],
+ [/\/chat\/completions$/i, ''],
+ [/\/v1\/responses$/i, '/v1'],
+ [/\/responses$/i, ''],
+ [/\/v1\/models$/i, '/v1'],
+ [/\/models$/i, ''],
+ [/\/v1\/audio\/transcriptions$/i, '/v1'],
+ [/\/audio\/transcriptions$/i, ''],
+ [/\/v1\/audio\/translations$/i, '/v1'],
+ [/\/audio\/translations$/i, ''],
+ ];
+
+ for (const [pattern, replacement] of suffixReplacements) {
+ if (pattern.test(normalized)) {
+ normalized = normalized.replace(pattern, replacement).replace(/\/+$/, "");
+ }
+ }
+
+ return normalized.replace(/\/+$/, "");
+};
+
+export const buildApiUrl = (base: string, path: string): string => {
+ const normalizedBase = normalizeBaseUrl(base) || "https://api.openai.com/v1";
+ if (!path) {
+ return normalizedBase;
+ }
+ const normalizedPath = path.startsWith('/') ? path : `/${path}`;
+ return `${normalizedBase}${normalizedPath}`;
+};
+
+const env = (typeof import.meta !== "undefined" && (import.meta as any).env) || {};
+
+const computeBaseUrl = (candidates: Array<string | undefined>, fallback: string): string => {
+ for (const candidate of candidates) {
+ const normalized = normalizeBaseUrl(candidate);
+ if (normalized) {
+ return normalized;
+ }
+ }
+ return fallback;
+};
+
+const DEFAULT_OPENAI_BASE = computeBaseUrl(
+ [
+ env.OPENWHISPR_OPENAI_BASE_URL as string | undefined,
+ env.OPENAI_BASE_URL as string | undefined,
+ ],
+ 'https://api.openai.com/v1'
+);
+
+const DEFAULT_TRANSCRIPTION_BASE = computeBaseUrl(
+ [
+ env.OPENWHISPR_TRANSCRIPTION_BASE_URL as string | undefined,
+ env.WHISPER_BASE_URL as string | undefined,
+ ],
+ DEFAULT_OPENAI_BASE
+);
+
export const API_ENDPOINTS = {
- OPENAI: 'https://api.openai.com/v1/responses',
+ OPENAI_BASE: DEFAULT_OPENAI_BASE,
+ OPENAI: buildApiUrl(DEFAULT_OPENAI_BASE, '/responses'),
+ OPENAI_MODELS: buildApiUrl(DEFAULT_OPENAI_BASE, '/models'),
ANTHROPIC: 'https://api.anthropic.com/v1/messages',
GEMINI: 'https://generativelanguage.googleapis.com/v1beta',
+ TRANSCRIPTION_BASE: DEFAULT_TRANSCRIPTION_BASE,
+ TRANSCRIPTION: buildApiUrl(DEFAULT_TRANSCRIPTION_BASE, '/audio/transcriptions'),
} as const;
export const API_VERSIONS = {
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index be8dbf88f..cb6cb9047 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -1,5 +1,6 @@
-import TextCleanup from "../utils/textCleanup";
+import TextCleanup from "../utils/textCleanup";
import ReasoningService from "../services/ReasoningService";
+import { API_ENDPOINTS, buildApiUrl, normalizeBaseUrl } from "../config/constants";
// Debug logger for renderer process
const debugLogger = {
@@ -544,7 +545,7 @@ class AudioManager {
}
const response = await fetch(
- "https://api.openai.com/v1/audio/transcriptions",
+ this.getTranscriptionEndpoint(),
{
method: "POST",
headers: {
@@ -612,6 +613,30 @@ class AudioManager {
}
}
+ getTranscriptionEndpoint() {
+ try {
+ const stored = typeof localStorage !== "undefined"
+ ? localStorage.getItem("cloudTranscriptionBaseUrl") || ""
+ : "";
+ const trimmed = stored.trim();
+ const base = trimmed ? trimmed : API_ENDPOINTS.TRANSCRIPTION_BASE;
+ const normalizedBase = normalizeBaseUrl(base);
+
+ if (!normalizedBase) {
+ return API_ENDPOINTS.TRANSCRIPTION;
+ }
+
+ if (/\/audio\/(transcriptions|translations)$/i.test(normalizedBase)) {
+ return normalizedBase;
+ }
+
+ return buildApiUrl(normalizedBase, '/audio/transcriptions');
+ } catch (error) {
+ console.warn('Failed to resolve transcription endpoint:', error);
+ return API_ENDPOINTS.TRANSCRIPTION;
+ }
+ }
+
async safePaste(text) {
try {
await window.electronAPI.pasteText(text);
diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.ts
index 541a157e8..374501f5c 100644
--- a/src/hooks/useSettings.ts
+++ b/src/hooks/useSettings.ts
@@ -1,6 +1,7 @@
import { useCallback } from "react";
import { useLocalStorage } from "./useLocalStorage";
import { getModelProvider } from "../utils/languages";
+import { API_ENDPOINTS } from "../config/constants";
export interface TranscriptionSettings {
useLocalWhisper: boolean;
@@ -9,12 +10,14 @@ export interface TranscriptionSettings {
allowLocalFallback: boolean;
fallbackWhisperModel: string;
preferredLanguage: string;
+ cloudTranscriptionBaseUrl?: string;
}
export interface ReasoningSettings {
useReasoningModel: boolean;
reasoningModel: string;
reasoningProvider: string;
+ cloudReasoningBaseUrl?: string;
}
export interface HotkeySettings {
@@ -82,6 +85,24 @@ export function useSettings() {
}
);
+ const [cloudTranscriptionBaseUrl, setCloudTranscriptionBaseUrl] = useLocalStorage(
+ "cloudTranscriptionBaseUrl",
+ API_ENDPOINTS.TRANSCRIPTION_BASE,
+ {
+ serialize: String,
+ deserialize: String,
+ }
+ );
+
+ const [cloudReasoningBaseUrl, setCloudReasoningBaseUrl] = useLocalStorage(
+ "cloudReasoningBaseUrl",
+ API_ENDPOINTS.OPENAI_BASE,
+ {
+ serialize: String,
+ deserialize: String,
+ }
+ );
+
// Reasoning settings
const [useReasoningModel, setUseReasoningModel] = useLocalStorage(
"useReasoningModel",
@@ -149,6 +170,8 @@ export function useSettings() {
setFallbackWhisperModel(settings.fallbackWhisperModel);
if (settings.preferredLanguage !== undefined)
setPreferredLanguage(settings.preferredLanguage);
+ if (settings.cloudTranscriptionBaseUrl !== undefined)
+ setCloudTranscriptionBaseUrl(settings.cloudTranscriptionBaseUrl);
},
[
setUseLocalWhisper,
@@ -157,6 +180,7 @@ export function useSettings() {
setAllowLocalFallback,
setFallbackWhisperModel,
setPreferredLanguage,
+ setCloudTranscriptionBaseUrl,
]
);
@@ -166,9 +190,11 @@ export function useSettings() {
setUseReasoningModel(settings.useReasoningModel);
if (settings.reasoningModel !== undefined)
setReasoningModel(settings.reasoningModel);
+ if (settings.cloudReasoningBaseUrl !== undefined)
+ setCloudReasoningBaseUrl(settings.cloudReasoningBaseUrl);
// reasoningProvider is computed from reasoningModel, not stored separately
},
- [setUseReasoningModel, setReasoningModel]
+ [setUseReasoningModel, setReasoningModel, setCloudReasoningBaseUrl]
);
const updateApiKeys = useCallback(
@@ -189,6 +215,8 @@ export function useSettings() {
allowLocalFallback,
fallbackWhisperModel,
preferredLanguage,
+ cloudTranscriptionBaseUrl,
+ cloudReasoningBaseUrl,
useReasoningModel,
reasoningModel,
reasoningProvider,
@@ -202,9 +230,15 @@ export function useSettings() {
setAllowLocalFallback,
setFallbackWhisperModel,
setPreferredLanguage,
+ setCloudTranscriptionBaseUrl,
+ setCloudReasoningBaseUrl,
setUseReasoningModel,
setReasoningModel,
setReasoningProvider: (provider: string) => {
+ if (provider === 'custom') {
+ return;
+ }
+
const providerModels = {
openai: "gpt-4o-mini", // Start with cost-efficient multimodal model
anthropic: "claude-3.5-sonnet-20241022",
diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.ts
index 5db905267..c67355e6b 100644
--- a/src/services/ReasoningService.ts
+++ b/src/services/ReasoningService.ts
@@ -1,8 +1,8 @@
-import { getModelProvider } from "../utils/languages";
+import { getModelProvider } from "../utils/languages";
import { BaseReasoningService, ReasoningConfig } from "./BaseReasoningService";
import { SecureCache } from "../utils/SecureCache";
import { withRetry, createApiRetryStrategy } from "../utils/retry";
-import { API_ENDPOINTS, API_VERSIONS, TOKEN_LIMITS } from "../config/constants";
+import { API_ENDPOINTS, API_VERSIONS, TOKEN_LIMITS, buildApiUrl, normalizeBaseUrl } from "../config/constants";
// Import debugLogger for comprehensive logging
const debugLogger = typeof window !== 'undefined' && window.electronAPI
@@ -28,6 +28,44 @@ class ReasoningService extends BaseReasoningService {
this.cacheCleanupStop = this.apiKeyCache.startAutoCleanup();
}
+ private getConfiguredOpenAIBase(): string {
+ if (typeof window === 'undefined' || !window.localStorage) {
+ return API_ENDPOINTS.OPENAI_BASE;
+ }
+
+ try {
+ const stored = window.localStorage.getItem('cloudReasoningBaseUrl') || '';
+ const trimmed = stored.trim();
+ const candidate = trimmed || API_ENDPOINTS.OPENAI_BASE;
+ return normalizeBaseUrl(candidate) || API_ENDPOINTS.OPENAI_BASE;
+ } catch {
+ return API_ENDPOINTS.OPENAI_BASE;
+ }
+ }
+
+ private getOpenAIEndpointCandidates(): string[] {
+ const base = this.getConfiguredOpenAIBase();
+ const lower = base.toLowerCase();
+
+ if (lower.endsWith('/responses') || lower.endsWith('/chat/completions')) {
+ return [base];
+ }
+
+ return [
+ buildApiUrl(base, '/responses'),
+ buildApiUrl(base, '/chat/completions'),
+ ];
+ }
+
+ private getOpenAIModelsEndpoint(): string {
+ const base = this.getConfiguredOpenAIBase();
+ const lower = base.toLowerCase();
+ if (lower.endsWith('/models')) {
+ return base;
+ }
+ return buildApiUrl(base, '/models');
+ }
+
private async getApiKey(provider: 'openai' | 'anthropic' | 'gemini'): Promise<string> {
let apiKey = this.apiKeyCache.get(provider);
@@ -192,23 +230,62 @@ class ReasoningService extends BaseReasoningService {
requestBody.temperature = config.temperature || 0.3;
}
+ const endpointCandidates = this.getOpenAIEndpointCandidates();
+
+ debugLogger.logReasoning("OPENAI_ENDPOINTS", {
+ base: this.getConfiguredOpenAIBase(),
+ candidates: endpointCandidates,
+ });
+
const response = await withRetry(
async () => {
- const res = await fetch(API_ENDPOINTS.OPENAI, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${apiKey}`,
- },
- body: JSON.stringify(requestBody),
- });
-
- if (!res.ok) {
- const errorData = await res.json().catch(() => ({ error: res.statusText }));
- throw new Error(errorData.error?.message || `OpenAI API error: ${res.status}`);
+ let lastError: Error | null = null;
+
+ for (const endpoint of endpointCandidates) {
+ try {
+ const res = await fetch(endpoint, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${apiKey}`,
+ },
+ body: JSON.stringify(requestBody),
+ });
+
+ if (!res.ok) {
+ const errorData = await res.json().catch(() => ({ error: res.statusText }));
+ const errorMessage =
+ errorData.error?.message ||
+ errorData.message ||
+ `OpenAI API error: ${res.status}`;
+
+ const isUnsupportedEndpoint =
+ (res.status === 404 || res.status === 405) &&
+ endpoint.toLowerCase().endsWith('/responses');
+
+ if (isUnsupportedEndpoint) {
+ lastError = new Error(errorMessage);
+ continue;
+ }
+
+ throw new Error(errorMessage);
+ }
+
+ return res.json();
+ } catch (error) {
+ lastError = error as Error;
+ if (endpoint.toLowerCase().endsWith('/responses')) {
+ debugLogger.logReasoning('OPENAI_ENDPOINT_FALLBACK', {
+ attemptedEndpoint: endpoint,
+ error: (error as Error).message,
+ });
+ continue;
+ }
+ throw error;
+ }
}
- return res.json();
+ throw lastError || new Error('No OpenAI endpoint responded');
},
createApiRetryStrategy("OpenAI")
);