Skip to content

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

fix(llm): fail-closed LLM routing — custom-endpoint leaks, key pairing, model memory, secure scope keys (#1583)

Gabriel Steinbeedfd32fce9
diff --git a/preload.js b/preload.js
index 07352f331..ca4a18a48 100644
--- a/preload.js
+++ b/preload.js
@@ -14,6 +14,23 @@ const BYOK_KEY_BRIDGES = [
{ base: "openrouter", get: "getOpenrouterKey", save: "saveOpenrouterKey" },
{ base: "tinfoil", get: "getTinfoilKey", save: "saveTinfoilKey" },
{ base: "corti", get: "getCortiKey", save: "saveCortiKey" },
+ {
+ base: "note-formatting-custom",
+ get: "getNoteFormattingCustomKey",
+ save: "saveNoteFormattingCustomKey",
+ },
+ { base: "translation-custom", get: "getTranslationCustomKey", save: "saveTranslationCustomKey" },
+ {
+ base: "dictation-agent-custom",
+ get: "getDictationAgentCustomKey",
+ save: "saveDictationAgentCustomKey",
+ },
+ {
+ base: "dictation-agent-vision-custom",
+ get: "getDictationAgentVisionCustomKey",
+ save: "saveDictationAgentVisionCustomKey",
+ },
+ { base: "chat-agent-custom", get: "getChatAgentCustomKey", save: "saveChatAgentCustomKey" },
];
const secretKeyApi = {};
for (const k of BYOK_KEY_BRIDGES) {
diff --git a/src/components/CleanupFailureToastListener.tsx b/src/components/CleanupFailureToastListener.tsx
index 32d0d8f0e..2cdd80cb6 100644
--- a/src/components/CleanupFailureToastListener.tsx
+++ b/src/components/CleanupFailureToastListener.tsx
@@ -13,15 +13,17 @@ export default function CleanupFailureToastListener() {
useEffect(() => {
if (pending === 0) return;
+ const cause = useCleanupFailureStore.getState().lastMessage;
// Draining first keeps a re-run of this effect from toasting the same failure twice.
if (consumeCleanupFailures() === 0) return;
// The panel may already be hidden after dictation; surface it so the toast is seen.
if (isDictationPanelWindow()) {
window.electronAPI?.showDictationPanel?.();
}
+ const description = t("app.toasts.cleanupFailed.description");
toast({
title: t("app.toasts.cleanupFailed.title"),
- description: t("app.toasts.cleanupFailed.description"),
+ description: cause ? `${description} ${cause}` : description,
duration: 10000,
});
}, [pending, toast, t]);
diff --git a/src/components/ReasoningModelSelector.tsx b/src/components/ReasoningModelSelector.tsx
index 66f1a8a60..9772ed60f 100644
--- a/src/components/ReasoningModelSelector.tsx
+++ b/src/components/ReasoningModelSelector.tsx
@@ -67,6 +67,11 @@ interface ReasoningModelSelectorProps {
setCustomReasoningApiKey?: (key: string) => void;
setReasoningMode?: (mode: InferenceMode) => void;
mode?: "cloud" | "local";
+ /**
+ * Scope-aware provider switch (switchReasoningProvider) with per-provider
+ * model memory; receives the provider default for when nothing is remembered.
+ */
+ onCloudProviderSelect?: (provider: string, fallbackModel: string) => void;
}
function GpuStatusBadge() {
@@ -331,6 +336,7 @@ export default function ReasoningModelSelector({
setCustomReasoningApiKey,
setReasoningMode: setReasoningModeProp,
mode,
+ onCloudProviderSelect,
}: ReasoningModelSelectorProps) {
const { t } = useTranslation();
const openaiApiKey = useSettingsStore((s) => s.openaiApiKey);
@@ -475,27 +481,31 @@ export default function ReasoningModelSelector({
return new Set<string>();
}, []);
- const selectDefaultModelForProvider = useCallback(
- (provider: string) => {
+ const defaultModelForProvider = useCallback(
+ (provider: string): string => {
// Custom/OpenRouter fetch their model list dynamically — clear instead of
// presetting so another provider's model id can't persist under this one.
- if (provider === "custom" || provider === OPENROUTER_TAB) {
- setReasoningModel("");
- return;
- }
+ if (provider === "custom" || provider === OPENROUTER_TAB) return "";
+ if (provider === "tinfoil") return pickDefaultTinfoilModel(tinfoilModels)?.id ?? "";
+ const providerData = REASONING_PROVIDERS[provider as keyof typeof REASONING_PROVIDERS];
+ return providerData?.models?.[0]?.value ?? "";
+ },
+ [tinfoilModels]
+ );
- if (provider === "tinfoil") {
- const defaultModel = pickDefaultTinfoilModel(tinfoilModels);
- if (defaultModel) setReasoningModel(defaultModel.id);
+ const applyCloudProvider = useCallback(
+ (provider: string) => {
+ const fallbackModel = defaultModelForProvider(provider);
+ if (onCloudProviderSelect) {
+ onCloudProviderSelect(provider, fallbackModel);
return;
}
-
- const providerData = REASONING_PROVIDERS[provider as keyof typeof REASONING_PROVIDERS];
- if (providerData?.models?.length > 0) {
- setReasoningModel(providerData.models[0].value);
- }
+ setLocalReasoningProvider(provider);
+ // Tinfoil's catalog may still be loading — keep the current model until it lands.
+ if (provider === "tinfoil" && !fallbackModel) return;
+ setReasoningModel(fallbackModel);
},
- [setReasoningModel, tinfoilModels]
+ [defaultModelForProvider, onCloudProviderSelect, setLocalReasoningProvider, setReasoningModel]
);
const handleModeChange = async (newMode: "cloud" | "local") => {
@@ -514,8 +524,7 @@ export default function ReasoningModelSelector({
: cloudProviders[0]?.id;
if (!nextProvider) return;
if (nextProvider !== displayedCloudProvider) setSelectedCloudProvider(nextProvider);
- setLocalReasoningProvider(nextProvider);
- selectDefaultModelForProvider(nextProvider);
+ applyCloudProvider(nextProvider);
} else {
setLocalReasoningProvider(selectedLocalProvider);
const downloaded = await loadDownloadedModels();
@@ -536,10 +545,9 @@ export default function ReasoningModelSelector({
(provider: string) => {
if (!providerAllowed(provider)) return;
setSelectedCloudProvider(provider);
- setLocalReasoningProvider(provider);
- selectDefaultModelForProvider(provider);
+ applyCloudProvider(provider);
},
- [providerAllowed, selectDefaultModelForProvider, setLocalReasoningProvider]
+ [providerAllowed, applyCloudProvider]
);
const handleLocalProviderChange = async (providerId: string) => {
diff --git a/src/components/notes/NotesOnboarding.tsx b/src/components/notes/NotesOnboarding.tsx
index 9bd670546..af689f085 100644
--- a/src/components/notes/NotesOnboarding.tsx
+++ b/src/components/notes/NotesOnboarding.tsx
@@ -51,6 +51,13 @@ export default function NotesOnboarding({ onComplete }: NotesOnboardingProps) {
);
const setCleanupModel = useSettingsStore((s) => s.setCleanupModel);
const setCleanupProvider = useSettingsStore((s) => s.setCleanupProvider);
+ const switchCleanupProvider = useCallback(
+ (provider: string, fallbackModel: string) =>
+ useSettingsStore
+ .getState()
+ .switchReasoningProvider("dictationCleanup", provider, fallbackModel),
+ []
+ );
const setCleanupMode = useSettingsStore((s) => s.setCleanupMode);
const setCleanupCloudBaseUrl = useSettingsStore((s) => s.setCleanupCloudBaseUrl);
const setCleanupCustomApiKey = useSettingsStore((s) => s.setCleanupCustomApiKey);
@@ -174,6 +181,7 @@ export default function NotesOnboarding({ onComplete }: NotesOnboardingProps) {
setReasoningModel={setCleanupModel}
localReasoningProvider={cleanupConfig.provider}
setLocalReasoningProvider={setCleanupProvider}
+ onCloudProviderSelect={switchCleanupProvider}
cloudReasoningBaseUrl={cleanupConfig.cloudBaseUrl ?? ""}
setCloudReasoningBaseUrl={setCleanupCloudBaseUrl}
customReasoningApiKey={cleanupConfig.customApiKey ?? ""}
diff --git a/src/components/settings/InferenceConfigEditor.tsx b/src/components/settings/InferenceConfigEditor.tsx
index 1a93a30e1..330d527d7 100644
--- a/src/components/settings/InferenceConfigEditor.tsx
+++ b/src/components/settings/InferenceConfigEditor.tsx
@@ -157,12 +157,19 @@ export default function InferenceConfigEditor({
const setProvider = setField("provider");
const setModel = setField("model");
+ const switchCloudProvider = useCallback(
+ (provider: string, fallbackModel: string) =>
+ useSettingsStore.getState().switchReasoningProvider(scope, provider, fallbackModel),
+ [scope]
+ );
+
const renderModelSelector = (mode?: "cloud" | "local") => (
<ReasoningModelSelector
reasoningModel={config.model}
setReasoningModel={setModel}
localReasoningProvider={config.provider}
setLocalReasoningProvider={setProvider}
+ onCloudProviderSelect={switchCloudProvider}
cloudReasoningBaseUrl={config.cloudBaseUrl ?? ""}
setCloudReasoningBaseUrl={setField("cloudBaseUrl")}
customReasoningApiKey={config.customApiKey ?? ""}
diff --git a/src/components/ui/PromptStudio.tsx b/src/components/ui/PromptStudio.tsx
index 83f46bea2..53348ba12 100644
--- a/src/components/ui/PromptStudio.tsx
+++ b/src/components/ui/PromptStudio.tsx
@@ -228,9 +228,7 @@ export default function PromptStudio({ className = "", kind = "cleanup" }: Promp
const cleanupProvider = isCloudMode
? "openwhispr"
- : cleanupModel
- ? getModelProvider(cleanupModel)
- : "openai";
+ : (cleanupModel && getModelProvider(cleanupModel)) || "openai";
logger.debug(
"PromptStudio test starting",
@@ -479,7 +477,7 @@ export default function PromptStudio({ className = "", kind = "cleanup" }: Promp
? scopeProvider
: testIsCloud
? "openwhispr"
- : scopeProvider || (testModel ? getModelProvider(testModel) : "openai");
+ : scopeProvider || (testModel && getModelProvider(testModel)) || "openai";
const providerConfig = PROVIDER_CONFIG[testProvider] || {
label: testProvider.charAt(0).toUpperCase() + testProvider.slice(1),
};
diff --git a/src/config/secretKeys.js b/src/config/secretKeys.js
index 115d5ed6d..db548828c 100644
--- a/src/config/secretKeys.js
+++ b/src/config/secretKeys.js
@@ -64,6 +64,43 @@ const BYOK_API_KEYS = [
save: "saveCortiKey",
storeKey: "cortiApiKey",
},
+ // Per-scope Custom-endpoint keys. Dictation cleanup's counterpart predates
+ // this manifest and keeps its bespoke accessors (CUSTOM_CLEANUP_API_KEY).
+ {
+ base: "note-formatting-custom",
+ env: "NOTE_FORMATTING_CUSTOM_API_KEY",
+ get: "getNoteFormattingCustomKey",
+ save: "saveNoteFormattingCustomKey",
+ storeKey: "noteFormattingCustomApiKey",
+ },
+ {
+ base: "translation-custom",
+ env: "TRANSLATION_CUSTOM_API_KEY",
+ get: "getTranslationCustomKey",
+ save: "saveTranslationCustomKey",
+ storeKey: "translationCustomApiKey",
+ },
+ {
+ base: "dictation-agent-custom",
+ env: "DICTATION_AGENT_CUSTOM_API_KEY",
+ get: "getDictationAgentCustomKey",
+ save: "saveDictationAgentCustomKey",
+ storeKey: "dictationAgentCustomApiKey",
+ },
+ {
+ base: "dictation-agent-vision-custom",
+ env: "DICTATION_AGENT_VISION_CUSTOM_API_KEY",
+ get: "getDictationAgentVisionCustomKey",
+ save: "saveDictationAgentVisionCustomKey",
+ storeKey: "dictationAgentVisionCustomApiKey",
+ },
+ {
+ base: "chat-agent-custom",
+ env: "CHAT_AGENT_CUSTOM_API_KEY",
+ get: "getChatAgentCustomKey",
+ save: "saveChatAgentCustomKey",
+ storeKey: "chatAgentCustomApiKey",
+ },
];
module.exports = { BYOK_API_KEYS };
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index 2bd106eb3..bcf47522d 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -2605,7 +2605,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
fallbackToCleanup: true,
});
logger.warn("Reasoning failed", { source, error: error.message }, "notes");
- if (route?.kind === "cleanup") recordCleanupFailure();
+ if (route?.kind === "cleanup") recordCleanupFailure(error.message);
if (route?.kind === "agent") this._notifyAgentReasoningFailed();
}
}
@@ -2929,7 +2929,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
{ error: reasonError.message },
"transcription"
);
- if (route.kind === "cleanup") recordCleanupFailure();
+ if (route.kind === "cleanup") recordCleanupFailure(reasonError.message);
if (route.kind === "agent") this._notifyAgentReasoningFailed();
}
timings.reasoningProcessingDurationMs = Math.round(performance.now() - reasoningStart);
@@ -4340,7 +4340,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
{ error: reasonError.message },
"streaming"
);
- if (route.kind === "cleanup") recordCleanupFailure();
+ if (route.kind === "cleanup") recordCleanupFailure(reasonError.message);
if (route.kind === "agent") this._notifyAgentReasoningFailed();
}
}
diff --git a/src/helpers/dictationAgentInference.js b/src/helpers/dictationAgentInference.js
index 0aedc3f38..4bf50f93c 100644
--- a/src/helpers/dictationAgentInference.js
+++ b/src/helpers/dictationAgentInference.js
@@ -8,6 +8,7 @@ import {
import { isProviderValidForMode } from "../models/ModelRegistry";
import { getManagedScopeResolution } from "../stores/enterpriseIdentityStore";
import { selectResolvedLLMConfig } from "../stores/settingsStore";
+import { inheritsFallbackEndpoint } from "./reasoningRouting.js";
// The dictation agent's inference scope, shared by the dictation route in
// audioManager and the Prompt Studio test tab so a prompt test hits the same
@@ -89,6 +90,17 @@ export function resolveDictationAgentVisionInference(settings, { isSignedIn = fa
// otherwise the user must have picked a model for this scope specifically.
const chosen = isCloud || !!settings.dictationAgentVisionModel?.trim();
+ // The endpoint falls back to the agent scope, so the key that opens it must
+ // too — an inherited endpoint with only the vision key (or none) would call
+ // the agent's host with the wrong credential.
+ const agent = selectResolvedLLMConfig(settings, "dictationAgent");
+ const borrowsAgentEndpoint = inheritsFallbackEndpoint(
+ { mode, cloudBaseUrl: settings.dictationAgentVisionCloudBaseUrl },
+ agent.mode
+ );
+ const customApiKey =
+ resolved.customApiKey || (borrowsAgentEndpoint ? agent.customApiKey || "" : "");
+
return {
active:
!!settings.useDictationAgentVisionModel &&
@@ -97,9 +109,12 @@ export function resolveDictationAgentVisionInference(settings, { isSignedIn = fa
// Cloud picks the model server-side from its vision chain.
model: isCloud ? "" : model,
config: {
+ // The vision override is the agent's image lane: policy and managed
+ // enforcement must judge it as the agent scope, not dictation cleanup.
+ inferenceScope: /** @type {const} */ ("dictationAgent"),
provider,
baseUrl: isCustom ? resolved.cloudBaseUrl || undefined : undefined,
- customApiKey: isCustom ? resolved.customApiKey || undefined : undefined,
+ customApiKey: isCustom ? customApiKey || undefined : undefined,
disableThinking: resolved.disableThinking,
},
};
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index c772955e3..ead3862eb 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -450,6 +450,7 @@
"custom": {
"endpointWithProtocol": "Geben Sie eine vollständige Basis-URL mit Protokoll ein (z. B. https://server/v1).",
"httpsRequired": "HTTPS erforderlich (HTTP nur im lokalen Netzwerk erlaubt).",
+ "endpointInvalid": "Der benutzerdefinierte Endpunkt ist ungültig oder nicht konfiguriert. Prüfe die Endpunkt-URL unter Einstellungen → KI-Modelle.",
"endpointUnauthorized": "Der Endpoint hat die Anfrage abgelehnt (401/403). Fügen Sie einen API-Schlüssel hinzu oder passen Sie die Server-Authentifizierung an.",
"endpointTitle": "Endpoint-URL",
"endpointExamples": "Beispiele:",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index bbe0984f6..4a11df925 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -450,6 +450,7 @@
"custom": {
"endpointWithProtocol": "Enter a full base URL including protocol (for example, https://server/v1).",
"httpsRequired": "HTTPS required (HTTP allowed for local network only).",
+ "endpointInvalid": "Custom endpoint is invalid or not configured. Check the endpoint URL in Settings → AI Models.",
"endpointUnauthorized": "Endpoint rejected the request (401/403). Add an API key or adjust server auth settings.",
"endpointTitle": "Endpoint URL",
"endpointExamples": "Examples:",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index bfd5fc376..33387bfbc 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -450,6 +450,7 @@
"custom": {
"endpointWithProtocol": "Introduce una URL base completa con protocolo (por ejemplo, https://server/v1).",
"httpsRequired": "Se requiere HTTPS (HTTP solo para red local).",
+ "endpointInvalid": "El endpoint personalizado no es válido o no está configurado. Revisa la URL del endpoint en Ajustes → Modelos de IA.",
"endpointUnauthorized": "El endpoint rechazó la solicitud (401/403). Agrega una clave API o ajusta la autenticación del servidor.",
"endpointTitle": "URL del endpoint",
"endpointExamples": "Ejemplos:",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index 851d8255b..cb2f9ca9a 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -450,6 +450,7 @@
"custom": {
"endpointWithProtocol": "Saisissez une URL de base complète avec protocole (ex : https://server/v1).",
"httpsRequired": "HTTPS requis (HTTP autorisé seulement en réseau local).",
+ "endpointInvalid": "Le point de terminaison personnalisé est invalide ou non configuré. Vérifiez l'URL du point de terminaison dans Réglages → Modèles d'IA.",
"endpointUnauthorized": "Le endpoint a rejeté la requête (401/403). Ajoutez une clé API ou ajustez l'authentification du serveur.",
"endpointTitle": "URL du endpoint",
"endpointExamples": "Exemples :",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index cd37cebff..ef3055e2a 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -450,6 +450,7 @@
"custom": {
"endpointWithProtocol": "Inserisci un URL base completo di protocollo (ad esempio, https://server/v1).",
"httpsRequired": "HTTPS richiesto (HTTP consentito solo in rete locale).",
+ "endpointInvalid": "L'endpoint personalizzato non è valido o non è configurato. Controlla l'URL dell'endpoint in Impostazioni → Modelli IA.",
"endpointUnauthorized": "L'endpoint ha rifiutato la richiesta (401/403). Aggiungi una chiave API o modifica le impostazioni di autenticazione del server.",
"endpointTitle": "URL endpoint",
"endpointExamples": "Esempi:",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 60c2820ab..71cf64107 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -450,6 +450,7 @@
"custom": {
"endpointWithProtocol": "プロトコルを含む完全なベース URL を入力してください(例: https://server/v1)。",
"httpsRequired": "HTTPS が必要です(ローカルネットワークのみ HTTP を許可)。",
+ "endpointInvalid": "カスタムエンドポイントが無効か未設定です。設定 → AIモデルでエンドポイントURLを確認してください。",
"endpointUnauthorized": "エンドポイントがリクエストを拒否しました(401/403)。API キーを追加するか、サーバーの認証設定を調整してください。",
"endpointTitle": "エンドポイント URL",
"endpointExamples": "例:",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index c9b8e111a..b6a2b0bc6 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -429,6 +429,7 @@
"custom": {
"endpointWithProtocol": "Informe uma URL base completa com protocolo (por exemplo, https://server/v1).",
"httpsRequired": "HTTPS obrigatório (HTTP permitido apenas em rede local).",
+ "endpointInvalid": "O endpoint personalizado é inválido ou não está configurado. Verifique o URL do endpoint em Configurações → Modelos de IA.",
"endpointUnauthorized": "O endpoint rejeitou a requisição (401/403). Adicione uma chave API ou ajuste a autenticação do servidor.",
"endpointTitle": "URL do endpoint",
"endpointExamples": "Exemplos:",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 918c8a6eb..66cd36c24 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -450,6 +450,7 @@
"custom": {
"endpointWithProtocol": "Введите полный базовый URL, включая протокол (например, https://server/v1).",
"httpsRequired": "Требуется HTTPS (HTTP допускается только для локальной сети).",
+ "endpointInvalid": "Пользовательская конечная точка недействительна или не настроена. Проверьте URL конечной точки в Настройках → Модели ИИ.",
"endpointUnauthorized": "Конечная точка отклонила запрос (401/403). Добавьте API-ключ или измените настройки авторизации сервера.",
"endpointTitle": "URL конечной точки",
"endpointExamples": "Примеры:",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index aa8452b61..d82a3aaa8 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -450,6 +450,7 @@
"custom": {
"endpointWithProtocol": "请输入包含协议的完整 URL(例如 https://server/v1)。",
"httpsRequired": "需要 HTTPS(仅本地网络允许 HTTP)。",
+ "endpointInvalid": "自定义端点无效或未配置。请在设置 → AI 模型中检查端点 URL。",
"endpointUnauthorized": "端点拒绝了请求(401/403)。请添加 API Key 或调整服务器认证设置。",
"endpointTitle": "端点 URL",
"endpointExamples": "示例:",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index dc7889772..ae51d1874 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -450,6 +450,7 @@
"custom": {
"endpointWithProtocol": "請輸入包含通訊協定的完整 URL(例如 https://server/v1)。",
"httpsRequired": "需使用 HTTPS(僅限本機網路可使用 HTTP)。",
+ "endpointInvalid": "自訂端點無效或未設定。請在設定 → AI 模型中檢查端點 URL。",
"endpointUnauthorized": "端點拒絕了請求(401/403)。請新增 API Key 或調整伺服器驗證設定。",
"endpointTitle": "端點 URL",
"endpointExamples": "範例:",
diff --git a/src/models/ModelRegistry.ts b/src/models/ModelRegistry.ts
index 6f6c571e3..57bc884c5 100644
--- a/src/models/ModelRegistry.ts
+++ b/src/models/ModelRegistry.ts
@@ -407,7 +407,9 @@ export function getModelProvider(modelId: string): string {
return "local";
}
- return model?.provider || "openai";
+ // No default: an unrecognized model must fail closed at dispatch instead of
+ // being routed to OpenAI with whatever key that attaches.
+ return model?.provider || "";
}
// Local catalog IDs group models for selection and downloads, but all execute
diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.ts
index 97d4c2529..774004a61 100644
--- a/src/services/ReasoningService.ts
+++ b/src/services/ReasoningService.ts
@@ -20,7 +20,11 @@ import { createEnterpriseChatModel } from "./ai/enterpriseChatModel";
import { getManagedScopeResolution } from "../stores/enterpriseIdentityStore";
import type { InferenceScope } from "../config/inferenceScopes";
import { PROVIDER_REGISTRY, type ProviderContext } from "./ai/inferenceProviders";
-import { resolveConfiguredOpenAIBase, resolveSelfHostedOpenAIBase } from "./ai/openaiBase";
+import {
+ canBorrowCleanupCustomKey,
+ resolveConfiguredOpenAIBase,
+ resolveSelfHostedOpenAIBase,
+} from "./ai/openaiBase";
import { applyThinkingSuppression } from "./ai/thinkingSuppression";
import { detectEndpointDialect } from "./ai/thinkingSuppressionDialects";
import { extractApiErrorMessage } from "./ai/apiErrorMessage";
@@ -37,6 +41,26 @@ interface ToolExecutionResult {
metadata?: ToolMetadata;
}
+const BYOK_STREAM_PROVIDERS = [
+ "openai",
+ "groq",
+ "gemini",
+ "anthropic",
+ "tinfoil",
+ "custom",
+ "openrouter",
+ "corti",
+] as const;
+
+type ByokStreamProvider = (typeof BYOK_STREAM_PROVIDERS)[number];
+
+function toByokStreamProvider(provider: string): ByokStreamProvider {
+ if (!(BYOK_STREAM_PROVIDERS as readonly string[]).includes(provider)) {
+ throw new Error(`Unsupported reasoning provider: ${provider}`);
+ }
+ return provider as ByokStreamProvider;
+}
+
export type AgentStreamChunk =
| { type: "content"; text: string }
| { type: "tool_calls"; calls: Array<{ id: string; name: string; arguments: string }> }
@@ -223,6 +247,27 @@ class ReasoningService extends BaseReasoningService {
return apiKey;
}
+ // Single source for BYOK streaming credentials and endpoint overrides:
+ // rejects unknown providers instead of defaulting them to OpenAI, and only
+ // lets a custom scope borrow the shared cleanup key for the cleanup endpoint.
+ private async resolveByokAccess(
+ provider: string,
+ config: Pick<ReasoningConfig, "baseUrl" | "customApiKey">
+ ): Promise<{ apiKey: string; baseURL?: string }> {
+ const providerKey = toByokStreamProvider(provider);
+ const overrideKey = providerKey === "custom" ? config.customApiKey?.trim() || "" : "";
+ const canFallBackToSharedKey =
+ providerKey !== "custom" || canBorrowCleanupCustomKey(config.baseUrl);
+ const apiKey = overrideKey || (canFallBackToSharedKey ? await this.getApiKey(providerKey) : "");
+ const baseURL =
+ providerKey === "openrouter"
+ ? API_ENDPOINTS.OPENROUTER_BASE
+ : providerKey === "custom"
+ ? resolveConfiguredOpenAIBase(providerKey, config.baseUrl)
+ : undefined;
+ return { apiKey, baseURL };
+ }
+
private async callChatCompletionsApi(
endpoint: string,
apiKey: string,
@@ -422,6 +467,9 @@ class ReasoningService extends BaseReasoningService {
const providerId = isLanCleanup
? "lan"
: resolveInferenceProvider(dispatchConfig.provider, trimmedModel);
+ if (!providerId) {
+ throw new Error("No reasoning provider selected");
+ }
if (dispatchConfig.requiresAgent) assertAgentAllowedByPolicy();
assertReasoningAllowedByPolicy(providerId, resolveLlmDispatchMode(providerId, dispatchConfig));
@@ -501,39 +549,26 @@ class ReasoningService extends BaseReasoningService {
}
endpoint = `http://127.0.0.1:${serverResult.port}/v1/chat/completions`;
} else {
- const providerKey = provider as
- "openai" | "groq" | "gemini" | "anthropic" | "tinfoil" | "custom" | "openrouter" | "corti";
- const overrideKey = providerKey === "custom" ? config.customApiKey?.trim() : "";
- apiKey = overrideKey || (await this.getApiKey(providerKey));
-
- switch (providerKey) {
- case "groq":
- endpoint = buildApiUrl(API_ENDPOINTS.GROQ_BASE, "/chat/completions");
- break;
- case "corti":
- endpoint = buildApiUrl(API_ENDPOINTS.CORTI_MODELS_BASE, "/chat/completions");
- break;
- case "gemini":
- endpoint = buildApiUrl(API_ENDPOINTS.GEMINI, "/openai/chat/completions");
- break;
- case "openrouter":
- endpoint = buildApiUrl(API_ENDPOINTS.OPENROUTER_BASE, "/chat/completions");
- break;
- case "tinfoil":
- throw new Error("Tinfoil streaming must use the verified SDK transport");
- case "openai":
- endpoint = buildApiUrl(API_ENDPOINTS.OPENAI_BASE, "/chat/completions");
- break;
- case "custom":
- endpoint = buildApiUrl(
- resolveConfiguredOpenAIBase(providerKey, config.baseUrl),
- "/chat/completions"
- );
- break;
- default:
- endpoint = buildApiUrl(API_ENDPOINTS.OPENAI_BASE, "/chat/completions");
- break;
+ const access = await this.resolveByokAccess(provider, config);
+ apiKey = access.apiKey;
+ const chatBase =
+ access.baseURL ??
+ (
+ {
+ openai: API_ENDPOINTS.OPENAI_BASE,
+ groq: API_ENDPOINTS.GROQ_BASE,
+ corti: API_ENDPOINTS.CORTI_MODELS_BASE,
+ gemini: API_ENDPOINTS.GEMINI,
+ } as Partial<Record<string, string>>
+ )[provider];
+ // anthropic and tinfoil have no raw Chat Completions transport here.
+ if (!chatBase) {
+ throw new Error(`${provider} streaming must use the AI SDK transport`);
}
+ endpoint = buildApiUrl(
+ chatBase,
+ provider === "gemini" ? "/openai/chat/completions" : "/chat/completions"
+ );
}
// A known endpoint host knows its own request shape better than the model id does.
@@ -739,16 +774,7 @@ class ReasoningService extends BaseReasoningService {
}
baseURL = `http://127.0.0.1:${serverResult.port}/v1`;
} else {
- const providerKey = provider as
- "openai" | "groq" | "gemini" | "anthropic" | "tinfoil" | "custom" | "openrouter" | "corti";
- const overrideKey = providerKey === "custom" ? config.customApiKey?.trim() : "";
- apiKey = overrideKey || (await this.getApiKey(providerKey));
- baseURL =
- provider === "openrouter"
- ? API_ENDPOINTS.OPENROUTER_BASE
- : provider === "custom"
- ? resolveConfiguredOpenAIBase(provider, config.baseUrl)
- : undefined;
+ ({ apiKey, baseURL } = await this.resolveByokAccess(provider, config));
}
const aiProvider = isLocalProvider || isLanChat ? "local" : provider;
// OpenRouter ids are never in the local registry, so the supportsThinking
diff --git a/src/services/ai/inferenceProviders/openai.ts b/src/services/ai/inferenceProviders/openai.ts
index d42f484e8..4eef5e0f8 100644
--- a/src/services/ai/inferenceProviders/openai.ts
+++ b/src/services/ai/inferenceProviders/openai.ts
@@ -4,7 +4,7 @@ import { getOpenAiApiConfig } from "../../../models/ModelRegistry";
import { getSettings } from "../../../stores/settingsStore";
import { withRetry, createApiRetryStrategy, httpError } from "../../../utils/retry";
import logger from "../../../utils/logger";
-import { resolveConfiguredOpenAIBase } from "../openaiBase";
+import { canBorrowCleanupCustomKey, resolveConfiguredOpenAIBase } from "../openaiBase";
import { applyThinkingSuppression } from "../thinkingSuppression";
import { detectEndpointDialect } from "../thinkingSuppressionDialects";
import { extractApiErrorMessage } from "../apiErrorMessage";
@@ -136,9 +136,12 @@ export const openaiProvider: InferenceProvider = {
});
const overrideKey = isCustomProvider ? config.customApiKey?.trim() : "";
+ const canFallBackToSharedKey = !isCustomProvider || canBorrowCleanupCustomKey(config.baseUrl);
const apiKey =
overrideKey ||
- (await ctx.getApiKey(isCustomProvider ? "custom" : isOpenRouter ? "openrouter" : "openai"));
+ (canFallBackToSharedKey
+ ? await ctx.getApiKey(isCustomProvider ? "custom" : isOpenRouter ? "openrouter" : "openai")
+ : "");
logger.logReasoning("OPENAI_API_KEY", {
hasApiKey: !!apiKey,
@@ -247,7 +250,7 @@ export const openaiProvider: InferenceProvider = {
method: "POST",
headers: {
"Content-Type": "application/json",
- Authorization: `Bearer ${apiKey}`,
+ ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
},
body: JSON.stringify(requestBody),
signal: controller.signal,
diff --git a/src/services/ai/openaiBase.ts b/src/services/ai/openaiBase.ts
index b3ae81b8f..d1d03847c 100644
--- a/src/services/ai/openaiBase.ts
+++ b/src/services/ai/openaiBase.ts
@@ -1,23 +1,24 @@
import { API_ENDPOINTS, ensureV1Suffix } from "../../config/constants";
import { usePolicyStore } from "../../stores/policyStore";
+import { getSettings } from "../../stores/settingsStore";
import { isSecureHttpEndpoint } from "../../utils/urlUtils";
import logger from "../../utils/logger";
import i18n from "../../i18n";
-function invalidCustomEndpoint(reason: string, attempted?: string): string {
+// Never falls back: rerouting an invalid Custom endpoint to api.openai.com
+// would send the prompt and the custom API key to a host the user never chose.
+function invalidCustomEndpoint(reason: string, attempted?: string): never {
+ logger.logReasoning("OPENAI_BASE_REJECTED", { reason, attempted });
+
const policyStatus = usePolicyStore.getState().status;
if (policyStatus !== "idle" && policyStatus !== "unmanaged") {
throw Object.assign(new Error(i18n.t("common.policyAiProcessingRestricted")), {
code: "POLICY_RESTRICTED",
});
}
-
- logger.logReasoning("OPENAI_BASE_REJECTED", {
- reason,
- attempted,
- fallbackTo: API_ENDPOINTS.OPENAI_BASE,
+ throw Object.assign(new Error(i18n.t("reasoning.custom.endpointInvalid")), {
+ code: "CUSTOM_ENDPOINT_INVALID",
});
- return API_ENDPOINTS.OPENAI_BASE;
}
export function resolveConfiguredOpenAIBase(provider: string, configuredBaseUrl?: string): string {
@@ -37,6 +38,8 @@ export function resolveConfiguredOpenAIBase(provider: string, configuredBaseUrl?
"api.groq.com",
"api.anthropic.com",
"generativelanguage.googleapis.com",
+ // Tinfoil must go through its attested SDK client, never a plain fetch.
+ "tinfoil.sh",
];
if (knownNonOpenAIUrls.some((url) => normalized.includes(url))) {
return invalidCustomEndpoint("Custom URL is a known non-OpenAI provider", normalized);
@@ -58,6 +61,15 @@ export function resolveConfiguredOpenAIBase(provider: string, configuredBaseUrl?
return normalized;
}
+// The shared "custom" key slot belongs to Dictation Cleanup's endpoint. Only a
+// request bound for that same endpoint may borrow it — attaching it to another
+// scope's endpoint would send the credential to a host it was never entered for.
+export function canBorrowCleanupCustomKey(requestBaseUrl: string | undefined): boolean {
+ const cleanupBase = getSettings().cleanupCloudBaseUrl?.trim();
+ const requestBase = requestBaseUrl?.trim();
+ return !!requestBase && requestBase === cleanupBase;
+}
+
export function resolveSelfHostedOpenAIBase(configuredBaseUrl: string): string {
const normalized = ensureV1Suffix(configuredBaseUrl.trim());
if (!normalized || !isSecureHttpEndpoint(normalized)) {
diff --git a/src/stores/cleanupFailureStore.ts b/src/stores/cleanupFailureStore.ts
index 06cd447d7..66e096e98 100644
--- a/src/stores/cleanupFailureStore.ts
+++ b/src/stores/cleanupFailureStore.ts
@@ -3,14 +3,20 @@ import { create } from "zustand";
interface CleanupFailureState {
/** Dictations handed back raw because cleanup failed, not yet surfaced to the user. */
pending: number;
+ /** Cause of the most recent failure, shown with the toast so it's actionable. */
+ lastMessage: string;
}
export const useCleanupFailureStore = create<CleanupFailureState>(() => ({
pending: 0,
+ lastMessage: "",
}));
-export function recordCleanupFailure(): void {
- useCleanupFailureStore.setState((state) => ({ pending: state.pending + 1 }));
+export function recordCleanupFailure(message = ""): void {
+ useCleanupFailureStore.setState((state) => ({
+ pending: state.pending + 1,
+ lastMessage: message,
+ }));
}
export function consumeCleanupFailures(): number {
diff --git a/src/stores/enterpriseIdentityStore.ts b/src/stores/enterpriseIdentityStore.ts
index c3d508904..4650c73c5 100644
--- a/src/stores/enterpriseIdentityStore.ts
+++ b/src/stores/enterpriseIdentityStore.ts
@@ -180,12 +180,20 @@ if (typeof window !== "undefined") {
});
}
+// The vision override is the dictation agent's image lane; it has no managed
+// scope of its own (enterprise envelopes predate it), so managed resolution
+// follows the agent scope instead of failing as an unknown scope.
+const MANAGED_SCOPE_ALIASES: Partial<Record<InferenceScope, InferenceScope>> = {
+ dictationAgentVision: "dictationAgent",
+};
+
function resolveScope(
config: ManagedEnterpriseConfig | null,
- scope: InferenceScope,
+ requestedScope: InferenceScope,
setupMode: EnterpriseSetupMode,
failClosed: boolean
): ManagedEnterpriseScopeResolution {
+ const scope = MANAGED_SCOPE_ALIASES[requestedScope] ?? requestedScope;
if (!config && failClosed) {
return {
kind: "error",
diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.ts
index 62554b599..986d890cc 100644
--- a/src/stores/settingsStore.ts
+++ b/src/stores/settingsStore.ts
@@ -125,6 +125,18 @@ function canonicalTranscriptionBaseUrl(providerId: string): string | null {
);
}
+function reasoningModelBelongsToProvider(providerId: string, modelId: string): boolean {
+ if (!modelId) return false;
+ // Custom and OpenRouter ids are free-form; any remembered id is valid.
+ // Tinfoil's registry entry is refreshed in place from its live catalog.
+ if (providerId === "custom" || providerId === "openrouter") return true;
+ return (
+ modelRegistryData.cloudProviders
+ .find((provider) => provider.id === providerId)
+ ?.models.some((model) => model.id === modelId) ?? false
+ );
+}
+
function defaultLlmModel(mode: InferenceMode, providerId: string, bedrockRegion: string): string {
const providers =
mode === "local"
@@ -629,6 +641,9 @@ export interface SettingsState
/** Last model used per scope+provider (`"<context>:<providerId>"`), so switching providers restores it. */
transcriptionModelByProvider: Record<string, string>;
+ /** LLM twin of transcriptionModelByProvider, keyed `"<scope>:<providerId>"`. */
+ reasoningModelByProvider: Record<string, string>;
+
noteFormattingMode: InferenceMode;
noteFormattingProvider: string;
noteFormattingModel: string;
@@ -768,6 +783,11 @@ export interface SettingsState
context: TranscriptionPolicyContext,
providerId: string
) => void;
+ switchReasoningProvider: (
+ scope: InferenceScope,
+ providerId: string,
+ fallbackModel?: string
+ ) => void;
setCleanupCloudMode: (value: string) => void;
setCleanupCloudBaseUrl: (value: string) => void;
setCustomDictionary: (words: string[]) => void;
@@ -917,6 +937,22 @@ function persistTranscriptionModelMemory(memory: Record<string, string>) {
useSettingsStore.setState({ transcriptionModelByProvider: memory });
}
+function persistReasoningModelMemory(memory: Record<string, string>) {
+ if (isBrowser) localStorage.setItem("reasoningModelByProvider", JSON.stringify(memory));
+ useSettingsStore.setState({ reasoningModelByProvider: memory });
+}
+
+function readModelMemory(key: string): Record<string, string> {
+ try {
+ const parsed = JSON.parse(readString(key, "{}"));
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
+ ? (parsed as Record<string, string>)
+ : {};
+ } catch {
+ return {};
+ }
+}
+
/** Writes a string setting whose key is computed rather than known up front. */
export function setStringSetting(key: keyof SettingsState, value: string): void {
createStringSetter(key)(value);
@@ -1014,6 +1050,11 @@ const SECRET_IPC_SAVERS = {
tinfoil: "saveTinfoilKey",
customTranscription: "saveCustomTranscriptionKey",
cleanupCustom: "saveCleanupCustomKey",
+ noteFormattingCustom: "saveNoteFormattingCustomKey",
+ translationCustom: "saveTranslationCustomKey",
+ dictationAgentCustom: "saveDictationAgentCustomKey",
+ dictationAgentVisionCustom: "saveDictationAgentVisionCustomKey",
+ chatAgentCustom: "saveChatAgentCustomKey",
bedrockAccessKeyId: "saveBedrockAccessKeyId",
bedrockSecretAccessKey: "saveBedrockSecretAccessKey",
bedrockSessionToken: "saveBedrockSessionToken",
@@ -1057,6 +1098,11 @@ const STALE_SECRET_LOCALSTORAGE_KEYS = [
"customTranscriptionApiKey",
"customReasoningApiKey",
"cleanupCustomApiKey",
+ "noteFormattingCustomApiKey",
+ "translationCustomApiKey",
+ "dictationAgentCustomApiKey",
+ "dictationAgentVisionCustomApiKey",
+ "chatAgentCustomApiKey",
"bedrockAccessKeyId",
"bedrockSecretAccessKey",
"bedrockSessionToken",
@@ -1137,16 +1183,8 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
"cloudTranscriptionBaseUrl",
API_ENDPOINTS.TRANSCRIPTION_BASE
),
- transcriptionModelByProvider: (() => {
- try {
- const parsed = JSON.parse(readString("transcriptionModelByProvider", "{}"));
- return parsed && typeof parsed === "object" && !Array.isArray(parsed)
- ? (parsed as Record<string, string>)
- : {};
- } catch {
- return {};
- }
- })(),
+ transcriptionModelByProvider: readModelMemory("transcriptionModelByProvider"),
+ reasoningModelByProvider: readModelMemory("reasoningModelByProvider"),
// Secrets aren't hydrated yet at construction; the BYOK default is set
// post-hydration in initializeSettings.
cloudTranscriptionMode: readString("cloudTranscriptionMode", "openwhispr"),
@@ -1473,7 +1511,11 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
setNoteFormattingCloudMode: createStringSetter("noteFormattingCloudMode"),
setNoteFormattingCloudBaseUrl: createStringSetter("noteFormattingCloudBaseUrl"),
setNoteFormattingRemoteUrl: createStringSetter("noteFormattingRemoteUrl"),
- setNoteFormattingCustomApiKey: createStringSetter("noteFormattingCustomApiKey"),
+ setNoteFormattingCustomApiKey: createSecretSetter(
+ "noteFormattingCustomApiKey",
+ "noteFormattingCustom",
+ "custom"
+ ),
setTranslationMode: createStringSetter("translationMode") as (mode: InferenceMode) => void,
setTranslationProvider: createStringSetter("translationProvider"),
@@ -1481,7 +1523,11 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
setTranslationCloudMode: createStringSetter("translationCloudMode"),
setTranslationCloudBaseUrl: createStringSetter("translationCloudBaseUrl"),
setTranslationRemoteUrl: createStringSetter("translationRemoteUrl"),
- setTranslationCustomApiKey: createStringSetter("translationCustomApiKey"),
+ setTranslationCustomApiKey: createSecretSetter(
+ "translationCustomApiKey",
+ "translationCustom",
+ "custom"
+ ),
setTranslationDisableThinking: createBooleanSetter("translationDisableThinking"),
setUseDictationTranslation: createBooleanSetter("useDictationTranslation"),
setTranslationSourceLanguage: createStringSetter("translationSourceLanguage"),
@@ -1569,7 +1615,11 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
setDictationAgentCloudMode: createStringSetter("dictationAgentCloudMode"),
setDictationAgentCloudBaseUrl: createStringSetter("dictationAgentCloudBaseUrl"),
setDictationAgentRemoteUrl: createStringSetter("dictationAgentRemoteUrl"),
- setDictationAgentCustomApiKey: createStringSetter("dictationAgentCustomApiKey"),
+ setDictationAgentCustomApiKey: createSecretSetter(
+ "dictationAgentCustomApiKey",
+ "dictationAgentCustom",
+ "custom"
+ ),
setVoiceAgentScreenContext: createBooleanSetter("voiceAgentScreenContext"),
setUseDictationAgentVisionModel: createBooleanSetter("useDictationAgentVisionModel"),
@@ -1580,7 +1630,11 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
setDictationAgentVisionModel: createStringSetter("dictationAgentVisionModel"),
setDictationAgentVisionCloudMode: createStringSetter("dictationAgentVisionCloudMode"),
setDictationAgentVisionCloudBaseUrl: createStringSetter("dictationAgentVisionCloudBaseUrl"),
- setDictationAgentVisionCustomApiKey: createStringSetter("dictationAgentVisionCustomApiKey"),
+ setDictationAgentVisionCustomApiKey: createSecretSetter(
+ "dictationAgentVisionCustomApiKey",
+ "dictationAgentVisionCustom",
+ "custom"
+ ),
setCleanupDisableThinking: createBooleanSetter("cleanupDisableThinking"),
setDictationAgentDisableThinking: createBooleanSetter("dictationAgentDisableThinking"),
@@ -1637,6 +1691,34 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
: defaultTranscriptionModel(providerId, context)
);
},
+
+ // LLM twin of switchCloudTranscriptionProvider. The caller supplies the
+ // provider's default model because dynamic catalogs (Tinfoil) live in the UI.
+ switchReasoningProvider: (scope, providerId, fallbackModel = "") => {
+ const s = useSettingsStore.getState();
+ const cfg = selectResolvedLLMConfig(s, scope);
+ const memory = { ...s.reasoningModelByProvider };
+ // Only remember a model the outgoing provider actually owns — after a
+ // local/cloud mode round-trip the shared slot can hold a foreign id.
+ if (cfg.provider && cfg.provider !== providerId) {
+ if (reasoningModelBelongsToProvider(cfg.provider, cfg.model)) {
+ memory[`${scope}:${cfg.provider}`] = cfg.model;
+ persistReasoningModelMemory(memory);
+ }
+ } else if (reasoningModelBelongsToProvider(providerId, cfg.model)) {
+ // Reselecting the current provider with a model it owns: keep it.
+ setResolvedLLMConfig(scope, { provider: providerId });
+ return;
+ }
+ const remembered = memory[`${scope}:${providerId}`];
+ setResolvedLLMConfig(scope, {
+ provider: providerId,
+ model:
+ remembered && reasoningModelBelongsToProvider(providerId, remembered)
+ ? remembered
+ : fallbackModel,
+ });
+ },
setCloudTranscriptionMode: createStringSetter("cloudTranscriptionMode"),
setCleanupCloudMode: createStringSetter("cleanupCloudMode"),
setCleanupCloudBaseUrl: createStringSetter("cleanupCloudBaseUrl"),
@@ -2097,7 +2179,11 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
setChatAgentMode: createStringSetter("chatAgentMode") as (mode: InferenceMode) => void,
setChatAgentCloudBaseUrl: createStringSetter("chatAgentCloudBaseUrl"),
setChatAgentRemoteUrl: createStringSetter("chatAgentRemoteUrl"),
- setChatAgentCustomApiKey: createStringSetter("chatAgentCustomApiKey"),
+ setChatAgentCustomApiKey: createSecretSetter(
+ "chatAgentCustomApiKey",
+ "chatAgentCustom",
+ "custom"
+ ),
updateTranscriptionSettings: (settings: Partial<TranscriptionSettings>) => {
const s = useSettingsStore.getState();
@@ -2443,6 +2529,18 @@ export const selectResolvedLLMConfig = (
};
};
+// Scope custom keys are secrets kept in the OS secure store, not localStorage
+// (which is stripped on startup). Writes must go through their dedicated
+// setters so the values survive restarts.
+const SECRET_SCOPE_KEY_SETTERS = {
+ cleanupCustomApiKey: "setCleanupCustomApiKey",
+ noteFormattingCustomApiKey: "setNoteFormattingCustomApiKey",
+ translationCustomApiKey: "setTranslationCustomApiKey",
+ dictationAgentCustomApiKey: "setDictationAgentCustomApiKey",
+ dictationAgentVisionCustomApiKey: "setDictationAgentVisionCustomApiKey",
+ chatAgentCustomApiKey: "setChatAgentCustomApiKey",
+} as const;
+
export function setResolvedLLMConfig(
scope: InferenceScope,
patch: Partial<Omit<ResolvedLLMConfig, "scope">>
@@ -2453,11 +2551,10 @@ export function setResolvedLLMConfig(
if (value === undefined) continue;
const storeKey = def.storeKeys[field as keyof InferenceScopeStoreKeys];
if (!storeKey) continue;
- // cleanupCustomApiKey is a secret kept in the OS secure store, not
- // localStorage (which is stripped on startup). Route it through the
- // dedicated setter so it survives restarts.
- if (storeKey === "cleanupCustomApiKey") {
- useSettingsStore.getState().setCleanupCustomApiKey(value as string);
+ const secretSetter =
+ SECRET_SCOPE_KEY_SETTERS[storeKey as keyof typeof SECRET_SCOPE_KEY_SETTERS];
+ if (secretSetter) {
+ useSettingsStore.getState()[secretSetter](value as string);
continue;
}
if (isBrowser) {
@@ -2658,6 +2755,32 @@ export async function reconcileLocalModelSelections(): Promise<void> {
clearMissingLocalModelSelections((modelId) => installed.has(modelId));
}
+/**
+ * Repoints any scope still selecting a cloud model the registry no longer ships
+ * (e.g. a retired Groq id) at that provider's current default — otherwise every
+ * request 404s with an error the user can't act on. Custom, OpenRouter and
+ * Tinfoil ids are skipped: they're free-form or reconciled from the live
+ * catalog in tinfoilModels.ts.
+ */
+export function reconcileRetiredCloudModelSelections(): void {
+ const state = useSettingsStore.getState() as unknown as Record<string, unknown>;
+ for (const scope of Object.values(INFERENCE_SCOPES)) {
+ const provider = state[scope.storeKeys.provider] as string;
+ const model = state[scope.storeKeys.model] as string;
+ if (!provider || !model || provider === "tinfoil") continue;
+ const providerDef = modelRegistryData.cloudProviders.find((p) => p.id === provider);
+ if (!providerDef || reasoningModelBelongsToProvider(provider, model)) continue;
+ const replacement = providerDef.models[0]?.id;
+ if (!replacement) continue;
+ setStringSetting(scope.storeKeys.model as keyof SettingsState, replacement);
+ logger.info(
+ "Repointed retired cloud model selection",
+ { scope: scope.storeKeys.model, from: model, to: replacement },
+ "settings"
+ );
+ }
+}
+
export function getEffectiveCleanupModel() {
const state = getSettings();
if (selectIsCloudCleanupMode(state)) {
@@ -2680,6 +2803,30 @@ export function isCloudTranslationMode() {
// --- Initialization ---
+// One-time migration: scope custom keys lived in plaintext localStorage before
+// moving to the OS secure store. Prefer the secure value; otherwise push the
+// legacy plaintext copy into the secure store — the stale-secret sweep in
+// initializeSettings then strips it from localStorage.
+async function migrateScopeCustomKeys(
+ entries: ReadonlyArray<[keyof SettingsState & string, string | null | undefined, string]>
+): Promise<Partial<SettingsState>> {
+ const updates: Record<string, string> = {};
+ for (const [storeKey, secureValue, saverName] of entries) {
+ let value = secureValue || "";
+ if (!value) {
+ const legacy = localStorage.getItem(storeKey)?.trim() || "";
+ if (legacy) {
+ value = legacy;
+ const save = window.electronAPI?.[saverName as keyof typeof window.electronAPI] as
+ ((key: string) => Promise<unknown>) | undefined;
+ await save?.(legacy);
+ }
+ }
+ updates[storeKey] = value;
+ }
+ return updates as Partial<SettingsState>;
+}
+
let hasInitialized = false;
export async function initializeSettings(): Promise<void> {
@@ -2706,6 +2853,11 @@ export async function initializeSettings(): Promise<void> {
tinfoil,
customTx,
customRx,
+ noteFormattingCustom,
+ translationCustom,
+ dictationAgentCustom,
+ dictationAgentVisionCustom,
+ chatAgentCustom,
bedrockAccessKeyId,
bedrockSecretAccessKey,
bedrockSessionToken,
@@ -2725,6 +2877,11 @@ export async function initializeSettings(): Promise<void> {
window.electronAPI.getTinfoilKey?.(),
window.electronAPI.getCustomTranscriptionKey?.(),
window.electronAPI.getCleanupCustomKey?.(),
+ window.electronAPI.getNoteFormattingCustomKey?.(),
+ window.electronAPI.getTranslationCustomKey?.(),
+ window.electronAPI.getDictationAgentCustomKey?.(),
+ window.electronAPI.getDictationAgentVisionCustomKey?.(),
+ window.electronAPI.getChatAgentCustomKey?.(),
window.electronAPI.getBedrockAccessKeyId?.(),
window.electronAPI.getBedrockSecretAccessKey?.(),
window.electronAPI.getBedrockSessionToken?.(),
@@ -2747,6 +2904,17 @@ export async function initializeSettings(): Promise<void> {
customTranscriptionApiKey: customTx || "",
cleanupCustomApiKey: customRx || "",
bedrockAccessKeyId: bedrockAccessKeyId || "",
+ ...(await migrateScopeCustomKeys([
+ ["noteFormattingCustomApiKey", noteFormattingCustom, "saveNoteFormattingCustomKey"],
+ ["translationCustomApiKey", translationCustom, "saveTranslationCustomKey"],
+ ["dictationAgentCustomApiKey", dictationAgentCustom, "saveDictationAgentCustomKey"],
+ [
+ "dictationAgentVisionCustomApiKey",
+ dictationAgentVisionCustom,
+ "saveDictationAgentVisionCustomKey",
+ ],
+ ["chatAgentCustomApiKey", chatAgentCustom, "saveChatAgentCustomKey"],
+ ])),
bedrockSecretAccessKey: bedrockSecretAccessKey || "",
bedrockSessionToken: bedrockSessionToken || "",
azureApiKey: azureApiKey || "",
@@ -3061,6 +3229,8 @@ export async function initializeSettings(): Promise<void> {
);
}
+ reconcileRetiredCloudModelSelections();
+
try {
await reconcileLocalModelSelections();
} catch (err) {
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 6729131aa..20e5061c4 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -1620,6 +1620,16 @@ declare global {
saveCustomTranscriptionKey?: (key: string) => Promise<void>;
getCleanupCustomKey?: () => Promise<string | null>;
saveCleanupCustomKey?: (key: string) => Promise<void>;
+ getNoteFormattingCustomKey?: () => Promise<string | null>;
+ saveNoteFormattingCustomKey?: (key: string) => Promise<void>;
+ getTranslationCustomKey?: () => Promise<string | null>;
+ saveTranslationCustomKey?: (key: string) => Promise<void>;
+ getDictationAgentCustomKey?: () => Promise<string | null>;
+ saveDictationAgentCustomKey?: (key: string) => Promise<void>;
+ getDictationAgentVisionCustomKey?: () => Promise<string | null>;
+ saveDictationAgentVisionCustomKey?: (key: string) => Promise<void>;
+ getChatAgentCustomKey?: () => Promise<string | null>;
+ saveChatAgentCustomKey?: (key: string) => Promise<void>;
// Enterprise provider key persistence
getBedrockRegion?: () => Promise<string | null>;
diff --git a/test/helpers/dictationAgentInference.test.js b/test/helpers/dictationAgentInference.test.js
index 665d201e9..9c30b0b3a 100644
--- a/test/helpers/dictationAgentInference.test.js
+++ b/test/helpers/dictationAgentInference.test.js
@@ -227,3 +227,52 @@ test("enterprise mode with a missing provider fails closed", async () => {
assert.equal(result.reachable, false);
assert.equal(result.config.provider, undefined);
});
+
+test("vision override runs as the dictation agent scope and inherits key with endpoint", async () => {
+ const { resolveDictationAgentVisionInference } = await load();
+
+ const result = resolveDictationAgentVisionInference({
+ ...baseSettings,
+ dictationAgentProvider: "custom",
+ dictationAgentCloudBaseUrl: "https://agent.example.com/v1",
+ dictationAgentCustomApiKey: "agent-key",
+ useDictationAgentVisionModel: true,
+ dictationAgentVisionMode: "providers",
+ dictationAgentVisionProvider: "",
+ dictationAgentVisionModel: "vision-model",
+ dictationAgentVisionCloudBaseUrl: "",
+ dictationAgentVisionCustomApiKey: "",
+ });
+
+ assert.equal(result.config.inferenceScope, "dictationAgent");
+ assert.equal(result.config.baseUrl, "https://agent.example.com/v1");
+ assert.equal(
+ result.config.customApiKey,
+ "agent-key",
+ "an inherited endpoint must carry the agent's key with it"
+ );
+});
+
+test("a vision scope with its own endpoint never borrows the agent's key", async () => {
+ const { resolveDictationAgentVisionInference } = await load();
+
+ const result = resolveDictationAgentVisionInference({
+ ...baseSettings,
+ dictationAgentProvider: "custom",
+ dictationAgentCloudBaseUrl: "https://agent.example.com/v1",
+ dictationAgentCustomApiKey: "agent-key",
+ useDictationAgentVisionModel: true,
+ dictationAgentVisionMode: "providers",
+ dictationAgentVisionProvider: "custom",
+ dictationAgentVisionModel: "vision-model",
+ dictationAgentVisionCloudBaseUrl: "https://vision.example.com/v1",
+ dictationAgentVisionCustomApiKey: "",
+ });
+
+ assert.equal(result.config.baseUrl, "https://vision.example.com/v1");
+ assert.equal(
+ result.config.customApiKey,
+ undefined,
+ "the agent's key must not ride to the vision scope's own endpoint"
+ );
+});
diff --git a/test/helpers/reasoningModelMemory.test.js b/test/helpers/reasoningModelMemory.test.js
new file mode 100644
index 000000000..d4e60a5df
--- /dev/null
+++ b/test/helpers/reasoningModelMemory.test.js
@@ -0,0 +1,116 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+test("per-provider reasoning model memory", async (t) => {
+ installBrowserGlobals(t, {
+ initialStorage: {
+ _llmScopeKeysMigrated: "1",
+ cleanupMode: "providers",
+ cleanupProvider: "custom",
+ cleanupModel: "parasail-llm-v1",
+ cleanupCloudBaseUrl: "https://llm.parasail.example.com/v1",
+ },
+ });
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-reasoning-model-memory-test-",
+ });
+ const { useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");
+ const state = () => useSettingsStore.getState();
+
+ await t.test("switch-and-return restores the custom model (Parasail scenario)", () => {
+ state().switchReasoningProvider("dictationCleanup", "openai", "gpt-5.2");
+ assert.equal(state().cleanupProvider, "openai");
+ assert.equal(state().cleanupModel, "gpt-5.2");
+ assert.equal(
+ state().cleanupCloudBaseUrl,
+ "https://llm.parasail.example.com/v1",
+ "the custom URL slot must never be touched by a provider switch"
+ );
+
+ state().switchReasoningProvider("dictationCleanup", "custom", "");
+ assert.equal(state().cleanupProvider, "custom");
+ assert.equal(state().cleanupModel, "parasail-llm-v1");
+ });
+
+ await t.test("reselecting the current provider keeps the current model", () => {
+ state().setCleanupModel("parasail-tuned");
+ state().switchReasoningProvider("dictationCleanup", "custom", "");
+ assert.equal(state().cleanupModel, "parasail-tuned");
+ });
+
+ await t.test("a remembered model the provider no longer ships falls back", () => {
+ state().switchReasoningProvider("dictationCleanup", "groq", "llama-3.3-70b-versatile");
+ state().setCleanupModel("retired-groq-model");
+ state().switchReasoningProvider("dictationCleanup", "custom", "");
+ state().switchReasoningProvider("dictationCleanup", "groq", "llama-3.3-70b-versatile");
+ assert.equal(
+ state().cleanupModel,
+ "llama-3.3-70b-versatile",
+ "an unknown remembered model must degrade to the provider default"
+ );
+ });
+
+ await t.test("scopes have independent memory and writes", () => {
+ state().switchReasoningProvider("dictationCleanup", "custom", "");
+ const cleanupModel = state().cleanupModel;
+
+ state().switchReasoningProvider("chatIntelligence", "openai", "gpt-5.2");
+ assert.equal(state().chatAgentProvider, "openai");
+ assert.equal(state().chatAgentModel, "gpt-5.2");
+ assert.equal(state().cleanupProvider, "custom", "base scope untouched");
+ assert.equal(state().cleanupModel, cleanupModel, "base scope untouched");
+ });
+
+ await t.test("memory persists to localStorage as JSON", () => {
+ const persisted = JSON.parse(localStorage.getItem("reasoningModelByProvider"));
+ assert.equal(typeof persisted, "object");
+ assert.ok(Object.keys(persisted).some((key) => key.startsWith("dictationCleanup:")));
+ });
+});
+
+test("corrupt persisted reasoning model memory hydrates as empty, not a crash", async (t) => {
+ installBrowserGlobals(t, {
+ initialStorage: {
+ _llmScopeKeysMigrated: "1",
+ reasoningModelByProvider: "{not json",
+ },
+ });
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-reasoning-model-memory-corrupt-test-",
+ });
+ const { useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");
+ assert.deepEqual(useSettingsStore.getState().reasoningModelByProvider, {});
+});
+
+test("retired cloud model selections are repointed to the provider default", async (t) => {
+ installBrowserGlobals(t, {
+ initialStorage: {
+ _llmScopeKeysMigrated: "1",
+ cleanupProvider: "groq",
+ cleanupModel: "meta-llama/llama-4-scout-17b-16e-instruct",
+ chatAgentProvider: "openai",
+ chatAgentModel: "gpt-5.2",
+ noteFormattingProvider: "custom",
+ noteFormattingModel: "my-endpoint-model",
+ },
+ });
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-retired-cloud-model-test-",
+ });
+ const { useSettingsStore, reconcileRetiredCloudModelSelections } = await vite.ssrLoadModule(
+ "/stores/settingsStore.ts"
+ );
+
+ reconcileRetiredCloudModelSelections();
+
+ const state = useSettingsStore.getState();
+ assert.notEqual(
+ state.cleanupModel,
+ "meta-llama/llama-4-scout-17b-16e-instruct",
+ "a registry-retired model must be repointed"
+ );
+ assert.ok(state.cleanupModel, "repointed to a concrete replacement, not cleared");
+ assert.equal(state.chatAgentModel, "gpt-5.2", "shipping models stay untouched");
+ assert.equal(state.noteFormattingModel, "my-endpoint-model", "custom ids are free-form");
+});
diff --git a/test/helpers/secretKeys.test.js b/test/helpers/secretKeys.test.js
index 5bd007d9e..0db76f844 100644
--- a/test/helpers/secretKeys.test.js
+++ b/test/helpers/secretKeys.test.js
@@ -71,7 +71,7 @@ test("preload BYOK_KEY_BRIDGES mirror the manifest exactly", () => {
assert.ok(block, "BYOK_KEY_BRIDGES declared in preload.js");
for (const k of BYOK_API_KEYS) {
const entry = new RegExp(
- `\\{\\s*base:\\s*"${k.base}",\\s*get:\\s*"${k.get}",\\s*save:\\s*"${k.save}"\\s*\\}`
+ `\\{\\s*base:\\s*"${k.base}",\\s*get:\\s*"${k.get}",\\s*save:\\s*"${k.save}",?\\s*\\}`
);
assert.match(block[1], entry, `preload mirrors ${k.base}`);
}
diff --git a/test/services/reasoningServiceEnforcement.test.js b/test/services/reasoningServiceEnforcement.test.js
index e7da620dc..07fae0a67 100644
--- a/test/services/reasoningServiceEnforcement.test.js
+++ b/test/services/reasoningServiceEnforcement.test.js
@@ -162,20 +162,80 @@ test("ReasoningService entry points enforce the org policy", async (t) => {
}
});
- await t.test("unmanaged Custom endpoint compatibility remains unchanged", () => {
+ await t.test("unmanaged Custom endpoints fail closed instead of falling back to OpenAI", () => {
usePolicyStore.setState({ status: "unmanaged", appVersion: "1.8.1", policy: null });
- assert.equal(resolveConfiguredOpenAIBase("custom", ""), "https://api.openai.com/v1");
- assert.equal(
- resolveConfiguredOpenAIBase("custom", "http://public.example.com/v1"),
- "https://api.openai.com/v1"
- );
+ const CUSTOM_ENDPOINT_INVALID = enTranslations.reasoning.custom.endpointInvalid;
+ for (const baseUrl of [
+ "",
+ "http://public.example.com/v1",
+ "https://api.groq.com/openai/v1",
+ "https://inference.tinfoil.sh/v1",
+ ]) {
+ assert.throws(() => resolveConfiguredOpenAIBase("custom", baseUrl), {
+ message: CUSTOM_ENDPOINT_INVALID,
+ });
+ }
+ // HTTP stays allowed for local-network endpoints.
assert.equal(
resolveConfiguredOpenAIBase("custom", "http://192.168.1.20:11434/v1"),
"http://192.168.1.20:11434/v1"
);
});
+ await t.test("a scope's custom endpoint never borrows the cleanup key", async () => {
+ setPolicy({ llmModes: ["providers"], llmByokProviders: ["custom"] });
+ useSettingsStore.setState({
+ cleanupMode: "providers",
+ cleanupProvider: "custom",
+ cleanupCloudBaseUrl: "https://cleanup.example.com/v1",
+ cleanupCustomApiKey: "cleanup-secret",
+ });
+
+ const originalFetch = globalThis.fetch;
+ const requests = [];
+ globalThis.fetch = async (url, init) => {
+ requests.push({ url: String(url), auth: init?.headers?.Authorization });
+ return new Response(JSON.stringify({ error: "expected test stop" }), {
+ status: 400,
+ headers: { "content-type": "application/json" },
+ });
+ };
+
+ try {
+ await assert.rejects(
+ reasoningService.processText("hi", "other-model", null, {
+ provider: "custom",
+ baseUrl: "https://other-scope.example.com/v1",
+ inferenceScope: "chatIntelligence",
+ }),
+ { message: "expected test stop" }
+ );
+ assert.ok(requests.length > 0);
+ for (const request of requests) {
+ assert.ok(request.url.startsWith("https://other-scope.example.com/v1/"));
+ assert.equal(
+ request.auth,
+ undefined,
+ "the cleanup key must not ride to another scope's endpoint"
+ );
+ }
+
+ // The cleanup endpoint itself still gets the shared key.
+ requests.length = 0;
+ await assert.rejects(
+ reasoningService.processText("hi", "cleanup-model", null, {
+ provider: "custom",
+ baseUrl: "https://cleanup.example.com/v1",
+ }),
+ { message: "expected test stop" }
+ );
+ assert.ok(requests.some((request) => request.auth === "Bearer cleanup-secret"));
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ });
+
await t.test("normal cleanup uses its saved valid Custom endpoint", async () => {
setPolicy({ llmModes: ["providers"], llmByokProviders: ["custom"] });
useSettingsStore.setState({