Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
refactor(transcription): fail-closed STT routing — leak fixes, provider registry, model memory, single resolver (#1556)
Gabriel Steinbbee4cd901fa
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b828ae4eb..b91d62dc1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,18 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [Unreleased]++### Speech to text++- **Action required for some Custom endpoints.** If you selected the Custom speech-to-text provider but never changed its pre-filled URL (`https://api.openai.com/v1`), your audio and your custom key were being sent to OpenAI. That now fails with a clear error instead, so set a real endpoint under Settings → Speech to Text — or switch to the OpenAI provider, which the URL field does automatically once you re-enter it. (#1556)+- **Re-transcribing a Corti recording reaches Corti.** History → Re-transcribe sent Corti recordings to OpenAI. (#1556)+- **A leftover provider can no longer hijack self-hosted transcription.** With self-hosted selected, a stale Mistral, xAI, or Corti selection could still divert your audio to that provider. (#1556)+- **Each provider remembers its own model.** Switching speech-to-text providers and back restores the model you had chosen instead of resetting it to the default — including custom model names on your own endpoint. (#1556)+- **Mistral file uploads authenticate correctly.** Upload was the last path still sending a Bearer token instead of Mistral's `x-api-key`. (#1556)+- **Azure OpenAI endpoints work on every path.** Dictation, re-transcribe, and upload all build deployment-style URLs, whether the endpoint is configured as Custom or self-hosted. (#1556)+- **Uploads detect their own language again.** A file you upload is no longer forced into your dictation language. (#1556)+## [1.8.2] - 2026-08-11Meetings get more reliable speaker identity — labels you set now stick, Windows loopback gains live identification, and Intel Mac meetings no longer fail when the optional ONNX binding is unavailable. The voice agent can edit highlighted text in place or use an opt-in screenshot as context. Collaboration is now free for signed-in users, Microsoft and Apple Calendar join Google Calendar, and organizations gain server-enforced policy plus centrally managed Bedrock and Azure OpenAI access.diff --git a/electron-builder.json b/electron-builder.jsonindex 448bf0bf2..06dc007ac 100644--- a/electron-builder.json+++ b/electron-builder.json@@ -25,6 +25,8 @@"src/hooks/**/*","src/models/**/*","src/services/localReasoningBridge.js",+ "src/services/transcriptionBaseUrl.ts",+ "src/stores/policyRules.ts","src/types/**/*","src/utils.js","src/utils/**/*",diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsxindex 9fad6b4a3..2b33e00de 100644--- a/src/components/ControlPanel.tsx+++ b/src/components/ControlPanel.tsx@@ -612,6 +612,8 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelProcloudTranscriptionProvider: s.cloudTranscriptionProvider,cloudTranscriptionModel: s.cloudTranscriptionModel,cloudTranscriptionBaseUrl: s.cloudTranscriptionBaseUrl,+ cortiEnvironment: s.cortiEnvironment,+ cortiTenant: s.cortiTenant,parakeetModel: s.parakeetModel,whisperModel: s.whisperModel,preferredLanguage: s.preferredLanguage,diff --git a/src/components/TranscriptionModelPicker.tsx b/src/components/TranscriptionModelPicker.tsxindex 1de7423e4..405972fae 100644--- a/src/components/TranscriptionModelPicker.tsx+++ b/src/components/TranscriptionModelPicker.tsx@@ -30,6 +30,7 @@ import {isProviderAllowedByPolicy,reconcileCloudProviderSelection,shouldPersistProviderFallback,+ type TranscriptionPolicyContext,} from "../stores/policyRules";import { usePolicySnapshot } from "../hooks/usePolicy";import { getRemoteProviderIcon } from "../utils/providerIcons";@@ -190,7 +191,13 @@ function LocalModelCard({}interface TranscriptionModelPickerProps {+ /** Settings scope whose provider/model keys this picker edits. */+ transcriptionContext?: TranscriptionPolicyContext;selectedCloudProvider: string;+ /**+ * Policy reconciliation only — a user-driven pick goes through+ * switchCloudTranscriptionProvider so the outgoing model survives the swap.+ */onCloudProviderSelect: (providerId: string) => void;selectedCloudModel: string;onCloudModelSelect: (modelId: string) => void;@@ -327,6 +334,7 @@ function ModeToggle({ useLocalWhisper, onModeChange }: ModeToggleProps) {}export default function TranscriptionModelPicker({+ transcriptionContext = "dictation",selectedCloudProvider,onCloudProviderSelect,selectedCloudModel,@@ -345,6 +353,9 @@ export default function TranscriptionModelPicker({streamingOnly = false,}: TranscriptionModelPickerProps) {const { t } = useTranslation();+ const switchCloudTranscriptionProvider = useSettingsStore(+ (s) => s.switchCloudTranscriptionProvider+ );const openaiApiKey = useSettingsStore((s) => s.openaiApiKey);const setOpenaiApiKey = useSettingsStore((s) => s.setOpenaiApiKey);const groqApiKey = useSettingsStore((s) => s.groqApiKey);@@ -667,25 +678,16 @@ export default function TranscriptionModelPicker({[onModeChange]);- // Never writes cloudTranscriptionBaseUrl: that key is the Custom tab's only- // storage, and built-in providers resolve their endpoints from the registry- // at request time — writing it here destroyed the user's URL (#1459).+ // switchCloudTranscriptionProvider writes both the provider and the model for+ // this scope: it remembers the outgoing provider's model and restores the+ // incoming one. It never touches cloudTranscriptionBaseUrl — that key is the+ // Custom tab's only storage, and writing it here destroyed the URL (#1459).const handleCloudProviderChange = useCallback((providerId: string) => {if (!providerAllowed(providerId)) return;- onCloudProviderSelect(providerId);- const provider = cloudProviders.find((p) => p.id === providerId);-- if (providerId === "custom") {- onCloudModelSelect("whisper-1");- return;- }-- if (provider?.models?.length) {- onCloudModelSelect(provider.models[0].id);- }+ switchCloudTranscriptionProvider(transcriptionContext, providerId);},- [cloudProviders, onCloudProviderSelect, onCloudModelSelect, providerAllowed]+ [providerAllowed, switchCloudTranscriptionProvider, transcriptionContext]);const handleLocalProviderChange = useCallback(@@ -731,8 +733,7 @@ export default function TranscriptionModelPicker({for (const provider of cloudProviders) {const providerNormalized = normalizeBaseUrl(provider.baseUrl);if (normalized === providerNormalized) {- onCloudProviderSelect(provider.id);- onCloudModelSelect("whisper-1");+ switchCloudTranscriptionProvider(transcriptionContext, provider.id);break;}}@@ -741,8 +742,8 @@ export default function TranscriptionModelPicker({cloudTranscriptionBaseUrl,selectedCloudProvider,setCloudTranscriptionBaseUrl,- onCloudProviderSelect,- onCloudModelSelect,+ switchCloudTranscriptionProvider,+ transcriptionContext,cloudProviders,]);diff --git a/src/components/notes/UploadAudioView.tsx b/src/components/notes/UploadAudioView.tsxindex 4ed04dc43..894b835d9 100644--- a/src/components/notes/UploadAudioView.tsx+++ b/src/components/notes/UploadAudioView.tsx@@ -36,7 +36,11 @@ import { useAuth } from "../../hooks/useAuth";import { useUsage } from "../../hooks/useUsage";import { useSettings } from "../../hooks/useSettings";import { useStartOnboarding } from "../../hooks/useStartOnboarding";-import { getAllReasoningModels, getBatchTranscriptionModel } from "../../models/ModelRegistry";+import {+ getAllReasoningModels,+ getBatchTranscriptionModel,+ getTranscriptionProviders,+} from "../../models/ModelRegistry";import {useSettingsStore,selectIsCloudCleanupMode,@@ -59,7 +63,7 @@ import { getBaseLanguageCode } from "../../utils/languageSupport";import { isTranscriptionContextAllowed } from "../../stores/policyRules";import { usePolicyStore } from "../../stores/policyStore";import { usePolicySnapshot, useTranscriptionContextAllowed } from "../../hooks/usePolicy";-import { resolveCustomTranscriptionRoute } from "../../helpers/retryTranscriptionRouting";+import { resolveTranscriptionRoute } from "../../helpers/transcriptionRoute";type UploadState = "idle" | "selected" | "downloading" | "transcribing" | "complete" | "error";@@ -381,11 +385,11 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploaif (isSelfHosted) {if (!cancelled) setProviderReady(!!remoteTranscriptionUrl?.trim());} else if (cloudTranscriptionProvider === "custom") {- const customRoute = resolveCustomTranscriptionRoute({- provider: cloudTranscriptionProvider,- baseUrl: cloudTranscriptionBaseUrl,+ const route = resolveTranscriptionRoute({+ settings: { cloudTranscriptionProvider, cloudTranscriptionBaseUrl },+ providers: getTranscriptionProviders(),});- if (!cancelled) setProviderReady(customRoute?.kind === "custom");+ if (!cancelled) setProviderReady(route.transport !== "error");} else if (cloudTranscriptionProvider === "corti") {if (!cancelled) setProviderReady(!!(cortiClientId && cortiClientSecret));} else {@@ -489,7 +493,8 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: UploacloudTranscriptionProvider: cloudTranscriptionProvider as string,cloudTranscriptionBaseUrl: cloudTranscriptionBaseUrl || "",cloudTranscriptionModel,- language: getBaseLanguageCode(preferredLanguage) || "en",+ // Empty = auto-detect; the resolver supplies a default where one is required.+ language: getBaseLanguageCode(preferredLanguage) || "",cortiEnvironment,cortiTenant,transcriptionMode,diff --git a/src/components/notes/shared.ts b/src/components/notes/shared.tsindex edfb0cb67..b4bf3dc4f 100644--- a/src/components/notes/shared.ts+++ b/src/components/notes/shared.ts@@ -32,6 +32,7 @@ export const DOWNLOAD_ERROR_KEYS: Record<string, string> = {const TRANSCRIPTION_ERROR_KEYS: Record<string, string> = {NO_SPEECH_DETECTED: "noSpeechDetected",CHUNK_LOSS_EXCEEDED: "chunkLossExceeded",+ CUSTOM_ENDPOINT_INVALID: "customEndpointInvalid",};// A coded failure arrives either as a returned result (BYOK, local) or as adiff --git a/src/components/settings/MeetingSettings.tsx b/src/components/settings/MeetingSettings.tsxindex 98445f12d..af6d02def 100644--- a/src/components/settings/MeetingSettings.tsx+++ b/src/components/settings/MeetingSettings.tsx@@ -121,6 +121,7 @@ export function MeetingTranscriptionPanel() {const renderTranscriptionPicker = (mode: "cloud" | "local") => (<TranscriptionModelPickerstreamingOnly+ transcriptionContext="meeting"selectedCloudProvider={meetingCloudTranscriptionProvider}onCloudProviderSelect={setMeetingCloudTranscriptionProvider}selectedCloudModel={meetingCloudTranscriptionModel}diff --git a/src/components/settings/UploadSettings.tsx b/src/components/settings/UploadSettings.tsxindex 1c977cb33..c02ff090a 100644--- a/src/components/settings/UploadSettings.tsx+++ b/src/components/settings/UploadSettings.tsx@@ -99,6 +99,7 @@ export function UploadTranscriptionPanel() {const renderTranscriptionPicker = (mode: "cloud" | "local") => (<TranscriptionModelPicker+ transcriptionContext="upload"selectedCloudProvider={uploadCloudTranscriptionProvider}onCloudProviderSelect={setUploadCloudTranscriptionProvider}selectedCloudModel={uploadCloudTranscriptionModel}diff --git a/src/components/ui/TranscriptionItem.tsx b/src/components/ui/TranscriptionItem.tsxindex 0c946fece..2db02dc51 100644--- a/src/components/ui/TranscriptionItem.tsx+++ b/src/components/ui/TranscriptionItem.tsx@@ -84,7 +84,8 @@ export default function TranscriptionItem({const isConfigError =errorCode === "API_KEY_MISSING" ||errorCode === "INVALID_KEY" ||- errorCode === "MODEL_NOT_AVAILABLE";+ errorCode === "MODEL_NOT_AVAILABLE" ||+ errorCode === "CUSTOM_ENDPOINT_INVALID";const isLimitError = errorCode === "LIMIT_REACHED";const isOfflineError = errorCode === "OFFLINE";diff --git a/src/config/constants.ts b/src/config/constants.tsindex 029434c45..6b1d035da 100644--- a/src/config/constants.ts+++ b/src/config/constants.ts@@ -121,8 +121,6 @@ export const API_ENDPOINTS = {GEMINI: "https://generativelanguage.googleapis.com/v1beta",GROQ_BASE: "https://api.groq.com/openai/v1",CORTI_MODELS_BASE: "https://ai.eu.corti.app/v1",- XAI_BASE: "https://api.x.ai/v1",- MISTRAL_BASE: "https://api.mistral.ai/v1",OPENROUTER_BASE: "https://openrouter.ai/api/v1",TRANSCRIPTION_BASE: DEFAULT_TRANSCRIPTION_BASE,TRANSCRIPTION: buildApiUrl(DEFAULT_TRANSCRIPTION_BASE, "/audio/transcriptions"),diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex 549a48f16..0543cd613 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -1,13 +1,8 @@import ReasoningService from "../services/ReasoningService";import { PROVIDER_REGISTRY } from "../services/ai/inferenceProviders";-import { API_ENDPOINTS, buildApiUrl, normalizeBaseUrl } from "../config/constants";import logger from "../utils/logger";import { isBuiltInMicrophone } from "../utils/audioDeviceUtils";-import {- isSecureHttpEndpoint,- isAzureOpenAIEndpoint,- buildAzureTranscriptionUrl,-} from "../utils/urlUtils";+import { isAzureOpenAIEndpoint } from "../utils/urlUtils";import { withSessionRefresh } from "../lib/auth";import { getBaseLanguageCode, getLanguageLabel } from "../utils/languageSupport";import {@@ -59,10 +54,8 @@ import {getTranscriptionProviders,isOnlineParakeetModel,} from "../models/ModelRegistry";-import {- TINFOIL_PROXY_REQUIRED_ERROR,- isTinfoilInferenceUrl,-} from "../services/transcriptionBaseUrl";+import { TINFOIL_PROXY_REQUIRED_ERROR } from "../services/transcriptionBaseUrl";+import { resolveByokModel, resolveTranscriptionRoute } from "./transcriptionRoute.ts";import { shouldSkipTranscriptionApiKey } from "./transcriptionAuth";import {isSelfHostedTranscription,@@ -321,6 +314,54 @@ const STREAMING_PROVIDERS = {},};+// Batch providers that must transcribe via a main-process proxy (CORS,+// non-Bearer auth, OAuth, or attested transport) instead of a renderer fetch.+const PROXY_TRANSCRIPTION_PROVIDERS = {+ tinfoil: {+ displayName: "Tinfoil",+ ipc: () => window.electronAPI?.proxyTinfoilTranscription,+ buildPayload: ({ audioBuffer, language, dictionaryPrompt }) => ({+ audioBuffer,+ language,+ prompt: dictionaryPrompt || undefined,+ }),+ },+ mistral: {+ displayName: "Mistral",+ ipc: () => window.electronAPI?.proxyMistralTranscription,+ buildPayload: ({ audioBuffer, model, language, dictionaryPrompt }) => {+ const payload = { audioBuffer, model, language };+ const tokens = (dictionaryPrompt || "")+ .split(",")+ .flatMap((entry) => entry.trim().split(/\s+/))+ .filter(Boolean)+ .slice(0, 100);+ if (tokens.length > 0) payload.contextBias = tokens;+ return payload;+ },+ },+ xai: {+ displayName: "xAI",+ ipc: () => window.electronAPI?.proxyXaiTranscription,+ buildPayload: ({ audioBuffer, language, keyterms }) => {+ const payload = { audioBuffer, language: language !== "auto" ? language : undefined };+ if (keyterms.length > 0) payload.keyterms = keyterms;+ return payload;+ },+ },+ corti: {+ displayName: "Corti",+ ipc: () => window.electronAPI?.proxyCortiTranscription,+ buildPayload: ({ audioBuffer, language, apiSettings }) => ({+ audioBuffer,+ // Corti requires a concrete primaryLanguage; default to English when auto-detecting+ language: language || "en",+ environment: apiSettings.cortiEnvironment || "us",+ tenant: (apiSettings.cortiTenant || "").trim() || "base",+ }),+ },+};+class AudioManager {constructor() {this.mediaRecorder = null;@@ -386,9 +427,6 @@ class AudioManager {this.micStreamHold.drop();};navigator.mediaDevices?.addEventListener?.("devicechange", this._onDeviceChange);- this.cachedTranscriptionEndpoint = null;- this.cachedEndpointProvider = null;- this.cachedEndpointBaseUrl = null;this.recordingStartTime = null;this.reasoningAvailabilityCache = { value: false, expiresAt: 0 };this.cachedReasoningPreference = null;@@ -2919,18 +2957,27 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);const optimizedAudio = audioBlob;// Dispatch before endpoint resolution (which defaults to OpenAI and would leak- // the key). Self-hosted wins, so a leftover "tinfoil" provider isn't diverted here.- if (provider === "tinfoil" && !isSelfHostedTranscription(apiSettings)) {- if (!window.electronAPI?.proxyTinfoilTranscription) {- throw new Error("Tinfoil transcription is unavailable in this window");+ // the key). Self-hosted wins, so a leftover proxied provider isn't diverted here.+ const proxySpec = PROXY_TRANSCRIPTION_PROVIDERS[provider];+ if (proxySpec && !isSelfHostedTranscription(apiSettings)) {+ const call = proxySpec.ipc();+ if (!call) {+ throw new Error(`${proxySpec.displayName} transcription is unavailable in this window`);}- const dictionaryPrompt = this.getWhisperPrompt(apiSettings);const apiCallStart = performance.now();- const result = await window.electronAPI.proxyTinfoilTranscription({- audioBuffer: await optimizedAudio.arrayBuffer(),- language,- prompt: dictionaryPrompt || undefined,- });+ const result = await call(+ proxySpec.buildPayload({+ audioBuffer: await optimizedAudio.arrayBuffer(),+ model,+ language,+ apiSettings,+ dictionaryPrompt: this.getWhisperPrompt(apiSettings),+ keyterms: this.getKeyterms()+ .map((t) => t.trim().slice(0, 50))+ .filter(Boolean)+ .slice(0, 100),+ })+ );if (result?.error) {const err = new Error(result.error);if (result.code) err.code = result.code;@@ -2939,17 +2986,17 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}const proxyText = result?.text;if (!proxyText?.trim()) {- throw new Error("No text transcribed - Tinfoil response was empty");+ throw new Error(`No text transcribed - ${proxySpec.displayName} response was empty`);}if (this.isDictionaryEcho(proxyText)) {throw dictionaryEchoError();}timings.transcriptionProcessingDurationMs = Math.round(performance.now() - apiCallStart);const reasoningStart = performance.now();- const text = await this.processTranscription(proxyText, "tinfoil");+ const text = await this.processTranscription(proxyText, provider);timings.reasoningProcessingDurationMs = Math.round(performance.now() - reasoningStart);- const source = (await this.isReasoningAvailable()) ? "tinfoil-reasoned" : "tinfoil";+ const source = (await this.isReasoningAvailable()) ? `${provider}-reasoned` : provider;return { success: true, text, rawText: proxyText, source, timings };}@@ -3017,125 +3064,11 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);formData.append("stream", "true");}- const isCustomEndpoint =- provider === "custom" ||- (!endpoint.includes("api.openai.com") &&- !endpoint.includes("api.groq.com") &&- !endpoint.includes("api.x.ai") &&- !endpoint.includes("api.mistral.ai"));-const apiCallStart = performance.now();- // Mistral uses x-api-key auth (not Bearer) and doesn't allow browser CORS — proxy through main process- if (provider === "mistral" && window.electronAPI?.proxyMistralTranscription) {- const audioBuffer = await optimizedAudio.arrayBuffer();- const proxyData = { audioBuffer, model, language };-- if (dictionaryPrompt) {- const tokens = dictionaryPrompt- .split(",")- .flatMap((entry) => entry.trim().split(/\s+/))- .filter(Boolean)- .slice(0, 100);- if (tokens.length > 0) {- proxyData.contextBias = tokens;- }- }-- const result = await window.electronAPI.proxyMistralTranscription(proxyData);- const proxyText = result?.text;-- if (proxyText && proxyText.trim().length > 0) {- if (this.isDictionaryEcho(proxyText)) {- throw dictionaryEchoError();- }- timings.transcriptionProcessingDurationMs = Math.round(performance.now() - apiCallStart);- const rawText = proxyText;- const reasoningStart = performance.now();- const text = await this.processTranscription(proxyText, "mistral");- timings.reasoningProcessingDurationMs = Math.round(performance.now() - reasoningStart);-- const source = (await this.isReasoningAvailable()) ? "mistral-reasoned" : "mistral";- return { success: true, text, rawText, source, timings };- }-- throw new Error("No text transcribed - Mistral response was empty");- }-- // xAI STT has a non-OpenAI-compatible API — proxy through main process. See #910.- if (provider === "xai" && window.electronAPI?.proxyXaiTranscription) {- const audioBuffer = await optimizedAudio.arrayBuffer();- const proxyData = { audioBuffer, language: language !== "auto" ? language : undefined };-- const keyterms = this.getKeyterms()- .map((t) => t.trim().slice(0, 50))- .filter(Boolean)- .slice(0, 100);- if (keyterms.length > 0) {- proxyData.keyterms = keyterms;- }-- const result = await window.electronAPI.proxyXaiTranscription(proxyData);- const proxyText = result?.text;-- if (proxyText && proxyText.trim().length > 0) {- if (this.isDictionaryEcho(proxyText)) {- throw dictionaryEchoError();- }- timings.transcriptionProcessingDurationMs = Math.round(performance.now() - apiCallStart);- const rawText = proxyText;- const reasoningStart = performance.now();- const text = await this.processTranscription(proxyText, "xai");- timings.reasoningProcessingDurationMs = Math.round(performance.now() - reasoningStart);-- const source = (await this.isReasoningAvailable()) ? "xai-reasoned" : "xai";- return { success: true, text, rawText, source, timings };- }-- throw new Error("No text transcribed - xAI response was empty");- }-- // Corti uses OAuth client credentials and an interaction-based REST flow — proxy through main process- if (provider === "corti" && window.electronAPI?.proxyCortiTranscription) {- const audioBuffer = await optimizedAudio.arrayBuffer();- const proxyData = {- audioBuffer,- // Corti requires a concrete primaryLanguage; default to English when auto-detecting- language: language || "en",- environment: apiSettings.cortiEnvironment || "us",- tenant: (apiSettings.cortiTenant || "").trim() || "base",- };-- const result = await window.electronAPI.proxyCortiTranscription(proxyData);- const proxyText = result?.text;-- if (proxyText && proxyText.trim().length > 0) {- if (this.isDictionaryEcho(proxyText)) {- throw dictionaryEchoError();- }- timings.transcriptionProcessingDurationMs = Math.round(performance.now() - apiCallStart);- const rawText = proxyText;- const reasoningStart = performance.now();- const text = await this.processTranscription(proxyText, "corti");- timings.reasoningProcessingDurationMs = Math.round(performance.now() - reasoningStart);-- const source = (await this.isReasoningAvailable()) ? "corti-reasoned" : "corti";- return { success: true, text, rawText, source, timings };- }-- throw new Error("No text transcribed - Corti response was empty");- }-logger.debug("Making transcription API request",- {- endpoint,- shouldStream,- model,- provider,- isCustomEndpoint,- hasApiKey: !!apiKey,- },+ { endpoint, shouldStream, model, provider, hasApiKey: !!apiKey },"transcription");@@ -3348,9 +3281,12 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);if (fallbackError.selectionEditFatal) {throw fallbackError;}- throw new Error(+ const wrapped = new Error(`OpenAI API failed: ${error.message}. Local fallback also failed: ${fallbackError.message}`);+ if (error.code) wrapped.code = error.code;+ if (error.messageKey) wrapped.messageKey = error.messageKey;+ throw wrapped;}}@@ -3364,262 +3300,46 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);const selfHostedModel = resolveSelfHostedTranscriptionModel(s);if (selfHostedModel) return selfHostedModel;const provider = s.cloudTranscriptionProvider || "openai";- const trimmedModel = (s.cloudTranscriptionModel || "").trim();-- // For custom provider, use whatever model is set (or fallback to whisper-1)- if (provider === "custom") {- return trimmedModel || "whisper-1";- }-+ // Tinfoil pins its batch model in the registry rather than in settings.if (provider === "tinfoil") {return getBatchTranscriptionModel("tinfoil");}-- // Validate model matches provider to handle settings migration- if (trimmedModel) {- const isGroqModel = trimmedModel.startsWith("whisper-large-v3");- const isOpenAIModel = trimmedModel.startsWith("gpt-4o") || trimmedModel === "whisper-1";- const isMistralModel = trimmedModel.startsWith("voxtral-");- const isCortiModel = trimmedModel.startsWith("corti-");-- if (provider === "groq" && isGroqModel) {- return trimmedModel;- }- if (provider === "openai" && isOpenAIModel) {- return trimmedModel;- }- if (provider === "mistral" && isMistralModel) {- return trimmedModel;- }- if (provider === "corti" && isCortiModel) {- return trimmedModel;- }- // Model doesn't match provider - fall through to default- }-- // Return provider-appropriate default- if (provider === "groq") return "whisper-large-v3-turbo";- if (provider === "xai") return "grok-stt";- if (provider === "mistral") return "voxtral-mini-latest";- if (provider === "corti") return "corti-transcribe";- return "gpt-4o-mini-transcribe";+ return resolveByokModel(provider, s.cloudTranscriptionModel);} catch (error) {return "gpt-4o-mini-transcribe";}}+ // Local-vs-cloud is decided upstream, so useLocalWhisper is forced off here:+ // the local→cloud fallback resolves its cloud endpoint through this too.getTranscriptionEndpoint(deploymentName = "") {- const s = getSettings();- const currentProvider = s.cloudTranscriptionProvider || "openai";-- // Backstop against the OpenAI-default leak: Tinfoil goes through the main-process- // proxy, never here — except self-hosted, which resolves its remote URL below.- if (currentProvider === "tinfoil" && !isSelfHostedTranscription(s)) {- throw new Error(TINFOIL_PROXY_REQUIRED_ERROR);- }-- const currentBaseUrl = s.cloudTranscriptionBaseUrl || "";- const transcriptionMode = s.transcriptionMode || "";- const remoteUrl = (s.remoteTranscriptionUrl || "").trim();- const deployment = (deploymentName || "").trim();-- const isSelfHosted = isSelfHostedTranscription(s);- const isCustomEndpoint = isSelfHosted || currentProvider === "custom";- const isManagedCustomEndpoint =- currentProvider === "custom" && usePolicyStore.getState().status === "managed";-- const rejectManagedCustomEndpoint = () => {- const error = new Error("Transcription is restricted by your organization.");- error.code = "POLICY_RESTRICTED";- error.messageKey = "common.policyTranscriptionRestricted";+ const route = resolveTranscriptionRoute({+ settings: { ...getSettings(), useLocalWhisper: false },+ policy: usePolicyStore.getState(),+ providers: getTranscriptionProviders(),+ request: { model: deploymentName },+ });+ if (route.transport === "error") {+ const error = new Error(route.message);+ if (route.code) error.code = route.code;+ if (route.messageKey) error.messageKey = route.messageKey;throw error;- };-- // Never fall back to the cloud default for self-hosted — fail closed instead.- if (isSelfHosted) {- const normalizedRemote = normalizeBaseUrl(remoteUrl);- if (!normalizedRemote || !isSecureHttpEndpoint(normalizedRemote)) {- throw new Error("Self-hosted transcription URL is invalid or unsupported");- }- }-- // A managed Custom-only fallback has no safe implicit destination. Reusing- // OpenAI here would send audio and credentials to a policy-denied provider.- if (isManagedCustomEndpoint && !currentBaseUrl.trim()) {- rejectManagedCustomEndpoint();}-- // The provider-id guard above can't catch a Custom base URL that points at- // Tinfoil's inference host (e.g. persisted by the pre-#1459 tab clobber) —- // check the URL too. Must stay outside the try below: its catch swallows- // errors into the OpenAI default endpoint.- if (- currentProvider === "custom" &&- !isSelfHosted &&- isTinfoilInferenceUrl(currentBaseUrl, getTranscriptionProviders())- ) {- throw new Error(TINFOIL_PROXY_REQUIRED_ERROR);- }-- if (- this.cachedTranscriptionEndpoint &&- (this.cachedEndpointProvider !== currentProvider ||- this.cachedEndpointDeployment !== deployment ||- this.cachedEndpointBaseUrl !== currentBaseUrl ||- this.cachedEndpointMode !== transcriptionMode ||- this.cachedEndpointRemoteUrl !== remoteUrl)- ) {- logger.debug(- "STT endpoint cache invalidated",- {- previousProvider: this.cachedEndpointProvider,- newProvider: currentProvider,- previousBaseUrl: this.cachedEndpointBaseUrl,- newBaseUrl: currentBaseUrl,- previousMode: this.cachedEndpointMode,- newMode: transcriptionMode,- previousRemoteUrl: this.cachedEndpointRemoteUrl,- newRemoteUrl: remoteUrl,- },- "transcription"+ if (route.transport !== "http-batch") {+ // Proxied providers are dispatched before endpoint resolution; reaching+ // here means that guard was bypassed — never fall open to a default.+ throw new Error(+ route.provider === "tinfoil"+ ? TINFOIL_PROXY_REQUIRED_ERROR+ : `${route.provider} transcription must go through the main-process proxy`);- this.cachedTranscriptionEndpoint = null;- }-- if (this.cachedTranscriptionEndpoint) {- return this.cachedTranscriptionEndpoint;- }-- try {- let base;- if (isSelfHosted) {- base = remoteUrl;- } else if (currentProvider === "custom") {- base = currentBaseUrl.trim() || API_ENDPOINTS.TRANSCRIPTION_BASE;- } else if (currentProvider === "groq") {- base = API_ENDPOINTS.GROQ_BASE;- } else if (currentProvider === "xai") {- base = API_ENDPOINTS.XAI_BASE;- } else if (currentProvider === "mistral") {- base = API_ENDPOINTS.MISTRAL_BASE;- } else {- // OpenAI or other standard providers- base = API_ENDPOINTS.TRANSCRIPTION_BASE;- }-- const normalizedBase = normalizeBaseUrl(base);-- logger.debug(- "STT endpoint resolution",- {- provider: currentProvider,- mode: transcriptionMode,- isSelfHosted,- isCustomEndpoint,- rawBaseUrl: currentBaseUrl,- remoteUrl,- normalizedBase,- defaultBase: API_ENDPOINTS.TRANSCRIPTION_BASE,- },- "transcription"- );-- const cacheResult = (endpoint) => {- this.cachedTranscriptionEndpoint = endpoint;- this.cachedEndpointProvider = currentProvider;- this.cachedEndpointBaseUrl = currentBaseUrl;- this.cachedEndpointMode = transcriptionMode;- this.cachedEndpointRemoteUrl = remoteUrl;- this.cachedEndpointDeployment = deployment;-- logger.debug(- "STT endpoint resolved",- {- endpoint,- provider: currentProvider,- isCustomEndpoint,- usingDefault: endpoint === API_ENDPOINTS.TRANSCRIPTION,- },- "transcription"- );-- return endpoint;- };-- if (!normalizedBase) {- logger.debug(- "STT endpoint: using default (normalization failed)",- { rawBase: base },- "transcription"- );- return cacheResult(API_ENDPOINTS.TRANSCRIPTION);- }-- // Only validate HTTPS for custom endpoints (known providers are already HTTPS)- if (isCustomEndpoint && !isSecureHttpEndpoint(normalizedBase)) {- if (isManagedCustomEndpoint) {- rejectManagedCustomEndpoint();- }- logger.warn(- "STT endpoint: HTTPS required, falling back to default",- { attemptedUrl: normalizedBase },- "transcription"- );- return cacheResult(API_ENDPOINTS.TRANSCRIPTION);- }-- let endpoint;- if (isCustomEndpoint && isAzureOpenAIEndpoint(normalizedBase)) {- // Azure OpenAI routes by deployment in the URL path and requires an- // api-version query string — the plain {base}/audio/transcriptions- // shape returns DeploymentNotFound. Build the deployment-style URL.- // The api-version defaults to a transcribe-capable preview; a user can- // override it by appending ?api-version=... to their endpoint URL.- // Built from the raw base — normalization strips the /audio/transcriptions- // suffix that marks a deployment the user pinned.- const azureUrl = buildAzureTranscriptionUrl(base, deployment);- if (azureUrl) {- endpoint = azureUrl;- logger.debug(- "STT endpoint: built Azure deployment URL",- { base, deployment, endpoint },- "transcription"- );- } else {- endpoint = buildApiUrl(normalizedBase, "/audio/transcriptions");- logger.warn(- "STT endpoint: Azure host detected but no deployment name; falling back to default path",- { base: normalizedBase, endpoint },- "transcription"- );- }- } else if (/\/audio\/(transcriptions|translations)$/i.test(normalizedBase)) {- endpoint = normalizedBase;- logger.debug("STT endpoint: using full path from config", { endpoint }, "transcription");- } else {- endpoint = buildApiUrl(normalizedBase, "/audio/transcriptions");- logger.debug(- "STT endpoint: appending /audio/transcriptions to base",- { base: normalizedBase, endpoint },- "transcription"- );- }-- return cacheResult(endpoint);- } catch (error) {- logger.error(- "STT endpoint resolution failed",- { error: error.message, stack: error.stack },- "transcription"- );- if (isSelfHosted || isManagedCustomEndpoint) throw error;- this.cachedTranscriptionEndpoint = API_ENDPOINTS.TRANSCRIPTION;- this.cachedEndpointProvider = currentProvider;- this.cachedEndpointBaseUrl = currentBaseUrl;- this.cachedEndpointMode = transcriptionMode;- this.cachedEndpointRemoteUrl = remoteUrl;- return API_ENDPOINTS.TRANSCRIPTION;}+ logger.debug(+ "STT endpoint resolved",+ { endpoint: route.endpoint, provider: route.provider },+ "transcription"+ );+ return route.endpoint;}async safePaste(text, options = {}) {diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 3025df479..5c95bce04 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -18,6 +18,32 @@ const {toPolicyFailure,} = require("./policyResponseError");const { classifyAndLog } = require("./networkErrors");+// The renderer's ModelRegistry is not main-loadable; the raw registry data is+// packaged, and the route resolver only needs {id, baseUrl} per provider.+const transcriptionProviderBaseUrls = () =>+ require("../models/modelRegistryData.json").transcriptionProviders;+// ipcMain.handle keeps only the message when a promise rejects, dropping custom+// props — proxy handlers return {error, code, messageKey} so the renderer can+// rebuild the error.+const serializeIpcError =+ (fn) =>+ async (...args) => {+ try {+ return await fn(...args);+ } catch (error) {+ return { error: error.message, code: error.code, messageKey: error.messageKey };+ }+ };+// Which diarization dialect a resolved endpoint speaks, for Custom endpoints+// that front a known provider. Null when the host offers no known dialect.+const diarizationHost = (endpoint) => {+ try {+ const host = new URL(endpoint).hostname;+ if (host === "mistral.ai" || host.endsWith(".mistral.ai")) return "mistral";+ if (host === "openai.com" || host.endsWith(".openai.com")) return "openai";+ } catch {}+ return null;+};const { resolveLocalServerNeeds } = require("./localServerPolicy");const GnomeShortcutManager = require("./gnomeShortcut");const HyprlandShortcutManager = require("./hyprlandShortcut");@@ -82,35 +108,6 @@ const MISTRAL_TRANSCRIPTION_URL = "https://api.mistral.ai/v1/audio/transcriptionconst XAI_STT_URL = "https://api.x.ai/v1/stt";-// xAI STT supports 25 languages; language must be in this set to enable ITN via format=true-const XAI_STT_LANGUAGES = new Set([- "ar",- "cs",- "da",- "de",- "en",- "es",- "fa",- "fil",- "fr",- "hi",- "id",- "it",- "ja",- "ko",- "mk",- "ms",- "nl",- "pl",- "pt",- "ro",- "ru",- "sv",- "th",- "tr",- "vi",-]);-// Debounce delay: wait for user to stop typing before processing correctionsconst AUTO_LEARN_DEBOUNCE_MS = 1500;@@ -880,23 +877,6 @@ class IPCHandlers {}}- _resolveByokModel(provider, configuredModel) {- const trimmed = (configuredModel || "").trim();- if (provider === "custom") return trimmed || "whisper-1";- if (trimmed) {- const isGroq = trimmed.startsWith("whisper-large-v3");- const isOpenAI = trimmed.startsWith("gpt-4o") || trimmed === "whisper-1";- const isMistral = trimmed.startsWith("voxtral-");- if (provider === "groq" && isGroq) return trimmed;- if (provider === "openai" && isOpenAI) return trimmed;- if (provider === "mistral" && isMistral) return trimmed;- }- if (provider === "groq") return "whisper-large-v3-turbo";- if (provider === "xai") return "grok-stt";- if (provider === "mistral") return "voxtral-mini-latest";- return "gpt-4o-mini-transcribe";- }-_cleanupTextEditMonitor() {if (this._autoLearnDebounceTimer) {clearTimeout(this._autoLearnDebounceTimer);@@ -3566,7 +3546,7 @@ class IPCHandlers {ipcMain.handle("proxy-xai-transcription",- async (event, { audioBuffer, language, keyterms }) => {+ serializeIpcError(async (event, { audioBuffer, language, keyterms }) => {const apiKey = this.environmentManager.getXaiKey();if (!apiKey) {throw new Error("xAI API key not configured");@@ -3575,6 +3555,7 @@ class IPCHandlers {const formData = new FormData();const audioBlob = new Blob([Buffer.from(audioBuffer)], { type: "audio/webm" });formData.append("file", audioBlob, "audio.webm");+ const { XAI_STT_LANGUAGES } = await import("./transcriptionRoute.ts");if (language && language !== "auto" && XAI_STT_LANGUAGES.has(language)) {formData.append("language", language);formData.append("format", "true");@@ -3597,12 +3578,12 @@ class IPCHandlers {}return await response.json();- }+ }));ipcMain.handle("proxy-mistral-transcription",- async (event, { audioBuffer, model, language, contextBias }) => {+ serializeIpcError(async (event, { audioBuffer, model, language, contextBias }) => {const apiKey = this.environmentManager.getMistralKey();if (!apiKey) {throw new Error("Mistral API key not configured");@@ -3635,7 +3616,7 @@ class IPCHandlers {}return await response.json();- }+ }));ipcMain.handle("get-corti-client-id", async () => {@@ -3656,7 +3637,7 @@ class IPCHandlers {ipcMain.handle("proxy-corti-transcription",- async (event, { audioBuffer, language, environment, tenant }) => {+ serializeIpcError(async (event, { audioBuffer, language, environment, tenant }) => {const clientId = this.environmentManager.getCortiClientId();const clientSecret = this.environmentManager.getCortiClientSecret();if (!clientId || !clientSecret) {@@ -3664,7 +3645,7 @@ class IPCHandlers {}const { transcribeAudio } = require("./cortiTranscription");- return transcribeAudio({+ return await transcribeAudio({environment,tenant,clientId,@@ -3672,7 +3653,7 @@ class IPCHandlers {audioBuffer,language,});- }+ }));ipcMain.handle("get-tinfoil-chat-models", async () => {@@ -3682,22 +3663,16 @@ class IPCHandlers {// Enclave attestation is Node-only, so batch transcription is proxied through main.ipcMain.handle("proxy-tinfoil-transcription",- async (event, { audioBuffer, language, prompt }) => {- try {- return await transcribeWithTinfoil({- audioBuffer: Buffer.from(audioBuffer),- fileName: "audio.webm",- contentType: "audio/webm",- language,- prompt,- apiKey: this.environmentManager.getTinfoilKey(),- });- } catch (error) {- // ipcMain.handle keeps only the message when a promise rejects, dropping- // custom props — return the code so the renderer can rebuild the error.- return { error: error.message, code: error.code, messageKey: error.messageKey };- }- }+ serializeIpcError(async (event, { audioBuffer, language, prompt }) => {+ return await transcribeWithTinfoil({+ audioBuffer: Buffer.from(audioBuffer),+ fileName: "audio.webm",+ contentType: "audio/webm",+ language,+ prompt,+ apiKey: this.environmentManager.getTinfoilKey(),+ });+ }));ipcMain.handle("get-custom-transcription-key", async () => {@@ -5066,25 +5041,39 @@ class IPCHandlers {preferredLanguage && preferredLanguage !== "auto"? preferredLanguage.split("-")[0]: undefined;- const { resolveCustomTranscriptionRoute, resolveSelfHostedRetryRoute } =- await import("./retryTranscriptionRouting.js");- const selfHostedRoute = resolveSelfHostedRetryRoute(settings);+ const { resolveTranscriptionRoute } = await import("./transcriptionRoute.ts");+ // Renderer pre-flight owns policy; retry re-routes stored audio through+ // whatever is selected NOW.+ const route = resolveTranscriptionRoute({+ settings: settings || {},+ providers: transcriptionProviderBaseUrls(),+ request: { effectiveLanguage: language },+ });- if (selfHostedRoute?.kind === "configuration-error") {- throw new Error(selfHostedRoute.error);+ // An error route is fatal unless OpenWhispr cloud is selected — a+ // leftover BYOK misconfiguration must not block the cloud pipeline.+ if (+ route.transport === "error" &&+ (settings?.transcriptionMode === "self-hosted" ||+ settings?.cloudTranscriptionMode !== "openwhispr")+ ) {+ const err = new Error(route.message);+ if (route.code) err.code = route.code;+ if (route.messageKey) err.messageKey = route.messageKey;+ throw err;}- if (selfHostedRoute?.kind === "self-hosted") {+ if (route.transport === "http-batch" && route.provider === "self-hosted") {const formData = new FormData();formData.append("file", new Blob([buffer], { type: "audio/webm" }), "audio.webm");- if (selfHostedRoute.model) {- formData.append("model", selfHostedRoute.model);+ if (route.model) {+ formData.append("model", route.model);}- if (language) {- formData.append("language", language);+ if (route.language) {+ formData.append("language", route.language);}- const response = await proxyFetch(selfHostedRoute.endpoint, {+ const response = await proxyFetch(route.endpoint, {method: "POST",body: formData,});@@ -5097,10 +5086,10 @@ class IPCHandlers {result = {text: data.text,source: "self-hosted",- model: selfHostedRoute.model,+ model: route.model,};}- } else if (settings?.useLocalWhisper) {+ } else if (route.transport === "local") {if (settings.localTranscriptionProvider === "nvidia") {const model =settings.parakeetModel || process.env.PARAKEET_MODEL || "parakeet-tdt-0.6b-v3";@@ -5162,46 +5151,54 @@ class IPCHandlers {}}}- } else if (settings?.cloudTranscriptionProvider === "tinfoil") {+ } else if (route.transport === "proxied" && route.provider === "tinfoil") {// Attested transport, so this can't reuse the generic fetch below.const { text, model } = await transcribeWithTinfoil({audioBuffer: buffer,fileName: "audio.webm",contentType: "audio/webm",- language,+ language: route.language,apiKey: this.environmentManager.getTinfoilKey(),});if (text) result = { text, source: "tinfoil", model };+ } else if (route.transport === "proxied" && route.provider === "corti") {+ // Corti uses OAuth + an interaction-based REST flow, so it can't use+ // the generic fetch below.+ const clientId = this.environmentManager.getCortiClientId();+ const clientSecret = this.environmentManager.getCortiClientSecret();+ if (!clientId || !clientSecret) {+ throw new Error("Corti credentials not configured. Add them in Settings.");+ }+ const { transcribeAudio } = require("./cortiTranscription");+ const { text } = await transcribeAudio({+ environment: route.cortiEnvironment,+ tenant: route.cortiTenant,+ clientId,+ clientSecret,+ audioBuffer: buffer,+ language: route.language,+ });+ if (text) result = { text, source: "corti", model: route.model };} else {- const provider = settings?.cloudTranscriptionProvider || "openai";- const model = this._resolveByokModel(provider, settings?.cloudTranscriptionModel);-- let apiKey, endpoint;- if (provider === "groq") {- apiKey = this.environmentManager.getGroqKey();- endpoint = "https://api.groq.com/openai/v1/audio/transcriptions";- } else if (provider === "xai") {- apiKey = this.environmentManager.getXaiKey();- endpoint = XAI_STT_URL;- } else if (provider === "mistral") {- apiKey = this.environmentManager.getMistralKey();- endpoint = MISTRAL_TRANSCRIPTION_URL;- } else if (provider === "custom") {- apiKey = this.environmentManager.getCustomTranscriptionKey();- const customRoute = resolveCustomTranscriptionRoute({- provider,- baseUrl: settings?.cloudTranscriptionBaseUrl,- });- if (customRoute?.kind !== "custom") {- throw new Error(- customRoute?.error || "Custom transcription endpoint is not configured"- );- }- endpoint = customRoute.endpoint;- } else {- apiKey = this.environmentManager.getOpenAIKey();- endpoint = "https://api.openai.com/v1/audio/transcriptions";- }+ // mistral/xai have no OpenAI-compatible endpoint — main talks to them+ // directly; everything else consumes the route endpoint as-is.+ const provider = route.provider;+ const endpoint =+ provider === "mistral"+ ? MISTRAL_TRANSCRIPTION_URL+ : provider === "xai"+ ? XAI_STT_URL+ : route.endpoint;+ const apiKey =+ provider === "mistral"+ ? this.environmentManager.getMistralKey()+ : provider === "xai"+ ? this.environmentManager.getXaiKey()+ : route.auth.keyRef === "custom"+ ? this.environmentManager.getCustomTranscriptionKey()+ : route.auth.keyRef === "groq"+ ? this.environmentManager.getGroqKey()+ : this.environmentManager.getOpenAIKey();if (!apiKey && provider !== "custom") {throw new Error(`${provider} API key not configured`);}@@ -5209,20 +5206,24 @@ class IPCHandlers {const formData = new FormData();formData.append("file", new Blob([buffer], { type: "audio/webm" }), "audio.webm");if (provider === "xai") {- // xAI STT does not accept a model field; language only when in supported set- if (language && XAI_STT_LANGUAGES.has(language)) {- formData.append("language", language);+ // xAI STT does not accept a model field; the route pre-filters language+ if (route.language) {+ formData.append("language", route.language);formData.append("format", "true");}} else {- formData.append("model", model);- if (language) formData.append("language", language);+ formData.append("model", route.model);+ if (route.language) formData.append("language", route.language);}const headers = {};if (provider === "mistral") {headers["x-api-key"] = apiKey;} else if (apiKey) {- headers.Authorization = `Bearer ${apiKey}`;+ if (route.transport === "http-batch" && route.auth.scheme === "azure-api-key") {+ headers["api-key"] = apiKey;+ } else {+ headers.Authorization = `Bearer ${apiKey}`;+ }}const response = await proxyFetch(endpoint, { method: "POST", headers, body: formData });@@ -5232,7 +5233,7 @@ class IPCHandlers {}const data = await response.json();if (data?.text) {- result = { text: data.text, source: provider, model };+ result = { text: data.text, source: provider, model: route.model };}}@@ -8195,7 +8196,6 @@ class IPCHandlers {}) => {const fs = require("fs");- const BYOK_FILE_SIZE_LIMIT = 25 * 1024 * 1024; // 25 MBtry {if (typeof filePath !== "string") {return { success: false, error: "Invalid file path" };@@ -8203,29 +8203,37 @@ class IPCHandlers {const realByok = resolveAllowedAudioPath(filePath);if (!realByok) return { success: false, error: "File path not allowed" };- const { resolveCustomTranscriptionRoute, resolveSelfHostedRetryRoute } =- await import("./retryTranscriptionRouting.js");- const selfHostedRoute = resolveSelfHostedRetryRoute({- transcriptionMode,- remoteTranscriptionUrl,- remoteTranscriptionModel,+ const { resolveTranscriptionRoute } = await import("./transcriptionRoute.ts");+ const route = resolveTranscriptionRoute({+ settings: {+ transcriptionMode,+ remoteTranscriptionUrl,+ remoteTranscriptionModel,+ cloudTranscriptionProvider: provider,+ cloudTranscriptionModel: model,+ cloudTranscriptionBaseUrl: baseUrl,+ cortiEnvironment: environment,+ cortiTenant: tenant,+ },+ providers: transcriptionProviderBaseUrls(),+ request: { effectiveLanguage: language || undefined },});- // Fail closed: a misconfigured self-hosted setup must never fall through to BYOK.- if (selfHostedRoute?.kind === "configuration-error") {- return { success: false, error: selfHostedRoute.error };+ // Fail closed: a misconfigured route must never fall through to a default.+ if (route.transport === "error") {+ return { success: false, error: route.message, code: route.code };}- if (selfHostedRoute?.kind === "self-hosted") {+ if (route.transport === "http-batch" && route.provider === "self-hosted") {// User's own server, so the 25 MB third-party cap does not apply.const ext = path.extname(realByok).toLowerCase().replace(".", "");const { body, boundary } = buildMultipartBody(fs.readFileSync(realByok),path.basename(realByok),AUDIO_MIME_TYPES[ext] || "audio/mpeg",- { model: selfHostedRoute.model, language }+ { model: route.model, language: route.language });- const data = await postMultipart(new URL(selfHostedRoute.endpoint), body, boundary);+ const data = await postMultipart(new URL(route.endpoint), body, boundary);if (data.statusCode !== 200) {throw new Error(data.data?.error?.message ||@@ -8237,14 +8245,14 @@ class IPCHandlers {}const fileSize = fs.statSync(realByok).size;- if (fileSize > BYOK_FILE_SIZE_LIMIT) {+ if (route.sizeCapBytes && fileSize > route.sizeCapBytes) {return {success: false,error: "File too large. Maximum size for bring-your-own-key is 25 MB.",};}- if (provider === "corti") {+ if (route.transport === "proxied" && route.provider === "corti") {const clientId = this.environmentManager.getCortiClientId();const clientSecret = this.environmentManager.getCortiClientSecret();if (!clientId || !clientSecret) {@@ -8252,85 +8260,75 @@ class IPCHandlers {}const { transcribeAudio } = require("./cortiTranscription");const { text } = await transcribeAudio({- environment,- tenant,+ environment: route.cortiEnvironment,+ tenant: route.cortiTenant,clientId,clientSecret,audioBuffer: fs.readFileSync(realByok),- language: language || "en",+ language: route.language,});return { success: true, text };}- if (provider === "tinfoil") {+ if (route.transport === "proxied" && route.provider === "tinfoil") {const ext = path.extname(realByok).toLowerCase().replace(".", "");const { text } = await transcribeWithTinfoil({audioBuffer: fs.readFileSync(realByok),fileName: path.basename(realByok),contentType: AUDIO_MIME_TYPES[ext] || "audio/mpeg",- language,+ language: route.language,apiKey: this.environmentManager.getTinfoilKey(),});return { success: true, text };}- if (!apiKey && provider !== "custom") {+ if (!apiKey && route.provider !== "custom") {throw new Error("No API key configured. Add your key in Settings.");}- const customRoute = resolveCustomTranscriptionRoute({ provider, baseUrl });- if (customRoute?.kind === "configuration-error") {- throw new Error(customRoute.error);- }- if (!baseUrl && provider !== "xai") {- throw new Error("No transcription endpoint configured.");- }const audioBuffer = fs.readFileSync(realByok);const ext = path.extname(realByok).toLowerCase().replace(".", "");const contentType = AUDIO_MIME_TYPES[ext] || "audio/mpeg";const fileName = path.basename(realByok);+ // mistral/xai have no OpenAI-compatible endpoint — talk to them+ // directly; everything else consumes the route endpoint as-is.let transcriptionUrl;const multipartFields = {};- if (provider === "xai") {- // xAI STT has a fixed endpoint and accepts no model field. See #910.+ if (route.provider === "xai") {transcriptionUrl = XAI_STT_URL;- if (language && XAI_STT_LANGUAGES.has(language)) {- multipartFields.language = language;+ // xAI STT accepts no model field; the route pre-filters language+ if (route.language) {+ multipartFields.language = route.language;multipartFields.format = "true";}} else {- transcriptionUrl = customRoute?.endpoint ?? baseUrl.replace(/\/+$/, "");- if (!customRoute && !transcriptionUrl.endsWith("/audio/transcriptions")) {- transcriptionUrl += "/audio/transcriptions";- }- multipartFields.model = model || "whisper-1";+ transcriptionUrl =+ route.provider === "mistral" ? MISTRAL_TRANSCRIPTION_URL : route.endpoint;+ multipartFields.model = route.model;+ // No language field: an uploaded file is often not in the dictation+ // language, and a wrong hint silently mistranscribes it. Providers+ // that require one (Corti) are handled on their own branch above.}if (diarize) {- let isMistral = false;- let isOpenAi = false;- try {- const h = new URL(baseUrl).hostname;- isMistral = h.endsWith(".mistral.ai") || h === "mistral.ai";- isOpenAi = h.endsWith(".openai.com") || h === "openai.com";- } catch {}- if (isMistral) {- multipartFields.model = model || "voxtral-mini-latest";+ // A Custom endpoint may front OpenAI or Mistral, so fall back to the+ // resolved host before giving up on speaker labels.+ const diarizeTarget =+ route.provider === "custom" ? diarizationHost(route.endpoint) : route.provider;+ if (diarizeTarget === "mistral") {multipartFields.diarize = "true";multipartFields.timestamp_granularities = "segment";- } else if (isOpenAi) {+ } else if (diarizeTarget === "openai") {multipartFields.model = "gpt-4o-transcribe-diarize";// Speaker annotations require diarized_json; verbose_json is not supported by this model.multipartFields.response_format = "diarized_json";multipartFields.chunking_strategy = "auto";} else {- // The renderer gates on provider name; this re-check is by hostname.- // A non-canonical base URL (Azure/OpenAI-compatible gateway) can- // disagree — degrade to a plain transcript, never fail the upload.+ // Degrade to a plain transcript, never fail the upload.debugLogger.warn(- "BYOK diarization requested but base URL is not OpenAI/Mistral; transcribing without speakers",- { baseUrl }+ "BYOK diarization requested but provider is not OpenAI/Mistral; transcribing without speakers",+ { provider: route.provider, endpoint: route.endpoint });}}@@ -8343,7 +8341,14 @@ class IPCHandlers {);const url = new URL(transcriptionUrl);- const headers = apiKey ? { Authorization: `Bearer ${apiKey}` } : undefined;+ // Mistral authenticates with x-api-key, not Bearer.+ const headers = apiKey+ ? route.provider === "mistral"+ ? { "x-api-key": apiKey }+ : route.transport === "http-batch" && route.auth.scheme === "azure-api-key"+ ? { "api-key": apiKey }+ : { Authorization: `Bearer ${apiKey}` }+ : undefined;const data = await postMultipart(url, body, boundary, headers);if (data.statusCode === 401) {diff --git a/src/helpers/retryTranscriptionRouting.js b/src/helpers/retryTranscriptionRouting.jsdeleted file mode 100644index 5de56817d..000000000--- a/src/helpers/retryTranscriptionRouting.js+++ /dev/null@@ -1,54 +0,0 @@-import { buildApiUrl, normalizeBaseUrl } from "../config/constants.ts";-import { isSecureHttpEndpoint } from "../utils/urlUtils.ts";-import { resolveSelfHostedTranscriptionModel } from "./selfHostedTranscription.js";--export function resolveSelfHostedRetryRoute(settings) {- const mode =- typeof settings?.transcriptionMode === "string" ? settings.transcriptionMode.trim() : "";- if (mode !== "self-hosted") return null;-- const configuredUrl =- typeof settings?.remoteTranscriptionUrl === "string"- ? settings.remoteTranscriptionUrl.trim()- : "";- if (!configuredUrl) {- return {- kind: "configuration-error",- error: "Self-hosted transcription URL is not configured",- };- }-- const remoteUrl = configuredUrl.replace(/\/+$/, "");- const normalizedBaseUrl = normalizeBaseUrl(remoteUrl);- if (!normalizedBaseUrl || !isSecureHttpEndpoint(normalizedBaseUrl)) {- return {- kind: "configuration-error",- error: "Self-hosted transcription URL is invalid or unsupported",- };- }-- return {- kind: "self-hosted",- endpoint: buildApiUrl(normalizedBaseUrl, "/audio/transcriptions"),- model: resolveSelfHostedTranscriptionModel(settings),- };-}--export function resolveCustomTranscriptionRoute({ provider, baseUrl }) {- if (provider !== "custom") return null;-- const configuredUrl = typeof baseUrl === "string" ? baseUrl.trim() : "";- const normalizedBaseUrl = normalizeBaseUrl(configuredUrl);- if (!normalizedBaseUrl || !isSecureHttpEndpoint(normalizedBaseUrl)) {- return {- kind: "configuration-error",- error: "Custom transcription endpoint is invalid or unsupported",- };- }-- return {- kind: "custom",- baseUrl: normalizedBaseUrl,- endpoint: buildApiUrl(normalizedBaseUrl, "/audio/transcriptions"),- };-}diff --git a/src/helpers/transcriptionRoute.ts b/src/helpers/transcriptionRoute.tsnew file mode 100644index 000000000..a73f08f60--- /dev/null+++ b/src/helpers/transcriptionRoute.ts@@ -0,0 +1,302 @@+// Single source of truth for batch speech-to-text routing across dictation,+// retry, and upload. Callers resolve their scope's settings into the flat base+// names and handle the OpenWhispr-cloud pipeline upstream; streaming provider+// selection is a live-recorder concern and stays in audioManager.+//+// Loaded by the renderer and the main process alike (main uses dynamic import):+// erasable TypeScript syntax only, explicit import extensions, no store imports.+// Routes never carry secrets — `auth.keyRef` names the key slot the executor+// resolves itself.+import { API_ENDPOINTS, buildApiUrl, normalizeBaseUrl } from "../config/constants.ts";+import {+ isSecureHttpEndpoint,+ isAzureOpenAIEndpoint,+ buildAzureTranscriptionUrl,+} from "../utils/urlUtils.ts";+import {+ isSelfHostedTranscription,+ resolveSelfHostedTranscriptionModel,+} from "./selfHostedTranscription.js";+import {+ isTranscriptionSelectionAllowed,+ type PolicyDecisionSnapshot,+} from "../stores/policyRules.ts";+import {+ isTinfoilInferenceUrl,+ TINFOIL_PROXY_REQUIRED_ERROR,+ type TranscriptionProviderBaseUrl,+} from "../services/transcriptionBaseUrl.ts";++const BYOK_FILE_SIZE_LIMIT = 25 * 1024 * 1024;++const CUSTOM_ENDPOINT_INVALID_MESSAGE_KEY =+ "hooks.audioRecording.errorDescriptions.customEndpointInvalid";++export interface TranscriptionRouteSettings {+ transcriptionMode?: string;+ useLocalWhisper?: boolean;+ remoteTranscriptionUrl?: string;+ remoteTranscriptionModel?: string;+ cloudTranscriptionProvider?: string;+ cloudTranscriptionModel?: string;+ cloudTranscriptionBaseUrl?: string;+ cortiEnvironment?: string;+ cortiTenant?: string;+ preferredLanguage?: string;+}++export interface TranscriptionRouteInput {+ /** Policy-EFFECTIVE, scope-resolved snapshot — the resolver never re-maps selections. */+ settings: TranscriptionRouteSettings;+ /** Optional fail-closed floor; renderer callers pass the policy store state, main-process callers omit it. */+ policy?: PolicyDecisionSnapshot | null;+ /** Provider registry, for the Tinfoil-host guard. Renderer passes ModelRegistry, main the raw JSON. */+ providers?: readonly TranscriptionProviderBaseUrl[];+ request?: {+ /** Explicit model override; doubles as the Azure deployment name. */+ model?: string;+ /** Translation-aware language (dictation's getEffectiveSttLanguage) — wins over preferredLanguage. */+ effectiveLanguage?: string;+ };+}++export type TranscriptionRoute =+ | { transport: "error"; message: string; code?: string; messageKey?: string }+ | { transport: "local" }+ | {+ transport: "proxied";+ provider: "tinfoil" | "mistral" | "xai" | "corti";+ model: string | null;+ language?: string;+ sizeCapBytes: number;+ cortiEnvironment?: string;+ cortiTenant?: string;+ }+ | {+ transport: "http-batch";+ provider: "self-hosted" | "custom" | "openai" | "groq";+ endpoint: string;+ model: string | null;+ auth: { scheme: "bearer" | "azure-api-key" | "none"; keyRef: string | null };+ sizeCapBytes: number | null;+ language?: string;+ };++// xAI STT supports 25 languages; language must be in this set to enable ITN via format=true+export const XAI_STT_LANGUAGES = new Set([+ "ar",+ "cs",+ "da",+ "de",+ "en",+ "es",+ "fa",+ "fil",+ "fr",+ "hi",+ "id",+ "it",+ "ja",+ "ko",+ "mk",+ "ms",+ "nl",+ "pl",+ "pt",+ "ro",+ "ru",+ "sv",+ "th",+ "tr",+ "vi",+]);++// Prefix-matched rather than registry-checked on purpose: this module loads in+// the packaged main process without the registry, and strict validation would+// reset the model of anyone still on a retired id. The registry-backed picker+// rules live in settingsStore; transcriptionRouteModelAgreement.test.js pins the+// two together for every shipping model.+export function resolveByokModel(provider: string, configuredModel?: string): string {+ const trimmed = (configuredModel || "").trim();+ if (provider === "custom") return trimmed || "whisper-1";+ if (trimmed) {+ const matchesProvider =+ (provider === "groq" && trimmed.startsWith("whisper-large-v3")) ||+ (provider === "openai" && (trimmed.startsWith("gpt-4o") || trimmed === "whisper-1")) ||+ (provider === "mistral" && trimmed.startsWith("voxtral-")) ||+ (provider === "corti" && trimmed.startsWith("corti-"));+ if (matchesProvider) return trimmed;+ }+ if (provider === "groq") return "whisper-large-v3-turbo";+ if (provider === "xai") return "grok-stt";+ if (provider === "mistral") return "voxtral-mini-latest";+ if (provider === "corti") return "corti-transcribe";+ return "gpt-4o-mini-transcribe";+}++function error(message: string, code?: string, messageKey?: string): TranscriptionRoute {+ return { transport: "error", message, code, messageKey };+}++// Azure routes by deployment in the path and needs an api-version query, so the+// plain {base}/audio/transcriptions shape returns DeploymentNotFound. Takes the+// raw URL because normalization strips the suffix that marks a pinned deployment.+// Shared by self-hosted and Custom — deriveTranscriptionMode files Azure+// endpoints under either, depending on when the user configured them.+function buildBatchEndpoint(rawUrl: string, base: string, model: string | null): string {+ const fallback = buildApiUrl(base, "/audio/transcriptions");+ if (!isAzureOpenAIEndpoint(base)) return fallback;+ return buildAzureTranscriptionUrl(rawUrl, model || "") || fallback;+}++function customEndpointError(managed: boolean): TranscriptionRoute {+ if (managed) {+ return error(+ "Transcription is restricted by your organization.",+ "POLICY_RESTRICTED",+ "common.policyTranscriptionRestricted"+ );+ }+ return error(+ "Custom transcription endpoint is invalid or unsupported",+ "CUSTOM_ENDPOINT_INVALID",+ CUSTOM_ENDPOINT_INVALID_MESSAGE_KEY+ );+}++export function resolveTranscriptionRoute({+ settings,+ policy,+ providers = [],+ request,+}: TranscriptionRouteInput): TranscriptionRoute {+ const s = settings || {};+ const managed = policy?.status === "managed";++ // Fail-closed floor only: callers pass policy-effective settings, so a+ // disallowed selection here means the policy layer was bypassed upstream.+ if (+ managed &&+ !isTranscriptionSelectionAllowed(policy!, {+ mode: (s.transcriptionMode || (s.useLocalWhisper ? "local" : "providers")) as never,+ provider: s.cloudTranscriptionProvider || "",+ })+ ) {+ return error(+ "Transcription is restricted by your organization.",+ "POLICY_RESTRICTED",+ "common.policyTranscriptionRestricted"+ );+ }++ const language =+ request?.effectiveLanguage ??+ (!s.preferredLanguage || s.preferredLanguage === "auto"+ ? undefined+ : s.preferredLanguage.split("-")[0]);++ // Self-hosted wins over everything, including stale useLocalWhisper flags.+ // The route needs a configured URL: `byok + custom` also persists+ // transcriptionMode="self-hosted" (deriveTranscriptionMode), so+ // mode-without-URL falls through to the custom branch (fail-closed there)+ // instead of breaking that population, and everything else fails closed.+ if (s.transcriptionMode === "self-hosted") {+ if (isSelfHostedTranscription(s)) {+ const rawUrl = (s.remoteTranscriptionUrl || "").trim();+ const base = normalizeBaseUrl(rawUrl);+ if (!base || !isSecureHttpEndpoint(base)) {+ return error("Self-hosted transcription URL is invalid or unsupported");+ }+ const selfHostedModel = resolveSelfHostedTranscriptionModel(s);+ return {+ transport: "http-batch",+ provider: "self-hosted",+ endpoint: buildBatchEndpoint(rawUrl, base, selfHostedModel),+ model: selfHostedModel,+ auth: { scheme: "none", keyRef: null },+ sizeCapBytes: null,+ language,+ };+ }+ if (s.cloudTranscriptionProvider !== "custom") {+ return error("Self-hosted transcription URL is not configured");+ }+ }++ // Engine and model selection stay with the local managers.+ if (s.useLocalWhisper) {+ return { transport: "local" };+ }++ const provider = s.cloudTranscriptionProvider || "openai";+ const model = resolveByokModel(provider, request?.model ?? s.cloudTranscriptionModel);++ if (provider === "tinfoil" || provider === "mistral" || provider === "xai") {+ return {+ transport: "proxied",+ provider,+ // Tinfoil's attested client resolves its own model; xAI's API takes none.+ model: provider === "mistral" ? model : provider === "xai" ? "grok-stt" : null,+ language:+ provider === "xai" && language && !XAI_STT_LANGUAGES.has(language) ? undefined : language,+ sizeCapBytes: BYOK_FILE_SIZE_LIMIT,+ };+ }+ if (provider === "corti") {+ return {+ transport: "proxied",+ provider,+ model,+ // Corti requires a concrete primaryLanguage; default to English when auto-detecting+ language: language || "en",+ sizeCapBytes: BYOK_FILE_SIZE_LIMIT,+ cortiEnvironment: s.cortiEnvironment || "us",+ cortiTenant: (s.cortiTenant || "").trim() || "base",+ };+ }++ if (provider === "custom") {+ const rawUrl = (s.cloudTranscriptionBaseUrl || "").trim();+ const base = normalizeBaseUrl(rawUrl);+ if (+ !rawUrl ||+ // The untouched store default — Custom was selected but never configured;+ // passing it through would route the custom key + audio to OpenAI.+ rawUrl === API_ENDPOINTS.TRANSCRIPTION_BASE ||+ !base ||+ !isSecureHttpEndpoint(base)+ ) {+ return customEndpointError(managed);+ }+ if (isTinfoilInferenceUrl(base, providers)) {+ return error(TINFOIL_PROXY_REQUIRED_ERROR);+ }+ // Azure authenticates with the `api-key` header; Bearer is reserved for Entra ID.+ return {+ transport: "http-batch",+ provider: "custom",+ endpoint: buildBatchEndpoint(rawUrl, base, model),+ model,+ auth: {+ scheme: isAzureOpenAIEndpoint(base) ? "azure-api-key" : "bearer",+ keyRef: "custom",+ },+ sizeCapBytes: BYOK_FILE_SIZE_LIMIT,+ language,+ };+ }++ const isGroq = provider === "groq";+ return {+ transport: "http-batch",+ provider: isGroq ? "groq" : "openai",+ endpoint: buildApiUrl(+ isGroq ? API_ENDPOINTS.GROQ_BASE : API_ENDPOINTS.TRANSCRIPTION_BASE,+ "/audio/transcriptions"+ ),+ model,+ auth: { scheme: "bearer", keyRef: isGroq ? "groq" : "openai" },+ sizeCapBytes: BYOK_FILE_SIZE_LIMIT,+ language,+ };+}diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex c29ad3d87..27bd6e99c 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -603,7 +603,8 @@"providerRateLimited": "Dein Transkriptionsanbieter hat die Anfrage begrenzt. Warte kurz und versuch es erneut.","chunkLoss": "Ein Netzwerkproblem hat zu viel von der Aufnahme verloren. Transkribieren Sie sie über den Verlauf erneut.","agentReasoningFailed": "Ihr Sprachagent konnte den Befehl nicht verarbeiten – stattdessen wurde das unbearbeitete Transkript eingefügt.",- "screenContextSkipped": "Der Screenshot konnte nicht gesendet werden, daher lief Ihr Befehl ohne Bildschirmkontext."+ "screenContextSkipped": "Der Screenshot konnte nicht gesendet werden, daher lief Ihr Befehl ohne Bildschirmkontext.",+ "customEndpointInvalid": "Ihr benutzerdefinierter Transkriptionsendpunkt ist nicht konfiguriert oder seine URL ist ungültig. Aktualisieren Sie ihn unter Einstellungen → Sprache zu Text."},"translationFallback": {"unreachableTitle": "Übersetzung nicht verfügbar",@@ -2811,7 +2812,8 @@"urlsSkipped": "Einige Links konnten nicht hinzugefügt werden ({{n}})","queueFailed": "{{n}} fehlgeschlagen","urlFileTooLarge": "Die Datei ist zu groß zum Herunterladen. Die maximale Größe beträgt 500 MB.",- "urlYoutubeBlocked": "YouTube blockiert Downloads aus Ihrem Netzwerk vorübergehend. Versuchen Sie es später erneut."+ "urlYoutubeBlocked": "YouTube blockiert Downloads aus Ihrem Netzwerk vorübergehend. Versuchen Sie es später erneut.",+ "customEndpointInvalid": "Benutzerdefinierter Transkriptionsendpunkt ist nicht konfiguriert oder ungültig. Aktualisieren Sie ihn in den Einstellungen."},"meeting": {"title": "Besprechungsnotizen",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 736fad059..c5cfcee4c 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -603,7 +603,8 @@"providerRateLimited": "Your transcription provider rate-limited the request. Wait a moment and try again.","chunkLoss": "A network problem lost too much of the recording. Re-transcribe it from History.","agentReasoningFailed": "Your voice agent couldn't process the command — the raw transcript was inserted instead.",- "screenContextSkipped": "The screenshot couldn't be sent, so your command ran without screen context."+ "screenContextSkipped": "The screenshot couldn't be sent, so your command ran without screen context.",+ "customEndpointInvalid": "Your custom transcription endpoint is not configured or its URL is invalid. Update it in Settings → Speech to Text."},"translationFallback": {"unreachableTitle": "Translation unavailable",@@ -2811,7 +2812,8 @@"urlsSkipped": "Some links couldn't be added ({{n}})","queueFailed": "{{n}} failed","urlFileTooLarge": "File is too large to download. The maximum size is 500 MB.",- "urlYoutubeBlocked": "YouTube is temporarily blocking downloads from your network. Try again in a little while."+ "urlYoutubeBlocked": "YouTube is temporarily blocking downloads from your network. Try again in a little while.",+ "customEndpointInvalid": "Custom transcription endpoint is not configured or invalid. Update it in Settings."},"meeting": {"title": "Meeting Notes",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 6224c5b57..209b9ca41 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -603,7 +603,8 @@"providerRateLimited": "Tu proveedor de transcripción limitó la solicitud. Espera un momento e inténtalo de nuevo.","chunkLoss": "Un problema de red hizo que se perdiera demasiada parte de la grabación. Vuelve a transcribirla desde el historial.","agentReasoningFailed": "Tu agente de voz no pudo procesar el comando; se insertó la transcripción sin procesar.",- "screenContextSkipped": "No se pudo enviar la captura, así que tu comando se ejecutó sin contexto de pantalla."+ "screenContextSkipped": "No se pudo enviar la captura, así que tu comando se ejecutó sin contexto de pantalla.",+ "customEndpointInvalid": "Tu endpoint de transcripción personalizado no está configurado o su URL no es válida. Actualízalo en Ajustes → Voz a texto."},"translationFallback": {"unreachableTitle": "Traducción no disponible",@@ -2651,7 +2652,8 @@"urlsSkipped": "Algunos enlaces no se pudieron añadir ({{n}})","queueFailed": "{{n}} con error","urlFileTooLarge": "El archivo es demasiado grande para descargar. El tamaño máximo es 500 MB.",- "urlYoutubeBlocked": "YouTube está bloqueando temporalmente las descargas desde tu red. Inténtalo de nuevo más tarde."+ "urlYoutubeBlocked": "YouTube está bloqueando temporalmente las descargas desde tu red. Inténtalo de nuevo más tarde.",+ "customEndpointInvalid": "El endpoint de transcripción personalizado no está configurado o no es válido. Actualízalo en Ajustes."},"meeting": {"title": "Notas de reunión",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 3e7883ba8..f9c6cad31 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -603,7 +603,8 @@"providerRateLimited": "Votre fournisseur de transcription a limité la requête. Patientez un instant et réessayez.","chunkLoss": "Un problème réseau a fait perdre une trop grande partie de l'enregistrement. Retranscrivez-le depuis l'historique.","agentReasoningFailed": "Votre agent vocal n'a pas pu traiter la commande ; la transcription brute a été insérée à la place.",- "screenContextSkipped": "La capture n'a pas pu être envoyée ; votre commande a été exécutée sans contexte d'écran."+ "screenContextSkipped": "La capture n'a pas pu être envoyée ; votre commande a été exécutée sans contexte d'écran.",+ "customEndpointInvalid": "Votre point de terminaison de transcription personnalisé n'est pas configuré ou son URL est invalide. Mettez-le à jour dans Réglages → Parole en texte."},"translationFallback": {"unreachableTitle": "Traduction indisponible",@@ -2811,7 +2812,8 @@"urlsSkipped": "Certains liens n'ont pas pu être ajoutés ({{n}})","queueFailed": "{{n}} en échec","urlFileTooLarge": "Le fichier est trop volumineux pour être téléchargé. La taille maximale est de 500 Mo.",- "urlYoutubeBlocked": "YouTube bloque temporairement les téléchargements depuis votre réseau. Réessayez dans un moment."+ "urlYoutubeBlocked": "YouTube bloque temporairement les téléchargements depuis votre réseau. Réessayez dans un moment.",+ "customEndpointInvalid": "Le point de terminaison de transcription personnalisé n'est pas configuré ou est invalide. Mettez-le à jour dans les réglages."},"meeting": {"title": "Notes de réunion",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex aa61f303c..d9ed7f4e1 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -603,7 +603,8 @@"providerRateLimited": "Il tuo provider di trascrizione ha limitato la richiesta. Attendi un momento e riprova.","chunkLoss": "Un problema di rete ha fatto perdere troppa parte della registrazione. Ritrascrivila dalla cronologia.","agentReasoningFailed": "L'agente vocale non è riuscito a elaborare il comando; è stata inserita la trascrizione grezza.",- "screenContextSkipped": "Non è stato possibile inviare lo screenshot, quindi il comando è stato eseguito senza contesto dello schermo."+ "screenContextSkipped": "Non è stato possibile inviare lo screenshot, quindi il comando è stato eseguito senza contesto dello schermo.",+ "customEndpointInvalid": "L'endpoint di trascrizione personalizzato non è configurato o il suo URL non è valido. Aggiornalo in Impostazioni → Da voce a testo."},"translationFallback": {"unreachableTitle": "Traduzione non disponibile",@@ -2603,7 +2604,8 @@"urlsSkipped": "Alcuni link non sono stati aggiunti ({{n}})","queueFailed": "{{n}} non riusciti","urlFileTooLarge": "Il file è troppo grande per essere scaricato. La dimensione massima è 500 MB.",- "urlYoutubeBlocked": "YouTube sta bloccando temporaneamente i download dalla tua rete. Riprova tra poco."+ "urlYoutubeBlocked": "YouTube sta bloccando temporaneamente i download dalla tua rete. Riprova tra poco.",+ "customEndpointInvalid": "L'endpoint di trascrizione personalizzato non è configurato o non è valido. Aggiornalo nelle Impostazioni."},"meeting": {"title": "Note delle riunioni",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex ac33b9b20..7c9c33b25 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -603,7 +603,8 @@"providerRateLimited": "文字起こしプロバイダーがリクエストを制限しました。しばらく待ってからもう一度お試しください。","chunkLoss": "ネットワークの問題で録音の大部分が失われました。履歴から再文字起こししてください。","agentReasoningFailed": "ボイスエージェントがコマンドを処理できなかったため、未処理の文字起こしを挿入しました。",- "screenContextSkipped": "スクリーンショットを送信できなかったため、画面コンテキストなしでコマンドを実行しました。"+ "screenContextSkipped": "スクリーンショットを送信できなかったため、画面コンテキストなしでコマンドを実行しました。",+ "customEndpointInvalid": "カスタム文字起こしエンドポイントが未設定か、URLが無効です。設定 → 音声テキスト変換 から更新してください。"},"translationFallback": {"unreachableTitle": "翻訳を利用できません",@@ -2587,7 +2588,8 @@"urlsSkipped": "追加できなかったリンクがあります({{n}}件)","queueFailed": "{{n}}件失敗","urlFileTooLarge": "ファイルが大きすぎてダウンロードできません。最大サイズは500 MBです。",- "urlYoutubeBlocked": "YouTubeがお使いのネットワークからのダウンロードを一時的にブロックしています。しばらくしてからもう一度お試しください。"+ "urlYoutubeBlocked": "YouTubeがお使いのネットワークからのダウンロードを一時的にブロックしています。しばらくしてからもう一度お試しください。",+ "customEndpointInvalid": "カスタム文字起こしエンドポイントが未設定か無効です。設定から更新してください。"},"meeting": {"title": "議事録",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex ccb9c5ecc..c5d9f170b 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -582,7 +582,8 @@"providerRateLimited": "Seu provedor de transcrição limitou a solicitação. Aguarde um momento e tente novamente.","chunkLoss": "Um problema de rede fez perder grande parte da gravação. Retranscreva-a a partir do histórico.","agentReasoningFailed": "Seu agente de voz não conseguiu processar o comando; a transcrição bruta foi inserida no lugar.",- "screenContextSkipped": "Não foi possível enviar a captura, então seu comando foi executado sem contexto de tela."+ "screenContextSkipped": "Não foi possível enviar a captura, então seu comando foi executado sem contexto de tela.",+ "customEndpointInvalid": "Seu endpoint de transcrição personalizado não está configurado ou a URL é inválida. Atualize-o em Configurações → Fala para texto."},"translationFallback": {"unreachableTitle": "Tradução indisponível",@@ -2603,7 +2604,8 @@"urlsSkipped": "Alguns links não puderam ser adicionados ({{n}})","queueFailed": "{{n}} com falha","urlFileTooLarge": "O arquivo é grande demais para baixar. O tamanho máximo é 500 MB.",- "urlYoutubeBlocked": "O YouTube está bloqueando temporariamente downloads da sua rede. Tente novamente em instantes."+ "urlYoutubeBlocked": "O YouTube está bloqueando temporariamente downloads da sua rede. Tente novamente em instantes.",+ "customEndpointInvalid": "O endpoint de transcrição personalizado não está configurado ou é inválido. Atualize-o nas Configurações."},"meeting": {"title": "Notas de reunião",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex e81ff4ee4..08cf3c21d 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -603,7 +603,8 @@"providerRateLimited": "Ваш провайдер транскрипции ограничил запрос. Подождите немного и попробуйте снова.","chunkLoss": "Из-за проблемы с сетью потеряна значительная часть записи. Повторите расшифровку из истории.","agentReasoningFailed": "Голосовой агент не смог обработать команду — вместо этого вставлена необработанная расшифровка.",- "screenContextSkipped": "Снимок экрана не удалось отправить, поэтому команда выполнена без контекста экрана."+ "screenContextSkipped": "Снимок экрана не удалось отправить, поэтому команда выполнена без контекста экрана.",+ "customEndpointInvalid": "Пользовательская конечная точка транскрипции не настроена или её URL недействителен. Обновите её в Настройках → Речь в текст."},"translationFallback": {"unreachableTitle": "Перевод недоступен",@@ -2623,7 +2624,8 @@"urlsSkipped": "Некоторые ссылки не удалось добавить ({{n}})","queueFailed": "{{n}} с ошибкой","urlFileTooLarge": "Файл слишком большой для загрузки. Максимальный размер — 500 МБ.",- "urlYoutubeBlocked": "YouTube временно блокирует загрузки из вашей сети. Попробуйте снова чуть позже."+ "urlYoutubeBlocked": "YouTube временно блокирует загрузки из вашей сети. Попробуйте снова чуть позже.",+ "customEndpointInvalid": "Пользовательская конечная точка транскрипции не настроена или недействительна. Обновите её в Настройках."},"meeting": {"title": "Заметки со встреч",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 52057bb18..a84f25e3e 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -603,7 +603,8 @@"providerRateLimited": "你的转录服务商限制了请求频率。请稍候再试。","chunkLoss": "网络问题导致录音大部分丢失。请从历史记录中重新转录。","agentReasoningFailed": "语音助手无法处理该命令,已改为插入原始转录文本。",- "screenContextSkipped": "截图无法发送,因此已在没有屏幕上下文的情况下执行你的命令。"+ "screenContextSkipped": "截图无法发送,因此已在没有屏幕上下文的情况下执行你的命令。",+ "customEndpointInvalid": "自定义转写端点未配置或其 URL 无效。请在“设置 → 语音转文字”中更新。"},"translationFallback": {"unreachableTitle": "翻译不可用",@@ -2603,7 +2604,8 @@"urlsSkipped": "部分链接无法添加({{n}} 个)","queueFailed": "{{n}} 个失败","urlFileTooLarge": "文件过大,无法下载。最大大小为 500 MB。",- "urlYoutubeBlocked": "YouTube 暂时阻止了来自您网络的下载。请稍后重试。"+ "urlYoutubeBlocked": "YouTube 暂时阻止了来自您网络的下载。请稍后重试。",+ "customEndpointInvalid": "自定义转写端点未配置或无效。请在设置中更新。"},"meeting": {"title": "会议笔记",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 47df8d9c8..53ddd2f73 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -603,7 +603,8 @@"providerRateLimited": "你的轉錄服務商限制了請求頻率。請稍候再試。","chunkLoss": "網路問題導致錄音大部分遺失。請從歷史記錄中重新轉錄。","agentReasoningFailed": "語音助理無法處理該指令,已改為插入原始逐字稿。",- "screenContextSkipped": "截圖無法傳送,因此已在沒有螢幕內容的情況下執行你的指令。"+ "screenContextSkipped": "截圖無法傳送,因此已在沒有螢幕內容的情況下執行你的指令。",+ "customEndpointInvalid": "自訂轉錄端點未設定或其 URL 無效。請在「設定 → 語音轉文字」中更新。"},"translationFallback": {"unreachableTitle": "翻譯無法使用",@@ -2603,7 +2604,8 @@"urlsSkipped": "部分連結無法新增({{n}} 個)","queueFailed": "{{n}} 個失敗","urlFileTooLarge": "檔案過大,無法下載。大小上限為 500 MB。",- "urlYoutubeBlocked": "YouTube 暫時封鎖了來自您網路的下載。請稍後再試。"+ "urlYoutubeBlocked": "YouTube 暫時封鎖了來自您網路的下載。請稍後再試。",+ "customEndpointInvalid": "自訂轉錄端點未設定或無效。請在設定中更新。"},"meeting": {"title": "會議筆記",diff --git a/src/services/fileTranscription.ts b/src/services/fileTranscription.tsindex a2a775f6a..c172ecb22 100644--- a/src/services/fileTranscription.ts+++ b/src/services/fileTranscription.ts@@ -1,11 +1,6 @@import { withSessionRefresh } from "../lib/auth";-import { resolveCustomTranscriptionRoute } from "../helpers/retryTranscriptionRouting.js";+import { resolveTranscriptionRoute } from "../helpers/transcriptionRoute";import { getTranscriptionProviders } from "../models/ModelRegistry";-import {- TINFOIL_PROXY_REQUIRED_ERROR,- isTinfoilInferenceUrl,- resolveByokBaseUrl,-} from "./transcriptionBaseUrl";export interface FileTranscriptionResult {success: boolean;@@ -71,39 +66,26 @@ export async function transcribeFile(});}- // Built-in providers resolve from the registry; only Custom uses the- // stored URL, which provider tab switches no longer overwrite (#1459).- const providers = getTranscriptionProviders();- let baseUrl = resolveByokBaseUrl(- cfg.cloudTranscriptionProvider,- cfg.cloudTranscriptionBaseUrl || "",- providers- );-- if (cfg.transcriptionMode !== "self-hosted") {- const customRoute = resolveCustomTranscriptionRoute({- provider: cfg.cloudTranscriptionProvider,- baseUrl,- });- if (customRoute?.kind === "configuration-error") {- return {- success: false,- error: customRoute.error,- code: "CUSTOM_ENDPOINT_INVALID",- };- }- if (customRoute) baseUrl = customRoute.baseUrl;- }-- // A Custom URL pointing at Tinfoil (e.g. persisted by the pre-#1459 tab- // clobber) must not bypass the attested main-process proxy. Self-hosted- // mode is exempt: the handler routes it to remoteTranscriptionUrl.- if (- cfg.cloudTranscriptionProvider === "custom" &&- cfg.transcriptionMode !== "self-hosted" &&- isTinfoilInferenceUrl(baseUrl, providers)- ) {- throw new Error(TINFOIL_PROXY_REQUIRED_ERROR);+ // Pre-flight through the shared resolver: code-carrying errors (incl. the+ // Tinfoil-URL and fail-closed custom guards) surface here without an IPC+ // round-trip; the main-process handler re-resolves the same fields as+ // defense in depth.+ const route = resolveTranscriptionRoute({+ settings: {+ transcriptionMode: cfg.transcriptionMode,+ remoteTranscriptionUrl: cfg.remoteTranscriptionUrl,+ remoteTranscriptionModel: cfg.remoteTranscriptionModel,+ cloudTranscriptionProvider: cfg.cloudTranscriptionProvider,+ cloudTranscriptionModel: cfg.cloudTranscriptionModel,+ cloudTranscriptionBaseUrl: cfg.cloudTranscriptionBaseUrl,+ cortiEnvironment: cfg.cortiEnvironment,+ cortiTenant: cfg.cortiTenant,+ },+ providers: getTranscriptionProviders(),+ request: { effectiveLanguage: cfg.language || undefined },+ });+ if (route.transport === "error") {+ return { success: false, error: route.message, code: route.code };}// Self-hosted fields make the handler route to the configured server@@ -111,7 +93,7 @@ export async function transcribeFile(return window.electronAPI.transcribeAudioFileByok!({filePath,apiKey: cfg.getApiKey(),- baseUrl,+ baseUrl: cfg.cloudTranscriptionBaseUrl,model: cfg.cloudTranscriptionModel,diarize: diarize || undefined,provider: cfg.cloudTranscriptionProvider,diff --git a/src/services/transcriptionBaseUrl.ts b/src/services/transcriptionBaseUrl.tsindex 26f28b7d9..6674d06d1 100644--- a/src/services/transcriptionBaseUrl.ts+++ b/src/services/transcriptionBaseUrl.ts@@ -9,15 +9,6 @@ export interface TranscriptionProviderBaseUrl {baseUrl: string;}-export function resolveByokBaseUrl(- providerId: string,- storedBaseUrl: string,- providers: readonly TranscriptionProviderBaseUrl[]-): string {- if (providerId === "custom") return storedBaseUrl;- return providers.find((p) => p.id === providerId)?.baseUrl || "";-}-function parseHostname(url: string): string | null {for (const candidate of [url, `https://${url}`]) {try {diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex fe7767c25..62554b599 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -626,6 +626,9 @@ export interface SettingsStateuploadCloudTranscriptionBaseUrl: string;uploadCloudTranscriptionMode: string;+ /** Last model used per scope+provider (`"<context>:<providerId>"`), so switching providers restores it. */+ transcriptionModelByProvider: Record<string, string>;+noteFormattingMode: InferenceMode;noteFormattingProvider: string;noteFormattingModel: string;@@ -761,6 +764,10 @@ export interface SettingsStatesetCloudTranscriptionModel: (value: string) => void;setCloudTranscriptionBaseUrl: (value: string) => void;setCloudTranscriptionMode: (value: string) => void;+ switchCloudTranscriptionProvider: (+ context: TranscriptionPolicyContext,+ providerId: string+ ) => void;setCleanupCloudMode: (value: string) => void;setCleanupCloudBaseUrl: (value: string) => void;setCustomDictionary: (words: string[]) => void;@@ -905,6 +912,11 @@ function createStringSetter(key: string) {};}+function persistTranscriptionModelMemory(memory: Record<string, string>) {+ if (isBrowser) localStorage.setItem("transcriptionModelByProvider", JSON.stringify(memory));+ useSettingsStore.setState({ transcriptionModelByProvider: memory });+}+/** 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);@@ -1125,6 +1137,16 @@ 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 {};+ }+ })(),// Secrets aren't hydrated yet at construction; the BYOK default is set// post-hydration in initializeSettings.cloudTranscriptionMode: readString("cloudTranscriptionMode", "openwhispr"),@@ -1584,6 +1606,37 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({setCloudTranscriptionProvider: createStringSetter("cloudTranscriptionProvider"),setCloudTranscriptionModel: createStringSetter("cloudTranscriptionModel"),setCloudTranscriptionBaseUrl: createStringSetter("cloudTranscriptionBaseUrl"),++ // Every provider shares one model slot per scope, so a plain provider write+ // destroys the outgoing provider's model (the "Parasail" wipe). This setter+ // remembers the outgoing model and restores the incoming provider's last one.+ switchCloudTranscriptionProvider: (context, providerId) => {+ const s = useSettingsStore.getState();+ const keys = TRANSCRIPTION_CONTEXT_KEYS.find((entry) => entry.context === context);+ if (!keys) return;+ // Meeting/upload raw keys default to "" (inherit from dictation), so work+ // against resolved values. Restoring writes a concrete model — the scope+ // stops inheriting the dictation model from that point on.+ const outgoingProvider = (s[keys.provider] as string) || s.cloudTranscriptionProvider;+ if (outgoingProvider === providerId) {+ setStringSetting(keys.provider, providerId);+ return;+ }+ const outgoingModel = (s[keys.model] as string) || s.cloudTranscriptionModel;+ const memory = { ...s.transcriptionModelByProvider };+ if (outgoingProvider && outgoingModel) {+ memory[`${context}:${outgoingProvider}`] = outgoingModel;+ persistTranscriptionModelMemory(memory);+ }+ const remembered = memory[`${context}:${providerId}`];+ setStringSetting(keys.provider, providerId);+ setStringSetting(+ keys.model,+ remembered && transcriptionModelBelongsToProvider(providerId, remembered, context)+ ? remembered+ : defaultTranscriptionModel(providerId, context)+ );+ },setCloudTranscriptionMode: createStringSetter("cloudTranscriptionMode"),setCleanupCloudMode: createStringSetter("cleanupCloudMode"),setCleanupCloudBaseUrl: createStringSetter("cleanupCloudBaseUrl"),@@ -2111,6 +2164,15 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({s.setUploadCloudTranscriptionMode(cloudTranscriptionMode);s.setUploadCloudTranscriptionProvider(cloudTranscriptionProvider);s.setUploadCloudTranscriptionModel(cloudTranscriptionModel);+ // Seed the per-provider model memory so a later provider switch-and-return+ // in any scope restores the model onboarding chose.+ if (cloudTranscriptionProvider && cloudTranscriptionModel) {+ const memory = { ...useSettingsStore.getState().transcriptionModelByProvider };+ for (const { context } of TRANSCRIPTION_CONTEXT_KEYS) {+ memory[`${context}:${cloudTranscriptionProvider}`] = cloudTranscriptionModel;+ }+ persistTranscriptionModelMemory(memory);+ }},updateCleanupSettings: (settings: Partial<CleanupSettings>) => {diff --git a/src/types/electron.ts b/src/types/electron.tsindex 201b07c21..ce29e7d33 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -51,8 +51,17 @@ export type TranscriptionErrorCode =| "API_KEY_MISSING"| "INVALID_KEY"| "MODEL_NOT_AVAILABLE"+ | "CUSTOM_ENDPOINT_INVALID"| null;+/**+ * Proxied-transcription IPC results. `ipcMain.handle` drops custom error props on+ * rejection, so these handlers resolve with a serialized error instead of throwing.+ */+export type ProxyTranscriptionResult =+ | { text: string; model?: string; error?: undefined }+ | { error: string; code?: string; messageKey?: string; text?: undefined };+export interface AuthTokenState {token: string | null;generation: number;@@ -947,6 +956,8 @@ declare global {cloudTranscriptionProvider: string;cloudTranscriptionModel: string;cloudTranscriptionBaseUrl?: string;+ cortiEnvironment?: string;+ cortiTenant?: string;parakeetModel: string;whisperModel: string;preferredLanguage?: string;@@ -1536,7 +1547,7 @@ declare global {audioBuffer: ArrayBuffer;language?: string;keyterms?: string[];- }) => Promise<{ text: string }>;+ }) => Promise<ProxyTranscriptionResult>;// Mistral API key managementgetMistralKey: () => Promise<string | null>;@@ -1546,7 +1557,7 @@ declare global {model?: string;language?: string;contextBias?: string[];- }) => Promise<{ text: string }>;+ }) => Promise<ProxyTranscriptionResult>;// Corti credential managementgetCortiClientId?: () => Promise<string | null>;@@ -1560,7 +1571,7 @@ declare global {language: string;environment: string;tenant: string;- }) => Promise<{ text: string }>;+ }) => Promise<ProxyTranscriptionResult>;getTinfoilKey?: () => Promise<string | null>;saveTinfoilKey?: (key: string) => Promise<void>;getTinfoilChatModels?: () => Promise<TinfoilCatalogModel[]>;@@ -1568,9 +1579,7 @@ declare global {audioBuffer: ArrayBuffer;language?: string;prompt?: string;- }) => Promise<- { text: string; model: string } | { error: string; code?: string; messageKey?: string }- >;+ }) => Promise<ProxyTranscriptionResult>;// Custom endpoint API keysgetCustomTranscriptionKey?: () => Promise<string | null>;diff --git a/test/helpers/audioManagerCloudFallbackPolicy.test.js b/test/helpers/audioManagerCloudFallbackPolicy.test.jsindex 21485a87b..7f8f18dd2 100644--- a/test/helpers/audioManagerCloudFallbackPolicy.test.js+++ b/test/helpers/audioManagerCloudFallbackPolicy.test.js@@ -2,6 +2,81 @@ const test = require("node:test");const assert = require("node:assert/strict");const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");+// audioManager pulls in the whole renderer graph, so every test here needs the+// same store/service stubs. `settingsKey` names the globalThis slot each test+// swaps its settings through, keeping the module cache per-test isolated.+async function loadAudioManager(t, { cachePrefix, settingsKey }) {+ const { window } = installBrowserGlobals(t);+ const vite = await createRendererServer(t, {+ cachePrefix,+ mockModules: {+ "/utils/logger": "export default { debug() {}, info() {}, warn() {}, error() {} };",+ "/stores/settingsStore": `+ export const getSettings = () => globalThis.${settingsKey};+ export const getEffectiveCleanupModel = () => null;+ export const isCloudCleanupMode = () => false;+ export const isCloudDictationAgentMode = () => false;+ export const isCloudTranslationMode = () => false;+ `,+ "/services/ReasoningService": "export default class ReasoningService {};",+ "/services/SyncService.js": "export const syncService = {};",+ "/lib/auth": "export const withSessionRefresh = (fn) => fn();",+ "/utils/permissions": "export const isAccessibilitySkipped = () => false;",+ },+ });+ t.after(() => {+ delete globalThis[settingsKey];+ });++ const AudioManager = (await vite.ssrLoadModule("/helpers/audioManager.js")).default;+ return {+ window,+ vite,+ setSettings: (settings) => {+ globalThis[settingsKey] = settings;+ },+ // Prototype-only instance: the constructor wires up media devices we don't need.+ createManager: (overrides = {}) =>+ Object.assign(Object.create(AudioManager.prototype), {+ getEffectiveSttLanguage: () => "auto",+ getTranscriptionModel: () => "whisper-1",+ getAPIKey: async () => "test-key",+ getWhisperPrompt: () => null,+ getKeyterms: () => [],+ shouldStreamTranscription: () => false,+ isDictionaryEcho: () => false,+ processTranscription: async (text) => text,+ isReasoningAvailable: async () => false,+ ...overrides,+ }),+ };+}++// Replaces globalThis.fetch for the test and records every endpoint it saw.+function captureFetch(t, respond) {+ const originalFetch = globalThis.fetch;+ const endpoints = [];+ globalThis.fetch = async (endpoint, init) => {+ endpoints.push(String(endpoint));+ return respond(String(endpoint), init);+ };+ t.after(() => {+ globalThis.fetch = originalFetch;+ });+ return endpoints;+}++const okJson = (body) => async () => ({+ ok: true,+ status: 200,+ headers: { get: () => "application/json" },+ text: async () => JSON.stringify(body),+});++const rejectFetch = (message) => () => {+ throw new Error(message);+};+function buildManagedPolicy(allowedTranscriptionModes) {return {version: 1,@@ -22,26 +97,10 @@ function buildManagedPolicy(allowedTranscriptionModes) {}test("cloud->local fallback under org policy", async (t) => {- const { window } = installBrowserGlobals(t);- const vite = await createRendererServer(t, {+ const { window, vite, setSettings, createManager } = await loadAudioManager(t, {cachePrefix: "openwhispr-cloud-fallback-test-",- mockModules: {- "/utils/logger": "export default { debug() {}, info() {}, warn() {}, error() {} };",- "/stores/settingsStore": `- export const getSettings = () => globalThis.__cloudFallbackSettings;- export const getEffectiveCleanupModel = () => null;- export const isCloudCleanupMode = () => false;- export const isCloudDictationAgentMode = () => false;- export const isCloudTranslationMode = () => false;- `,- "/services/ReasoningService": "export default class ReasoningService {};",- "/services/SyncService.js": "export const syncService = {};",- "/lib/auth": "export const withSessionRefresh = (fn) => fn();",- "/utils/permissions": "export const isAccessibilitySkipped = () => false;",- },+ settingsKey: "__cloudFallbackSettings",});-- const AudioManager = (await vite.ssrLoadModule("/helpers/audioManager.js")).default;const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");const audioBlob = {@@ -49,14 +108,11 @@ test("cloud->local fallback under org policy", async (t) => {size: 1024,arrayBuffer: async () => new ArrayBuffer(8),};- globalThis.__cloudFallbackSettings = {+ setSettings({useLocalWhisper: false,allowLocalFallback: true,fallbackWhisperModel: "base",cloudTranscriptionProvider: "openai",- };- t.after(() => {- delete globalThis.__cloudFallbackSettings;});let localWhisperCalls = 0;@@ -65,16 +121,12 @@ test("cloud->local fallback under org policy", async (t) => {return { success: true, text: "local text" };};- const createManager = () => {- const manager = Object.create(AudioManager.prototype);- manager.getEffectiveSttLanguage = () => "auto";- manager.getTranscriptionModel = () => "whisper-1";- manager.getAPIKey = async () => {- throw new Error("cloud transcription unavailable");- };- manager.processTranscription = async (text) => text;- return manager;- };+ const failingCloudManager = () =>+ createManager({+ getAPIKey: async () => {+ throw new Error("cloud transcription unavailable");+ },+ });const setManagedPolicy = (allowedTranscriptionModes) => {usePolicyStore.setState({@@ -94,7 +146,7 @@ test("cloud->local fallback under org policy", async (t) => {setManagedPolicy(["providers"]);localWhisperCalls = 0;- await assert.rejects(createManager().processWithOpenAIAPI(audioBlob, {}), (error) => {+ await assert.rejects(failingCloudManager().processWithOpenAIAPI(audioBlob, {}), (error) => {assert.notEqual(error.code, "POLICY_RESTRICTED");assert.match(error.message, /cloud transcription unavailable/);return true;@@ -107,7 +159,7 @@ test("cloud->local fallback under org policy", async (t) => {setManagedPolicy(["providers", "local"]);localWhisperCalls = 0;- const result = await createManager().processWithOpenAIAPI(audioBlob, {});+ const result = await failingCloudManager().processWithOpenAIAPI(audioBlob, {});assert.equal(result.success, true);assert.equal(result.text, "local text");assert.equal(result.source, "local-fallback");@@ -116,37 +168,12 @@ test("cloud->local fallback under org policy", async (t) => {});test("managed custom transcription never falls through to OpenAI", async (t) => {- installBrowserGlobals(t);- const vite = await createRendererServer(t, {+ const { vite, setSettings, createManager } = await loadAudioManager(t, {cachePrefix: "openwhispr-managed-custom-endpoint-test-",- mockModules: {- "/utils/logger": "export default { debug() {}, info() {}, warn() {}, error() {} };",- "/stores/settingsStore": `- export const getSettings = () => globalThis.__managedCustomSettings;- export const getEffectiveCleanupModel = () => null;- export const isCloudCleanupMode = () => false;- export const isCloudDictationAgentMode = () => false;- export const isCloudTranslationMode = () => false;- `,- "/services/ReasoningService": "export default class ReasoningService {};",- "/services/SyncService.js": "export const syncService = {};",- "/lib/auth": "export const withSessionRefresh = (fn) => fn();",- "/utils/permissions": "export const isAccessibilitySkipped = () => false;",- },+ settingsKey: "__managedCustomSettings",});-- const AudioManager = (await vite.ssrLoadModule("/helpers/audioManager.js")).default;const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");- const originalFetch = globalThis.fetch;- let fetchCalls = 0;- globalThis.fetch = async () => {- fetchCalls += 1;- throw new Error("fetch must not run");- };- t.after(() => {- globalThis.fetch = originalFetch;- delete globalThis.__managedCustomSettings;- });+ const fetched = captureFetch(t, rejectFetch("fetch must not run"));usePolicyStore.setState({accountId: "org-user",@@ -164,22 +191,17 @@ test("managed custom transcription never falls through to OpenAI", async (t) =>appVersion: "1.8.1",});- const manager = Object.create(AudioManager.prototype);- manager.getEffectiveSttLanguage = () => "auto";- manager.getTranscriptionModel = () => "whisper-1";- manager.getAPIKey = async () => "should-not-leak";- manager.getWhisperPrompt = () => null;- manager.shouldStreamTranscription = () => false;+ const manager = createManager({ getAPIKey: async () => "should-not-leak" });const audioBlob = new Blob([new Uint8Array([1, 2, 3])], { type: "audio/webm" });for (const baseUrl of ["", "http://public.example.com/v1", "ftp://192.168.1.20/v1"]) {- globalThis.__managedCustomSettings = {+ setSettings({allowLocalFallback: false,cloudTranscriptionBaseUrl: baseUrl,cloudTranscriptionProvider: "custom",transcriptionMode: "providers",useLocalWhisper: false,- };+ });await assert.rejects(manager.processWithOpenAIAPI(audioBlob), (error) => {assert.equal(error.code, "POLICY_RESTRICTED");@@ -188,5 +210,347 @@ test("managed custom transcription never falls through to OpenAI", async (t) =>});}- assert.equal(fetchCalls, 0);+ assert.equal(fetched.length, 0);+});++test("unmanaged custom transcription fails closed instead of defaulting to OpenAI", async (t) => {+ const { vite, setSettings, createManager } = await loadAudioManager(t, {+ cachePrefix: "openwhispr-custom-endpoint-guard-test-",+ settingsKey: "__customGuardSettings",+ });+ const { API_ENDPOINTS } = await vite.ssrLoadModule("/config/constants.ts");+ const fetched = captureFetch(t, okJson({ text: "custom text" }));++ const manager = createManager({ getAPIKey: async () => "custom-key" });+ const audioBlob = new Blob([new Uint8Array([1, 2, 3])], { type: "audio/webm" });+ const useBaseUrl = (cloudTranscriptionBaseUrl) =>+ setSettings({+ allowLocalFallback: false,+ cloudTranscriptionBaseUrl,+ cloudTranscriptionProvider: "custom",+ transcriptionMode: "providers",+ useLocalWhisper: false,+ });++ await t.test(+ "empty, default-sentinel, and invalid URLs throw CUSTOM_ENDPOINT_INVALID",+ async () => {+ for (const baseUrl of [+ "",+ " ",+ API_ENDPOINTS.TRANSCRIPTION_BASE,+ "not a url",+ "http://public.example.com/v1",+ "ftp://192.168.1.20/v1",+ ]) {+ useBaseUrl(baseUrl);+ await assert.rejects(manager.processWithOpenAIAPI(audioBlob), (error) => {+ assert.equal(+ error.code,+ "CUSTOM_ENDPOINT_INVALID",+ `baseUrl: ${JSON.stringify(baseUrl)}`+ );+ assert.equal(+ error.messageKey,+ "hooks.audioRecording.errorDescriptions.customEndpointInvalid"+ );+ return true;+ });+ }+ assert.equal(fetched.length, 0, "no misconfigured request may leave the app");+ }+ );++ await t.test("a configured custom URL still routes to that URL", async () => {+ useBaseUrl("https://stt.parasail.example.com/v1");+ const result = await manager.processWithOpenAIAPI(audioBlob);+ assert.equal(result.success, true);+ assert.deepEqual(fetched, ["https://stt.parasail.example.com/v1/audio/transcriptions"]);+ });++ await t.test("error after a valid resolve does not cache the OpenAI default", async () => {+ fetched.length = 0;+ useBaseUrl("https://stt.parasail.example.com/v1");+ globalThis.fetch = async (endpoint) => {+ fetched.push(String(endpoint));+ throw new Error("network down");+ };+ await assert.rejects(manager.processWithOpenAIAPI(audioBlob));+ useBaseUrl("");+ await assert.rejects(manager.processWithOpenAIAPI(audioBlob), (error) => {+ assert.equal(error.code, "CUSTOM_ENDPOINT_INVALID");+ return true;+ });+ assert.deepEqual(fetched, ["https://stt.parasail.example.com/v1/audio/transcriptions"]);+ });++ await t.test("an Azure custom endpoint keeps its deployment URL and api-key auth", async () => {+ fetched.length = 0;+ let seenHeaders;+ globalThis.fetch = async (endpoint, init) => {+ fetched.push(String(endpoint));+ seenHeaders = init?.headers;+ return okJson({ text: "azure text" })();+ };+ useBaseUrl("https://myorg.openai.azure.com");+ const result = await manager.processWithOpenAIAPI(audioBlob);+ assert.equal(result.success, true);+ assert.deepEqual(fetched, [+ "https://myorg.openai.azure.com/openai/deployments/whisper-1/audio/transcriptions?api-version=2025-03-01-preview",+ ]);+ assert.equal(seenHeaders["api-key"], "custom-key");+ assert.equal(seenHeaders.Authorization, undefined);+ });+});++test("self-hosted mode is never hijacked by a leftover proxied provider", async (t) => {+ const { window, setSettings, createManager } = await loadAudioManager(t, {+ cachePrefix: "openwhispr-selfhosted-hijack-test-",+ settingsKey: "__hijackSettings",+ });++ const proxyCalls = { mistral: 0, xai: 0, corti: 0 };+ for (const [provider, channel] of [+ ["mistral", "proxyMistralTranscription"],+ ["xai", "proxyXaiTranscription"],+ ["corti", "proxyCortiTranscription"],+ ]) {+ window.electronAPI[channel] = async () => {+ proxyCalls[provider] += 1;+ throw new Error("must not be called in self-hosted mode");+ };+ }+ const fetched = captureFetch(t, okJson({ text: "self-hosted text" }));+ const manager = createManager({+ getTranscriptionModel: () => "self-hosted-model",+ getAPIKey: async () => null,+ });++ const audioBlob = new Blob([new Uint8Array([1, 2, 3])], { type: "audio/webm" });+ for (const provider of ["mistral", "xai", "corti"]) {+ setSettings({+ allowLocalFallback: false,+ cloudTranscriptionProvider: provider,+ transcriptionMode: "self-hosted",+ remoteTranscriptionUrl: "https://stt.internal.example.com",+ useLocalWhisper: false,+ });+ const result = await manager.processWithOpenAIAPI(audioBlob);+ assert.equal(result.success, true);+ }++ assert.deepEqual(proxyCalls, { mistral: 0, xai: 0, corti: 0 });+ assert.equal(+ fetched.every((e) => e.startsWith("https://stt.internal.example.com")),+ true,+ `unexpected endpoints: ${fetched.join(", ")}`+ );+});++// A self-hosted URL on an Azure host is a real population: migrateProviderSettings+// files every legacy `custom + byok` user under transcriptionMode "self-hosted"+// and copies their base URL across.+test("self-hosted Azure endpoints keep their deployment URL", async (t) => {+ const { setSettings, createManager } = await loadAudioManager(t, {+ cachePrefix: "openwhispr-selfhosted-azure-test-",+ settingsKey: "__selfHostedAzureSettings",+ });+ const fetched = captureFetch(t, okJson({ text: "azure text" }));+ const manager = createManager({+ getTranscriptionModel: () => "my-deployment",+ getAPIKey: async () => "azure-key",+ });+ const audioBlob = new Blob([new Uint8Array([1, 2, 3])], { type: "audio/webm" });++ const useRemote = (remoteTranscriptionUrl, remoteTranscriptionModel) =>+ setSettings({+ allowLocalFallback: false,+ transcriptionMode: "self-hosted",+ remoteTranscriptionUrl,+ remoteTranscriptionModel,+ useLocalWhisper: false,+ });++ await t.test("a bare Azure origin gains the deployment path and api-version", async () => {+ useRemote("https://myorg.openai.azure.com", "my-deployment");+ await manager.processWithOpenAIAPI(audioBlob);+ assert.deepEqual(fetched, [+ "https://myorg.openai.azure.com/openai/deployments/my-deployment/audio/transcriptions?api-version=2025-03-01-preview",+ ]);+ });++ await t.test("a pinned deployment URL is preserved verbatim", async () => {+ fetched.length = 0;+ const pinned =+ "https://myorg.openai.azure.com/openai/deployments/pinned/audio/transcriptions?api-version=2024-06-01";+ useRemote(pinned, "my-deployment");+ await manager.processWithOpenAIAPI(audioBlob);+ assert.deepEqual(fetched, [pinned]);+ });++ await t.test("a non-Azure self-hosted host is untouched", async () => {+ fetched.length = 0;+ useRemote("https://stt.internal.example.com", "tiny");+ await manager.processWithOpenAIAPI(audioBlob);+ assert.deepEqual(fetched, ["https://stt.internal.example.com/audio/transcriptions"]);+ });+});++test("corti without a preload bridge throws instead of falling through to OpenAI", async (t) => {+ const { window, setSettings, createManager } = await loadAudioManager(t, {+ cachePrefix: "openwhispr-corti-preload-test-",+ settingsKey: "__cortiPreloadSettings",+ });+ delete window.electronAPI.proxyCortiTranscription;+ const fetched = captureFetch(t, rejectFetch("fetch must not run"));++ setSettings({+ allowLocalFallback: false,+ cloudTranscriptionProvider: "corti",+ transcriptionMode: "providers",+ useLocalWhisper: false,+ });++ const manager = createManager({+ getTranscriptionModel: () => "corti-transcribe",+ getAPIKey: async () => null,+ });+ await assert.rejects(+ manager.processWithOpenAIAPI(new Blob([new Uint8Array([1])], { type: "audio/webm" })),+ /Corti transcription is unavailable in this window/+ );+ assert.equal(fetched.length, 0);+});++test("proxied providers dispatch through the registry", async (t) => {+ const { window, setSettings, createManager } = await loadAudioManager(t, {+ cachePrefix: "openwhispr-proxy-registry-test-",+ settingsKey: "__proxyRegistrySettings",+ });+ const fetched = captureFetch(+ t,+ rejectFetch("proxied providers must not fetch from the renderer")+ );++ const payloads = {};+ for (const [provider, channel] of [+ ["tinfoil", "proxyTinfoilTranscription"],+ ["mistral", "proxyMistralTranscription"],+ ["xai", "proxyXaiTranscription"],+ ["corti", "proxyCortiTranscription"],+ ]) {+ window.electronAPI[channel] = async (payload) => {+ payloads[provider] = payload;+ return { text: "proxied text" };+ };+ }++ const dictionary = Array.from({ length: 30 }, (_, i) => `term${i}`.padEnd(40, "x")).join(", ");+ const manager = createManager({+ getTranscriptionModel: () => "voxtral-mini-latest",+ getAPIKey: async () => "key",+ getWhisperPrompt: () => dictionary,+ getKeyterms: () => ["Alpha", " Beta ", ""],+ });++ const audioBlob = new Blob([new Uint8Array([1, 2, 3])], { type: "audio/webm" });+ const settingsFor = (provider) => ({+ allowLocalFallback: false,+ cloudTranscriptionProvider: provider,+ transcriptionMode: "providers",+ useLocalWhisper: false,+ cortiEnvironment: "eu",+ cortiTenant: " acme ",+ });++ await t.test("each provider gets its own payload shape and source label", async () => {+ for (const provider of ["tinfoil", "mistral", "xai", "corti"]) {+ setSettings(settingsFor(provider));+ const result = await manager.processWithOpenAIAPI(audioBlob);+ assert.equal(result.success, true);+ assert.equal(result.source, provider);+ }+ assert.equal(payloads.tinfoil.prompt, dictionary);+ // contextBias is built from the untruncated dictionary: all 30 terms survive.+ assert.equal(payloads.mistral.contextBias.length, 30);+ assert.equal(payloads.mistral.model, "voxtral-mini-latest");+ assert.deepEqual(payloads.xai.keyterms, ["Alpha", "Beta"]);+ assert.equal(payloads.xai.language, undefined);+ assert.equal(payloads.corti.language, "en");+ assert.equal(payloads.corti.environment, "eu");+ assert.equal(payloads.corti.tenant, "acme");+ assert.equal(fetched.length, 0);+ });++ await t.test("structured proxy errors are rebuilt with code and messageKey", async () => {+ setSettings(settingsFor("mistral"));+ window.electronAPI.proxyMistralTranscription = async () => ({+ error: "Mistral API Error: 401 unauthorized",+ code: "INVALID_KEY",+ messageKey: "some.key",+ });+ await assert.rejects(manager.processWithOpenAIAPI(audioBlob), (error) => {+ assert.equal(error.code, "INVALID_KEY");+ assert.equal(error.messageKey, "some.key");+ return true;+ });+ });++ await t.test("empty responses name the provider", async () => {+ setSettings(settingsFor("xai"));+ window.electronAPI.proxyXaiTranscription = async () => ({ text: " " });+ await assert.rejects(+ manager.processWithOpenAIAPI(audioBlob),+ /No text transcribed - xAI response was empty/+ );+ });++ await t.test("a missing preload bridge throws for every proxied provider", async () => {+ for (const [provider, channel, name] of [+ ["tinfoil", "proxyTinfoilTranscription", "Tinfoil"],+ ["mistral", "proxyMistralTranscription", "Mistral"],+ ["xai", "proxyXaiTranscription", "xAI"],+ ["corti", "proxyCortiTranscription", "Corti"],+ ]) {+ delete window.electronAPI[channel];+ setSettings(settingsFor(provider));+ await assert.rejects(+ manager.processWithOpenAIAPI(audioBlob),+ new RegExp(`${name} transcription is unavailable in this window`)+ );+ }+ assert.equal(fetched.length, 0);+ });+});++test("config-error code survives a failed local fallback", async (t) => {+ const { window, setSettings, createManager } = await loadAudioManager(t, {+ cachePrefix: "openwhispr-fallback-wrap-test-",+ settingsKey: "__fallbackWrapSettings",+ });+ window.electronAPI.transcribeLocalWhisper = async () => {+ throw new Error("local model missing");+ };++ const manager = createManager({ getAPIKey: async () => "custom-key" });+ setSettings({+ allowLocalFallback: true,+ fallbackWhisperModel: "base",+ cloudTranscriptionBaseUrl: "",+ cloudTranscriptionProvider: "custom",+ transcriptionMode: "providers",+ useLocalWhisper: false,+ });++ await assert.rejects(+ manager.processWithOpenAIAPI(new Blob([new Uint8Array([1])], { type: "audio/webm" })),+ (error) => {+ assert.equal(error.code, "CUSTOM_ENDPOINT_INVALID");+ assert.equal(+ error.messageKey,+ "hooks.audioRecording.errorDescriptions.customEndpointInvalid"+ );+ return true;+ }+ );});diff --git a/test/helpers/dictionaryEchoRecovery.test.js b/test/helpers/dictionaryEchoRecovery.test.jsindex 5005f5944..4131662af 100644--- a/test/helpers/dictionaryEchoRecovery.test.js+++ b/test/helpers/dictionaryEchoRecovery.test.js@@ -72,8 +72,13 @@ test("every dictionary-echo discard is tagged, on local and remote paths alike",// Each isDictionaryEcho guard must throw the tagged error; a plain// `new Error("No audio detected")` there would be swallowed again.+ //+ // The floor is a canary on the regex, not a target: it must track the real+ // guard count so a pattern that silently stops matching can't make the loop+ // below vacuous. It dropped from 7 to 4 when PROXY_TRANSCRIPTION_PROVIDERS+ // collapsed the tinfoil/mistral/xai/corti blocks into one dispatch.const guards = source.match(/isDictionaryEcho\([\s\S]{0,400}?throw [^;]+;/g) ?? [];- assert.ok(guards.length >= 7, `expected the known echo guards, found ${guards.length}`);+ assert.ok(guards.length >= 4, `expected the known echo guards, found ${guards.length}`);for (const guard of guards) {assert.match(guard, /throw dictionaryEchoError\(\);/);}diff --git a/test/helpers/ipcPolicyHeaderCoverage.test.js b/test/helpers/ipcPolicyHeaderCoverage.test.jsindex 63d41be9c..f0a7d11e7 100644--- a/test/helpers/ipcPolicyHeaderCoverage.test.js+++ b/test/helpers/ipcPolicyHeaderCoverage.test.js@@ -101,7 +101,7 @@ test("every direct OpenWhispr API route is policy-protected or explicitly exempt});test("policy headers are not injected into BYOK or self-hosted transports", () => {- for (const anchor of ['provider === "tinfoil"', 'kind === "self-hosted"']) {+ for (const anchor of ['provider === "tinfoil"', 'provider === "self-hosted"']) {const anchorIndex = source.indexOf(anchor);assert.notEqual(anchorIndex, -1, `anchor ${anchor} must exist in ipcHandlers.js`);assert.doesNotMatch(source.slice(anchorIndex, anchorIndex + 1200), /withPolicyHeaders/);diff --git a/test/helpers/retryTranscriptionHandler.test.js b/test/helpers/retryTranscriptionHandler.test.jsnew file mode 100644index 000000000..2bb5d7b53--- /dev/null+++ b/test/helpers/retryTranscriptionHandler.test.js@@ -0,0 +1,479 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const Module = require("node:module");++const handlersModulePath = require.resolve("../../src/helpers/ipcHandlers");+const originalLoad = Module._load;++// Captures every ipcMain.handle registration and every net.fetch request so the+// registered handler closures can be invoked directly against a fake `this`.+const handlers = new Map();+const fetches = [];+let fetchResponse = () => ({+ ok: true,+ status: 200,+ json: async () => ({ text: "transcribed" }),+ text: async () => JSON.stringify({ text: "transcribed" }),+});++const electronStub = {+ app: {+ getPath: () => "/tmp",+ getName: () => "test",+ getVersion: () => "0.0.0",+ isPackaged: false,+ on: () => {},+ requestSingleInstanceLock: () => true,+ },+ ipcMain: {+ handle: (channel, fn) => handlers.set(channel, fn),+ on: () => {},+ removeHandler: () => {},+ },+ net: {+ fetch: async (url, init) => {+ fetches.push({ url: String(url), init });+ return fetchResponse(String(url), init);+ },+ },+ BrowserWindow: class BrowserWindow {+ static getAllWindows() {+ return [];+ }+ static fromWebContents() {+ return null;+ }+ },+ shell: {},+ dialog: {},+ screen: { getPrimaryDisplay: () => ({ workAreaSize: { width: 0, height: 0 } }) },+ systemPreferences: { getMediaAccessStatus: () => "granted" },+ session: { fromPartition: () => ({}) },+ clipboard: {},+ nativeImage: {},+ globalShortcut: {},+ utilityProcess: {},+ MessageChannelMain: class {},+};++const cortiCalls = [];+const tinfoilCalls = [];+let cortiBehavior = async () => ({ text: "corti text" });++// Kept installed for the whole file: the corti client is require()d lazily at+// handler invocation time, not at module load.+Module._load = function loadWithMocks(request, parent, isMain) {+ if (request === "electron") return electronStub;+ if (parent?.filename === handlersModulePath) {+ if (request === "./cortiTranscription") {+ return {+ transcribeAudio: async (opts) => {+ cortiCalls.push(opts);+ return cortiBehavior(opts);+ },+ };+ }+ if (request === "./tinfoilTranscription") {+ return {+ transcribeWithTinfoil: async (opts) => {+ tinfoilCalls.push(opts);+ return { text: "tinfoil text", model: "tinfoil-model" };+ },+ getTinfoilChatModels: () => [],+ };+ }+ if (request === "./windowBroadcast") {+ return { broadcastToWindows: () => {} };+ }+ }+ return originalLoad.call(this, request, parent, isMain);+};++// A permissive `this` for setupHandlers: registration only stores closures, so+// any manager not exercised by the retry handler can be an inert stub.+function anything() {+ return new Proxy(function () {}, {+ get: (t, prop) => {+ if (prop === Symbol.toPrimitive || prop === "toString") return () => "";+ if (prop === "then") return undefined;+ return anything();+ },+ apply: () => anything(),+ });+}++function buildFakeThis() {+ const dbRows = new Map([[7, { id: 7, audio_duration_ms: 1200 }]]);+ const target = {+ sessionId: "test-session",+ audioStorageManager: { getAudioBuffer: (id) => (id === 7 ? Buffer.from([1, 2, 3]) : null) },+ databaseManager: {+ updateTranscriptionText: () => {},+ updateTranscriptionStatus: () => {},+ updateTranscriptionAudio: () => {},+ getTranscriptionById: (id) => dbRows.get(id),+ },+ environmentManager: {+ getOpenAIKey: () => "sk-openai",+ getGroqKey: () => "gk-groq",+ getMistralKey: () => "mk-mistral",+ getXaiKey: () => "xk-xai",+ getTinfoilKey: () => "tk-tinfoil",+ getCustomTranscriptionKey: () => "ck-custom",+ getCortiClientId: () => "corti-id",+ getCortiClientSecret: () => "corti-secret",+ },+ };+ return new Proxy(target, {+ get: (t, prop) => (prop in t ? t[prop] : anything()),+ });+}++let retryHandler;+test.before(() => {+ delete require.cache[handlersModulePath];+ const IPCHandlers = require(handlersModulePath);+ const Ctor = IPCHandlers.default || IPCHandlers;+ Ctor.prototype.setupHandlers.call(buildFakeThis());+ retryHandler = handlers.get("retry-transcription");+ assert.ok(retryHandler, "retry-transcription must be registered");+});++test.after(() => {+ Module._load = originalLoad;+});++const invoke = (settings, id = 7) => retryHandler({ sender: {} }, id, settings);++test("retry: corti routes to the corti client, never OpenAI", async () => {+ fetches.length = 0;+ const result = await invoke({+ cloudTranscriptionProvider: "corti",+ cloudTranscriptionMode: "byok",+ transcriptionMode: "providers",+ cortiEnvironment: "eu",+ cortiTenant: "acme",+ preferredLanguage: "auto",+ });+ assert.equal(result.success, true);+ assert.equal(cortiCalls.length, 1);+ assert.equal(cortiCalls[0].environment, "eu");+ assert.equal(cortiCalls[0].tenant, "acme");+ assert.equal(cortiCalls[0].language, "en");+ assert.equal(fetches.length, 0, "corti retry must not touch HTTP endpoints");+});++test("retry: custom misconfiguration fails closed with a coded error", async () => {+ fetches.length = 0;+ for (const cloudTranscriptionBaseUrl of ["", "https://api.openai.com/v1", "not a url"]) {+ const result = await invoke({+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionMode: "byok",+ transcriptionMode: "providers",+ cloudTranscriptionBaseUrl,+ });+ assert.equal(result.success, false, cloudTranscriptionBaseUrl);+ assert.equal(result.code, "CUSTOM_ENDPOINT_INVALID", cloudTranscriptionBaseUrl);+ }+ assert.equal(fetches.length, 0);+});++test("retry: openwhispr cloud masks a leftover BYOK misconfiguration", async () => {+ fetches.length = 0;+ const result = await invoke({+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionMode: "openwhispr",+ transcriptionMode: "providers",+ cloudTranscriptionBaseUrl: "",+ });+ // BrowserWindow.fromWebContents is stubbed to null, so the cloud branch+ // produces no result — but the route error must NOT surface.+ assert.equal(result.success, false);+ assert.notEqual(result.code, "CUSTOM_ENDPOINT_INVALID");+ assert.match(result.error, /No transcription engine available/);+ assert.equal(fetches.length, 0);+});++test("retry: Azure custom endpoints get deployment URLs and api-key auth", async () => {+ fetches.length = 0;+ const result = await invoke({+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionMode: "byok",+ transcriptionMode: "providers",+ cloudTranscriptionBaseUrl: "https://myres.openai.azure.com",+ cloudTranscriptionModel: "my-deployment",+ });+ assert.equal(result.success, true);+ assert.equal(fetches.length, 1);+ assert.match(fetches[0].url, /myres\.openai\.azure\.com\/openai\/deployments\/my-deployment/);+ assert.equal(fetches[0].init.headers["api-key"], "ck-custom");+ assert.equal(fetches[0].init.headers.Authorization, undefined);+});++test("retry: plain custom endpoints use Bearer auth at the configured URL", async () => {+ fetches.length = 0;+ const result = await invoke({+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionMode: "byok",+ transcriptionMode: "providers",+ cloudTranscriptionBaseUrl: "https://stt.parasail.example.com/v1",+ cloudTranscriptionModel: "parasail-model",+ });+ assert.equal(result.success, true);+ assert.equal(fetches[0].url, "https://stt.parasail.example.com/v1/audio/transcriptions");+ assert.equal(fetches[0].init.headers.Authorization, "Bearer ck-custom");+});++test("retry: a custom URL on Tinfoil's host is refused in the main process", async () => {+ fetches.length = 0;+ const result = await invoke({+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionMode: "byok",+ transcriptionMode: "providers",+ cloudTranscriptionBaseUrl: "https://inference.tinfoil.sh/v1",+ });+ assert.equal(result.success, false);+ assert.match(result.error, /attested main-process proxy/);+ assert.equal(fetches.length, 0);+ assert.equal(tinfoilCalls.length, 0);+});++test("retry: mistral goes to Mistral with x-api-key", async () => {+ fetches.length = 0;+ const result = await invoke({+ cloudTranscriptionProvider: "mistral",+ cloudTranscriptionMode: "byok",+ transcriptionMode: "providers",+ });+ assert.equal(result.success, true);+ assert.match(fetches[0].url, /api\.mistral\.ai/);+ assert.equal(fetches[0].init.headers["x-api-key"], "mk-mistral");+});++test("proxy transcription handlers resolve to structured errors instead of rejecting", async () => {+ fetchResponse = () => ({+ ok: false,+ status: 401,+ text: async () => "unauthorized",+ json: async () => ({}),+ });+ cortiBehavior = async () => {+ const err = new Error("Corti API Error: 401");+ err.code = "INVALID_KEY";+ throw err;+ };+ try {+ for (const channel of [+ "proxy-mistral-transcription",+ "proxy-xai-transcription",+ "proxy-corti-transcription",+ ]) {+ const fn = handlers.get(channel);+ assert.ok(fn, `${channel} must be registered`);+ const result = await fn({ sender: {} }, { audioBuffer: new ArrayBuffer(4) });+ assert.equal(typeof result.error, "string", channel);+ }+ } finally {+ cortiBehavior = async () => ({ text: "corti text" });+ fetchResponse = () => ({+ ok: true,+ status: 200,+ json: async () => ({ text: "transcribed" }),+ text: async () => JSON.stringify({ text: "transcribed" }),+ });+ }+});++const fsNode = require("node:fs");+const osNode = require("node:os");+const pathNode = require("node:path");++const uploadTempFile = pathNode.join(osNode.tmpdir(), "openwhispr-upload-handler-test.webm");++const invokeUpload = (payload) => {+ const uploadHandler = handlers.get("transcribe-audio-file-byok");+ assert.ok(uploadHandler, "transcribe-audio-file-byok must be registered");+ fsNode.writeFileSync(uploadTempFile, Buffer.from([1, 2, 3, 4]));+ return uploadHandler({ sender: {} }, { filePath: uploadTempFile, ...payload });+};++test("upload: mistral sends x-api-key with a provider-validated model and no language on auto", async () => {+ fetches.length = 0;+ const result = await invokeUpload({+ apiKey: "mk-mistral",+ baseUrl: "https://api.mistral.ai/v1",+ model: "gpt-4o-mini-transcribe", // stale from an openai era — must degrade+ provider: "mistral",+ language: "",+ transcriptionMode: "providers",+ });+ assert.equal(result.success, true);+ assert.match(fetches[0].url, /api\.mistral\.ai/);+ assert.equal(fetches[0].init.headers["x-api-key"], "mk-mistral");+ assert.equal(fetches[0].init.headers.Authorization, undefined);+ const body = fetches[0].init.body.toString();+ assert.match(body, /voxtral-mini-latest/);+ assert.doesNotMatch(body, /name="language"/);+});++test("upload: openai diarization fields ride the route, Bearer auth", async () => {+ fetches.length = 0;+ const result = await invokeUpload({+ apiKey: "sk-openai",+ baseUrl: "https://api.openai.com/v1",+ model: "gpt-4o-mini-transcribe",+ provider: "openai",+ diarize: true,+ language: "",+ transcriptionMode: "providers",+ });+ assert.equal(result.success, true);+ assert.equal(fetches[0].init.headers.Authorization, "Bearer sk-openai");+ const body = fetches[0].init.body.toString();+ assert.match(body, /gpt-4o-transcribe-diarize/);+ assert.match(body, /diarized_json/);+});++test("upload: sentinel custom URL fails closed before any request", async () => {+ fetches.length = 0;+ const result = await invokeUpload({+ apiKey: "ck-custom",+ baseUrl: "https://api.openai.com/v1",+ model: "whisper-1",+ provider: "custom",+ language: "",+ transcriptionMode: "providers",+ });+ assert.equal(result.success, false);+ assert.equal(result.code, "CUSTOM_ENDPOINT_INVALID");+ assert.equal(fetches.length, 0);+});++test("upload: a custom URL on Tinfoil's host is refused in the main process", async () => {+ fetches.length = 0;+ const result = await invokeUpload({+ apiKey: "ck-custom",+ baseUrl: "https://inference.tinfoil.sh/v1",+ model: "whisper-1",+ provider: "custom",+ language: "",+ transcriptionMode: "providers",+ });+ assert.equal(result.success, false);+ assert.match(result.error, /attested main-process proxy/);+ assert.equal(fetches.length, 0);+});++// An uploaded file is frequently not in the dictation language, and a wrong hint+// silently mistranscribes it — so BYOK cloud uploads auto-detect even when the+// user has pinned a preferred language for dictation.+test("upload: a preferred language never constrains a BYOK cloud upload", async () => {+ for (const provider of ["openai", "groq", "custom"]) {+ fetches.length = 0;+ const result = await invokeUpload({+ apiKey: "sk-key",+ baseUrl: provider === "custom" ? "https://gateway.example.com/v1" : "",+ model: "whisper-1",+ provider,+ language: "de",+ transcriptionMode: "providers",+ });+ assert.equal(result.success, true, provider);+ assert.doesNotMatch(fetches[0].init.body.toString(), /name="language"/, provider);+ }+});++// Providers that require a concrete language still receive one.+test("upload: corti and xai still get their language", async () => {+ fetches.length = 0;+ const xai = await invokeUpload({+ apiKey: "xk-key",+ baseUrl: "",+ model: "grok-stt",+ provider: "xai",+ language: "de",+ transcriptionMode: "providers",+ });+ assert.equal(xai.success, true);+ assert.match(fetches[0].url, /api\.x\.ai/);+ const xaiBody = fetches[0].init.body.toString();+ assert.match(xaiBody, /name="language"[\s\S]*?de/);+ assert.doesNotMatch(xaiBody, /name="model"/);++ const corti = await invokeUpload({+ apiKey: "",+ baseUrl: "",+ model: "corti-transcribe",+ provider: "corti",+ language: "",+ environment: "eu",+ tenant: " acme ",+ transcriptionMode: "providers",+ });+ assert.equal(corti.success, true);+ assert.equal(cortiCalls.at(-1).language, "en", "corti needs a concrete primaryLanguage");+ assert.equal(cortiCalls.at(-1).environment, "eu");+ assert.equal(cortiCalls.at(-1).tenant, "acme");+});++// #1459 made cloudTranscriptionBaseUrl Custom-only, so provider id alone can no+// longer tell whether a Custom endpoint fronts a diarization-capable API.+test("upload: a Custom endpoint fronting OpenAI or Mistral keeps diarization", async () => {+ fetches.length = 0;+ const openaiFronted = await invokeUpload({+ apiKey: "ck-custom",+ baseUrl: "https://api.openai.com/v1/audio/transcriptions",+ model: "whisper-1",+ provider: "custom",+ diarize: true,+ language: "",+ transcriptionMode: "providers",+ });+ assert.equal(openaiFronted.success, true);+ assert.match(fetches[0].init.body.toString(), /gpt-4o-transcribe-diarize/);++ fetches.length = 0;+ const mistralFronted = await invokeUpload({+ apiKey: "ck-custom",+ baseUrl: "https://api.mistral.ai/v1/audio/transcriptions",+ model: "voxtral-mini-latest",+ provider: "custom",+ diarize: true,+ language: "",+ transcriptionMode: "providers",+ });+ assert.equal(mistralFronted.success, true);+ assert.match(fetches[0].init.body.toString(), /name="diarize"/);++ fetches.length = 0;+ const unknownGateway = await invokeUpload({+ apiKey: "ck-custom",+ baseUrl: "https://gateway.example.com/v1",+ model: "whisper-1",+ provider: "custom",+ diarize: true,+ language: "",+ transcriptionMode: "providers",+ });+ assert.equal(unknownGateway.success, true, "an unknown gateway degrades, never fails");+ assert.doesNotMatch(fetches[0].init.body.toString(), /diarized_json/);+});++test("upload: a self-hosted Azure endpoint keeps its deployment URL", async () => {+ fetches.length = 0;+ const result = await invokeUpload({+ apiKey: "",+ baseUrl: "",+ model: "",+ provider: "custom",+ language: "",+ transcriptionMode: "self-hosted",+ remoteTranscriptionUrl: "https://myorg.openai.azure.com",+ remoteTranscriptionModel: "my-deployment",+ });+ assert.equal(result.success, true);+ assert.equal(+ fetches[0].url,+ "https://myorg.openai.azure.com/openai/deployments/my-deployment/audio/transcriptions?api-version=2025-03-01-preview"+ );+});diff --git a/test/helpers/retryTranscriptionRouting.test.js b/test/helpers/retryTranscriptionRouting.test.jsdeleted file mode 100644index 4e3d67845..000000000--- a/test/helpers/retryTranscriptionRouting.test.js+++ /dev/null@@ -1,145 +0,0 @@-const test = require("node:test");-const assert = require("node:assert/strict");--const load = () => import("../../src/helpers/retryTranscriptionRouting.js");--test("selects self-hosted retry routing over stale cloud settings", async () => {- const { resolveSelfHostedRetryRoute } = await load();-- for (const provider of ["groq", "openai", "mistral", "xai", "tinfoil", "custom"]) {- const route = resolveSelfHostedRetryRoute({- transcriptionMode: "self-hosted",- remoteTranscriptionUrl: "http://localhost:5001/v1",- remoteTranscriptionModel: " self-hosted-model ",- useLocalWhisper: true,- cloudTranscriptionMode: "openwhispr",- cloudTranscriptionProvider: provider,- cloudTranscriptionModel: "stale-cloud-model",- });-- assert.deepEqual(route, {- kind: "self-hosted",- endpoint: "http://localhost:5001/v1/audio/transcriptions",- model: "self-hosted-model",- });- }-});--test("normalizes supported self-hosted URLs and allows private HTTP endpoints", async () => {- const { resolveSelfHostedRetryRoute } = await load();- const cases = [- ["http://localhost:5001", "http://localhost:5001/audio/transcriptions"],- ["http://localhost:5001/v1", "http://localhost:5001/v1/audio/transcriptions"],- ["http://127.0.0.1:5001/v1", "http://127.0.0.1:5001/v1/audio/transcriptions"],- ["http://192.168.1.20:5001/v1", "http://192.168.1.20:5001/v1/audio/transcriptions"],- [- "http://localhost:5001/v1/audio/transcriptions",- "http://localhost:5001/v1/audio/transcriptions",- ],- [- " http://localhost:5001/v1/audio/transcriptions/// ",- "http://localhost:5001/v1/audio/transcriptions",- ],- ];-- for (const [remoteTranscriptionUrl, endpoint] of cases) {- const route = resolveSelfHostedRetryRoute({- transcriptionMode: "self-hosted",- remoteTranscriptionUrl,- });- assert.equal(route.kind, "self-hosted");- assert.equal(route.endpoint, endpoint);- }-});--test("fails closed for missing, malformed, or unsupported self-hosted URLs", async () => {- const { resolveSelfHostedRetryRoute } = await load();- const missingError = "Self-hosted transcription URL is not configured";- const invalidError = "Self-hosted transcription URL is invalid or unsupported";- const cases = [- [undefined, missingError],- [null, missingError],- ["", missingError],- [" ", missingError],- [42, missingError],- ["not a url", invalidError],- ["https://", invalidError],- ["ftp://localhost:5001/v1", invalidError],- ["http://example.com/v1", invalidError],- ];-- for (const [remoteTranscriptionUrl, error] of cases) {- assert.deepEqual(- resolveSelfHostedRetryRoute({- transcriptionMode: "self-hosted",- remoteTranscriptionUrl,- useLocalWhisper: true,- cloudTranscriptionMode: "openwhispr",- cloudTranscriptionProvider: "groq",- }),- {- kind: "configuration-error",- error,- }- );- }-});--test("does not intercept non-self-hosted retry modes", async () => {- const { resolveSelfHostedRetryRoute } = await load();-- for (const settings of [- { transcriptionMode: "local", useLocalWhisper: true },- { transcriptionMode: "openwhispr", cloudTranscriptionMode: "openwhispr" },- { transcriptionMode: "providers", cloudTranscriptionProvider: "tinfoil" },- { transcriptionMode: "providers", cloudTranscriptionProvider: "groq" },- {},- ]) {- assert.equal(resolveSelfHostedRetryRoute(settings), null);- }-});--test("custom transcription routes require a configured secure endpoint", async () => {- const { resolveCustomTranscriptionRoute } = await load();-- for (const baseUrl of [- undefined,- "",- "not a url",- "http://public.example.com/v1",- "ftp://192.168.1.20/v1",- "ws://192.168.1.20/v1",- ]) {- assert.deepEqual(resolveCustomTranscriptionRoute({ provider: "custom", baseUrl }), {- kind: "configuration-error",- error: "Custom transcription endpoint is invalid or unsupported",- });- }-- assert.deepEqual(- resolveCustomTranscriptionRoute({- provider: "custom",- baseUrl: "http://192.168.1.20:5001/v1",- }),- {- kind: "custom",- baseUrl: "http://192.168.1.20:5001/v1",- endpoint: "http://192.168.1.20:5001/v1/audio/transcriptions",- }- );- assert.deepEqual(- resolveCustomTranscriptionRoute({- provider: "custom",- baseUrl: "https://api.example.com/v1/audio/transcriptions",- }),- {- kind: "custom",- baseUrl: "https://api.example.com/v1",- endpoint: "https://api.example.com/v1/audio/transcriptions",- }- );- assert.equal(- resolveCustomTranscriptionRoute({ provider: "openai", baseUrl: "https://api.openai.com/v1" }),- null- );-});diff --git a/test/helpers/transcriptionErrorKeys.test.js b/test/helpers/transcriptionErrorKeys.test.jsindex 7feec656e..6bd8976ac 100644--- a/test/helpers/transcriptionErrorKeys.test.js+++ b/test/helpers/transcriptionErrorKeys.test.js@@ -8,7 +8,7 @@ const load = () => import("../../src/components/notes/shared.ts");// Codes chunkedCloudTranscribe and interpretTranscribeResponse surface to the// upload UI. Anything added there needs a locale key or it reaches the user as// a raw English main-process string.-const MAPPED_CODES = ["NO_SPEECH_DETECTED", "CHUNK_LOSS_EXCEEDED"];+const MAPPED_CODES = ["NO_SPEECH_DETECTED", "CHUNK_LOSS_EXCEEDED", "CUSTOM_ENDPOINT_INVALID"];test("every mapped code resolves to a key that exists in en", async () => {const { transcriptionErrorKey } = await load();diff --git a/test/helpers/transcriptionModelMemory.test.js b/test/helpers/transcriptionModelMemory.test.jsnew file mode 100644index 000000000..1a186c6f7--- /dev/null+++ b/test/helpers/transcriptionModelMemory.test.js@@ -0,0 +1,129 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++test("per-provider transcription model memory", async (t) => {+ installBrowserGlobals(t, {+ initialStorage: {+ _providerSettingsMigrated: "1",+ uploadTranscriptionMigrated: "true",+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionModel: "parasail-whisper-v3",+ cloudTranscriptionBaseUrl: "https://stt.parasail.example.com/v1",+ },+ });+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-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().switchCloudTranscriptionProvider("dictation", "tinfoil");+ assert.equal(state().cloudTranscriptionProvider, "tinfoil");+ assert.notEqual(state().cloudTranscriptionModel, "parasail-whisper-v3");+ assert.equal(+ state().cloudTranscriptionBaseUrl,+ "https://stt.parasail.example.com/v1",+ "the custom URL slot must never be touched by a provider switch"+ );++ state().switchCloudTranscriptionProvider("dictation", "custom");+ assert.equal(state().cloudTranscriptionProvider, "custom");+ assert.equal(state().cloudTranscriptionModel, "parasail-whisper-v3");+ });++ await t.test("reselecting the current provider keeps the current model", () => {+ state().setCloudTranscriptionModel("parasail-tuned");+ state().switchCloudTranscriptionProvider("dictation", "custom");+ assert.equal(state().cloudTranscriptionModel, "parasail-tuned");+ });++ await t.test("a remembered model that no longer matches the provider falls back", () => {+ state().switchCloudTranscriptionProvider("dictation", "groq");+ state().setCloudTranscriptionModel("retired-groq-model");+ state().switchCloudTranscriptionProvider("dictation", "custom");+ state().switchCloudTranscriptionProvider("dictation", "groq");+ assert.notEqual(+ state().cloudTranscriptionModel,+ "retired-groq-model",+ "an unknown remembered model must degrade to the provider default"+ );+ assert.match(state().cloudTranscriptionModel, /^whisper-large-v3/);+ });++ await t.test("scopes have independent memory and writes", () => {+ state().switchCloudTranscriptionProvider("dictation", "custom");+ const dictationModel = state().cloudTranscriptionModel;++ state().switchCloudTranscriptionProvider("upload", "groq");+ assert.equal(state().uploadCloudTranscriptionProvider, "groq");+ assert.match(state().uploadCloudTranscriptionModel, /^whisper-large-v3/);+ assert.equal(state().cloudTranscriptionProvider, "custom", "base scope untouched");+ assert.equal(state().cloudTranscriptionModel, dictationModel, "base scope untouched");+ });++ await t.test("memory persists to localStorage as JSON", () => {+ const persisted = JSON.parse(localStorage.getItem("transcriptionModelByProvider"));+ assert.equal(typeof persisted, "object");+ assert.ok(Object.keys(persisted).some((key) => key.startsWith("dictation:")));+ });++ await t.test("meeting scope restores only streaming-capable models", () => {+ state().switchCloudTranscriptionProvider("meeting", "openai");+ // A remembered batch-only model must not survive into the streaming-filtered+ // meeting scope; the streaming default wins instead.+ const restored = state().meetingCloudTranscriptionModel;+ assert.notEqual(restored, "");+ state().setMeetingCloudTranscriptionModel("gpt-4o-mini-transcribe");+ state().switchCloudTranscriptionProvider("meeting", "groq");+ state().switchCloudTranscriptionProvider("meeting", "openai");+ assert.notEqual(state().meetingCloudTranscriptionModel, "");+ });++ // The picker no longer writes the provider itself — switchCloudTranscriptionProvider+ // is the single writer for both keys, so it must land the provider on its own.+ await t.test("the switch writes the provider key for every scope", () => {+ state().switchCloudTranscriptionProvider("dictation", "groq");+ assert.equal(state().cloudTranscriptionProvider, "groq");+ state().switchCloudTranscriptionProvider("meeting", "openai");+ assert.equal(state().meetingCloudTranscriptionProvider, "openai");+ state().switchCloudTranscriptionProvider("upload", "custom");+ assert.equal(state().uploadCloudTranscriptionProvider, "custom");+ });++ await t.test("an unknown context is a no-op, not a crash", () => {+ const before = { ...state() };+ state().switchCloudTranscriptionProvider("nonexistent", "groq");+ assert.equal(state().cloudTranscriptionProvider, before.cloudTranscriptionProvider);+ assert.equal(state().cloudTranscriptionModel, before.cloudTranscriptionModel);+ });++ await t.test("setCloudTranscriptionForAllScopes seeds memory in every scope", () => {+ state().setCloudTranscriptionForAllScopes({+ useLocalWhisper: false,+ cloudTranscriptionMode: "byok",+ cloudTranscriptionProvider: "corti",+ cloudTranscriptionModel: "corti-transcribe",+ });+ const memory = state().transcriptionModelByProvider;+ for (const context of ["dictation", "meeting", "upload"]) {+ assert.equal(memory[`${context}:corti`], "corti-transcribe");+ }+ });+});++test("corrupt persisted model memory hydrates as empty, not a crash", async (t) => {+ installBrowserGlobals(t, {+ initialStorage: {+ _providerSettingsMigrated: "1",+ uploadTranscriptionMigrated: "true",+ transcriptionModelByProvider: "{not json",+ },+ });+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-model-memory-corrupt-test-",+ });+ const { useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");+ assert.deepEqual(useSettingsStore.getState().transcriptionModelByProvider, {});+});diff --git a/test/helpers/transcriptionRoute.test.js b/test/helpers/transcriptionRoute.test.jsnew file mode 100644index 000000000..233a40320--- /dev/null+++ b/test/helpers/transcriptionRoute.test.js@@ -0,0 +1,272 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/helpers/transcriptionRoute.ts");++const resolve = async (settings, extra = {}) => {+ const { resolveTranscriptionRoute } = await load();+ return resolveTranscriptionRoute({ settings, ...extra });+};++const MANAGED_OPENAI_ONLY = {+ status: "managed",+ appVersion: "1.8.2",+ policy: {+ version: 1,+ transcription: { allowedModes: ["providers"], allowedByokProviders: ["openai"] },+ llm: { allowedModes: [], allowedByokProviders: [], allowedEnterpriseProviders: [] },+ features: { agentEnabled: false, webSearchEnabled: false },+ sharing: { externalLinkSharing: "disabled" },+ dataRetention: {+ audioRetentionMaxDays: null,+ localHistoryMode: "user_choice",+ cloudBackupAllowed: false,+ },+ minAppVersion: null,+ },+};++test("self-hosted routes to the configured server and wins over stale flags", async () => {+ const route = await resolve({+ transcriptionMode: "self-hosted",+ remoteTranscriptionUrl: "http://192.168.1.5:11434/v1",+ remoteTranscriptionModel: "whisper-1",+ useLocalWhisper: true,+ cloudTranscriptionProvider: "mistral",+ });+ assert.equal(route.transport, "http-batch");+ assert.equal(route.provider, "self-hosted");+ assert.equal(route.endpoint, "http://192.168.1.5:11434/v1/audio/transcriptions");+ assert.deepEqual(route.auth, { scheme: "none", keyRef: null });+ assert.equal(route.sizeCapBytes, null);+});++test("self-hosted mode without a URL fails closed unless the provider is custom", async () => {+ for (const provider of ["openai", "groq", "mistral", "xai", "corti", "tinfoil"]) {+ const route = await resolve({+ transcriptionMode: "self-hosted",+ remoteTranscriptionUrl: "",+ cloudTranscriptionProvider: provider,+ });+ assert.equal(route.transport, "error", provider);+ assert.match(route.message, /not configured/, provider);+ }++ // byok+custom persists transcriptionMode="self-hosted" (deriveTranscriptionMode),+ // so a custom user with a cleared remote URL must still reach their endpoint.+ const customRoute = await resolve({+ transcriptionMode: "self-hosted",+ remoteTranscriptionUrl: "",+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionBaseUrl: "https://stt.parasail.example.com/v1",+ });+ assert.equal(customRoute.transport, "http-batch");+ assert.equal(customRoute.provider, "custom");+ assert.equal(customRoute.endpoint, "https://stt.parasail.example.com/v1/audio/transcriptions");+});++test("self-hosted fails closed on invalid or public-http URLs", async () => {+ for (const remoteTranscriptionUrl of [+ "not a url",+ "ftp://localhost:8080",+ "http://example.com/v1",+ ]) {+ const route = await resolve({+ transcriptionMode: "self-hosted",+ remoteTranscriptionUrl,+ cloudTranscriptionProvider: "openai",+ });+ assert.equal(route.transport, "error", remoteTranscriptionUrl);+ assert.match(route.message, /invalid or unsupported/, remoteTranscriptionUrl);+ }+});++test("local mode yields a bare local route; decode details stay with the local managers", async () => {+ assert.deepEqual(await resolve({ useLocalWhisper: true, whisperModel: "small" }), {+ transport: "local",+ });+});++test("proxied providers carry their quirks as route data", async () => {+ const tinfoil = await resolve({ cloudTranscriptionProvider: "tinfoil" });+ assert.equal(tinfoil.transport, "proxied");+ assert.equal(tinfoil.model, null, "tinfoil's attested client resolves its own model");++ const mistral = await resolve({+ cloudTranscriptionProvider: "mistral",+ cloudTranscriptionModel: "voxtral-small-latest",+ });+ assert.equal(mistral.model, "voxtral-small-latest");++ const xai = await resolve({+ cloudTranscriptionProvider: "xai",+ preferredLanguage: "mk",+ });+ assert.equal(xai.model, "grok-stt", "recorded for history; executors omit the form field");+ assert.equal(xai.language, "mk");+ const xaiUnsupported = await resolve({+ cloudTranscriptionProvider: "xai",+ preferredLanguage: "yo",+ });+ assert.equal(xaiUnsupported.language, undefined, "outside the xAI ITN allowlist");++ const corti = await resolve({ cloudTranscriptionProvider: "corti", cortiTenant: " acme " });+ assert.equal(corti.model, "corti-transcribe");+ assert.equal(corti.language, "en", "Corti needs a concrete language even on auto");+ assert.equal(corti.cortiEnvironment, "us");+ assert.equal(corti.cortiTenant, "acme");+});++test("custom requires a configured secure endpoint (empty, sentinel, garbage all fail)", async () => {+ const { resolveTranscriptionRoute } = await load();+ for (const cloudTranscriptionBaseUrl of [+ "",+ " ",+ "https://api.openai.com/v1", // the untouched store default+ "not a url",+ "http://public.example.com/v1",+ "ftp://192.168.1.20/v1",+ ]) {+ const route = resolveTranscriptionRoute({+ settings: { cloudTranscriptionProvider: "custom", cloudTranscriptionBaseUrl },+ });+ assert.equal(route.transport, "error", cloudTranscriptionBaseUrl);+ assert.equal(route.code, "CUSTOM_ENDPOINT_INVALID", cloudTranscriptionBaseUrl);+ }++ const localhost = await resolve({+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionBaseUrl: "http://localhost:1234/v1",+ cloudTranscriptionModel: "my-model",+ });+ assert.equal(localhost.transport, "http-batch");+ assert.equal(localhost.endpoint, "http://localhost:1234/v1/audio/transcriptions");+ assert.equal(localhost.model, "my-model");+ assert.deepEqual(localhost.auth, { scheme: "bearer", keyRef: "custom" });+});++test("a custom URL pointing at Tinfoil's host must use the attested proxy", async () => {+ const route = await resolve(+ {+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionBaseUrl: "https://inference.tinfoil.sh/v1",+ },+ { providers: [{ id: "tinfoil", baseUrl: "https://inference.tinfoil.sh/v1" }] }+ );+ assert.equal(route.transport, "error");+ assert.match(route.message, /attested main-process proxy/);+});++test("Azure custom endpoints build deployment URLs from the raw base", async () => {+ const route = await resolve({+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionBaseUrl: "https://myres.openai.azure.com",+ cloudTranscriptionModel: "my-deployment",+ });+ assert.equal(+ route.endpoint,+ "https://myres.openai.azure.com/openai/deployments/my-deployment/audio/transcriptions?api-version=2025-03-01-preview"+ );+ assert.deepEqual(route.auth, { scheme: "azure-api-key", keyRef: "custom" });++ // A user-pinned full path survives — normalization must not strip it.+ const pinned = await resolve({+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionBaseUrl:+ "https://myres.openai.azure.com/openai/deployments/d1/audio/transcriptions?api-version=2024-06-01",+ cloudTranscriptionModel: "ignored",+ });+ assert.match(pinned.endpoint, /deployments\/d1\/audio\/transcriptions\?api-version=2024-06-01/);+});++// migrateProviderSettings files every legacy `custom + byok` user under+// transcriptionMode "self-hosted" and copies their base URL across, so Azure+// endpoints reach the resolver through this branch too.+test("Azure self-hosted endpoints build deployment URLs, like Custom ones", async () => {+ const route = await resolve({+ transcriptionMode: "self-hosted",+ remoteTranscriptionUrl: "https://myres.openai.azure.com",+ remoteTranscriptionModel: "my-deployment",+ });+ assert.equal(route.provider, "self-hosted");+ assert.equal(+ route.endpoint,+ "https://myres.openai.azure.com/openai/deployments/my-deployment/audio/transcriptions?api-version=2025-03-01-preview"+ );++ const pinned = await resolve({+ transcriptionMode: "self-hosted",+ remoteTranscriptionUrl:+ "https://myres.openai.azure.com/openai/deployments/d1/audio/transcriptions?api-version=2024-06-01",+ remoteTranscriptionModel: "ignored",+ });+ assert.match(pinned.endpoint, /deployments\/d1\/audio\/transcriptions\?api-version=2024-06-01/);++ // Non-Azure self-hosted servers keep the plain OpenAI-compatible path.+ const plain = await resolve({+ transcriptionMode: "self-hosted",+ remoteTranscriptionUrl: "https://stt.internal.example.com",+ remoteTranscriptionModel: "tiny",+ });+ assert.equal(plain.endpoint, "https://stt.internal.example.com/audio/transcriptions");+});++test("openai and groq route to fixed endpoints with provider-validated models", async () => {+ const openai = await resolve({});+ assert.equal(openai.provider, "openai");+ assert.equal(openai.endpoint, "https://api.openai.com/v1/audio/transcriptions");+ assert.equal(openai.model, "gpt-4o-mini-transcribe");+ assert.equal(openai.sizeCapBytes, 25 * 1024 * 1024);++ const groqStale = await resolve({+ cloudTranscriptionProvider: "groq",+ cloudTranscriptionModel: "voxtral-mini-latest", // stale from a mistral era+ });+ assert.equal(groqStale.endpoint, "https://api.groq.com/openai/v1/audio/transcriptions");+ assert.equal(groqStale.model, "whisper-large-v3-turbo", "mismatched model degrades to default");+ assert.deepEqual(groqStale.auth, { scheme: "bearer", keyRef: "groq" });+});++test("managed policy is a fail-closed floor", async () => {+ const blocked = await resolve(+ { transcriptionMode: "providers", cloudTranscriptionProvider: "groq" },+ { policy: MANAGED_OPENAI_ONLY }+ );+ assert.equal(blocked.transport, "error");+ assert.equal(blocked.code, "POLICY_RESTRICTED");++ const allowed = await resolve(+ { transcriptionMode: "providers", cloudTranscriptionProvider: "openai" },+ { policy: MANAGED_OPENAI_ONLY }+ );+ assert.equal(allowed.transport, "http-batch");++ // Managed orgs see the policy message for a broken custom endpoint, never+ // the config hint (pins the Phase 1 precedence).+ const managedCustom = await resolve(+ {+ transcriptionMode: "providers",+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionBaseUrl: "",+ },+ {+ policy: {+ ...MANAGED_OPENAI_ONLY,+ policy: {+ ...MANAGED_OPENAI_ONLY.policy,+ transcription: { allowedModes: ["providers"], allowedByokProviders: ["custom"] },+ },+ },+ }+ );+ assert.equal(managedCustom.code, "POLICY_RESTRICTED");+});++test("request overrides win: explicit model and effective language", async () => {+ const route = await resolve(+ { cloudTranscriptionProvider: "groq", preferredLanguage: "de-DE" },+ { request: { model: "whisper-large-v3", effectiveLanguage: "ja" } }+ );+ assert.equal(route.model, "whisper-large-v3");+ assert.equal(route.language, "ja");+});diff --git a/test/helpers/transcriptionRouteModelAgreement.test.js b/test/helpers/transcriptionRouteModelAgreement.test.jsnew file mode 100644index 000000000..69aa37132--- /dev/null+++ b/test/helpers/transcriptionRouteModelAgreement.test.js@@ -0,0 +1,75 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const registry = require("../../src/models/modelRegistryData.json");+const load = () => import("../../src/helpers/transcriptionRoute.ts");++// resolveByokModel validates by prefix so it can run in the packaged main process+// without the registry, which means the two can silently drift apart. Every model+// the picker can write must survive a round trip through the resolver, or a user+// who picks it has their choice replaced by the provider default at request time.+//+// Tinfoil is excluded: its batch model comes from the registry directly+// (getBatchTranscriptionModel) and the route sends none.+const PREFIX_VALIDATED_PROVIDERS = ["openai", "groq", "xai", "mistral", "corti"];++test("every shipping registry model survives resolveByokModel", async () => {+ const { resolveByokModel } = await load();++ for (const providerId of PREFIX_VALIDATED_PROVIDERS) {+ const provider = registry.transcriptionProviders.find((p) => p.id === providerId);+ assert.ok(provider, `registry is missing provider ${providerId}`);++ for (const model of provider.models) {+ assert.equal(+ resolveByokModel(providerId, model.id),+ model.id,+ `${providerId}/${model.id} is offered by the picker but rewritten by the resolver`+ );+ }+ }+});++test("each provider's fallback default is a model that provider actually offers", async () => {+ const { resolveByokModel } = await load();++ for (const providerId of PREFIX_VALIDATED_PROVIDERS) {+ const provider = registry.transcriptionProviders.find((p) => p.id === providerId);+ const fallback = resolveByokModel(providerId, "a-model-from-another-provider");+ assert.ok(+ provider.models.some((m) => m.id === fallback),+ `${providerId} falls back to ${fallback}, which it does not offer`+ );+ }+});++test("custom keeps any non-empty model and defaults to whisper-1", async () => {+ const { resolveByokModel } = await load();++ assert.equal(resolveByokModel("custom", "parasail-whisper-v3"), "parasail-whisper-v3");+ assert.equal(resolveByokModel("custom", " spaced-model "), "spaced-model");+ assert.equal(resolveByokModel("custom", ""), "whisper-1");+ assert.equal(resolveByokModel("custom", undefined), "whisper-1");+});++// The leniency is deliberate: a retired id (e.g. the voxtral-small entry that+// shipped in #1120) must keep working rather than be reset out from under a user.+test("a retired provider-shaped model id is preserved, not reset", async () => {+ const { resolveByokModel } = await load();++ assert.equal(resolveByokModel("mistral", "voxtral-small-latest"), "voxtral-small-latest");+ assert.equal(resolveByokModel("groq", "whisper-large-v3-en"), "whisper-large-v3-en");+ assert.equal(+ resolveByokModel("openai", "gpt-4o-transcribe-diarize"),+ "gpt-4o-transcribe-diarize"+ );+});++test("a model belonging to another provider degrades to the provider default", async () => {+ const { resolveByokModel } = await load();++ assert.equal(resolveByokModel("groq", "gpt-4o-mini-transcribe"), "whisper-large-v3-turbo");+ assert.equal(resolveByokModel("openai", "voxtral-mini-latest"), "gpt-4o-mini-transcribe");+ assert.equal(resolveByokModel("mistral", "whisper-1"), "voxtral-mini-latest");+ assert.equal(resolveByokModel("corti", "whisper-1"), "corti-transcribe");+});diff --git a/test/services/fileTranscriptionCustomEndpoint.test.js b/test/services/fileTranscriptionCustomEndpoint.test.jsindex 7d542baa7..5ae4eae7d 100644--- a/test/services/fileTranscriptionCustomEndpoint.test.js+++ b/test/services/fileTranscriptionCustomEndpoint.test.js@@ -34,13 +34,43 @@ test("file transcription enforces Custom endpoint security before IPC", async (treturn { success: true, text: "must not run" };};- for (const baseUrl of ["", "http://public.example.com/v1", "ftp://192.168.1.20/v1"]) {+ for (const baseUrl of [+ "",+ // The untouched store default — Custom selected but never configured.+ "https://api.openai.com/v1",+ "http://public.example.com/v1",+ "ftp://192.168.1.20/v1",+ ]) {const result = await transcribeFile("/tmp/audio.webm", customConfig(baseUrl), false);- assert.equal(result.success, false);- assert.equal(result.code, "CUSTOM_ENDPOINT_INVALID");+ assert.equal(result.success, false, baseUrl);+ assert.equal(result.code, "CUSTOM_ENDPOINT_INVALID", baseUrl);}++ // A Custom URL pointing at Tinfoil's host returns a failure (not a throw)+ // so the upload UI shows it like any other config error.+ const tinfoilResult = await transcribeFile(+ "/tmp/audio.webm",+ customConfig("https://inference.tinfoil.sh/v1"),+ false+ );+ assert.equal(tinfoilResult.success, false);+ assert.match(tinfoilResult.error, /attested main-process proxy/);assert.equal(ipcCalls, 0);+ // Built-in providers ignore the stored custom URL entirely.+ window.electronAPI.transcribeAudioFileByok = async () => {+ ipcCalls += 1;+ return { success: true, text: "groq ok" };+ };+ const groqResult = await transcribeFile(+ "/tmp/audio.webm",+ { ...customConfig("ftp://garbage"), cloudTranscriptionProvider: "groq" },+ false+ );+ assert.equal(groqResult.success, true);+ assert.equal(ipcCalls, 1);+ ipcCalls = 0;+let receivedOptions = null;window.electronAPI.transcribeAudioFileByok = async (options) => {receivedOptions = options;diff --git a/test/services/transcriptionBaseUrl.test.js b/test/services/transcriptionBaseUrl.test.jsindex 36c023ad2..4d051c549 100644--- a/test/services/transcriptionBaseUrl.test.js+++ b/test/services/transcriptionBaseUrl.test.js@@ -24,27 +24,6 @@ const PROVIDERS = [{ id: "tinfoil", baseUrl: "https://inference.tinfoil.sh/v1" },];-test("custom provider resolves to the stored URL, untouched", async () => {- const { resolveByokBaseUrl } = await load();- assert.equal(- resolveByokBaseUrl("custom", "http://127.0.0.1:8587/v1", PROVIDERS),- "http://127.0.0.1:8587/v1"- );-});--test("built-in provider resolves from the registry, ignoring a stored custom URL", async () => {- const { resolveByokBaseUrl } = await load();- assert.equal(- resolveByokBaseUrl("groq", "http://127.0.0.1:8587/v1", PROVIDERS),- "https://api.groq.com/openai/v1"- );-});--test("unknown provider resolves to empty so callers fail closed", async () => {- const { resolveByokBaseUrl } = await load();- assert.equal(resolveByokBaseUrl("nonexistent", "http://127.0.0.1:8587/v1", PROVIDERS), "");-});-test("detects Tinfoil's inference host regardless of path or trailing slash", async () => {const { isTinfoilInferenceUrl } = await load();assert.equal(isTinfoilInferenceUrl("https://inference.tinfoil.sh/v1", PROVIDERS), true);