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
fix(policy): harden managed provider enforcement
Gabriel Steincc9ebe0b37aa
diff --cc src/components/ReasoningModelSelector.tsxindex c4bee3fca,64f8b3a88..66f1a8a60--- a/src/components/ReasoningModelSelector.tsx+++ b/src/components/ReasoningModelSelector.tsx@@@ -24,11 -24,7 +24,12 @@@ import { getRemoteProviderIcon } from "import { GetApiKeyLink } from "./ui/GetApiKeyLink";import { getCachedPlatform } from "../utils/platform";import { useSettingsStore } from "../stores/settingsStore";-import { isProviderAllowedByPolicy } from "../stores/policyRules";+import {+ filterByokProviderOptionsByPolicy,++ isModeAllowedByPolicy,+ isProviderAllowedByPolicy,+ reconcileProviderSelection,+} from "../stores/policyRules";import { usePolicySnapshot } from "../hooks/usePolicy";type CloudModelOption = {@@@ -349,39 -345,34 +350,50 @@@ export default function ReasoningModelSconst [selectedMode, setSelectedMode] = useState<"cloud" | "local">(mode || "cloud");const [selectedCloudProvider, setSelectedCloudProvider] = useState("openai");const [selectedLocalProvider, setSelectedLocalProvider] = useState("qwen");-- const {-- models: tinfoilModels,-- loading: tinfoilModelsLoading,-- error: tinfoilModelsError,-- } = useTinfoilModels(selectedCloudProvider === "tinfoil");const policyState = usePolicySnapshot();const providerAllowed = useCallback((providerId: string) => isProviderAllowedByPolicy(policyState, "llm", providerId),[policyState]);-- const effectiveMode = mode || selectedMode;--- const cloudProviderTabs = CLOUD_PROVIDER_IDS.map((id): ProviderTabItem => {- const tab = {- id,- name:- id === "custom"- ? t("reasoning.custom.providerName")- : id === OPENROUTER_TAB- ? "OpenRouter"- : REASONING_PROVIDERS[id as keyof typeof REASONING_PROVIDERS]?.name || id,- };- return providerAllowed(id)- ? tab- : { ...tab, disabled: true, disabledLabel: t("common.managedByOrg") };- });- const cloudProviders = cloudProviderTabs.filter((tab) => !tab.disabled);+ const cloudProviderTabs = useMemo(+ () =>+ filterByokProviderOptionsByPolicy(+ CLOUD_PROVIDER_IDS.map((id): ProviderTabItem => ({+ id,+ name:+ id === "custom"+ ? t("reasoning.custom.providerName")+ : id === OPENROUTER_TAB+ ? "OpenRouter"+ : REASONING_PROVIDERS[id as keyof typeof REASONING_PROVIDERS]?.name || id,+ })),+ "llm",+ policyState+ ),+ [policyState, t]+ );+ const cloudProviders = cloudProviderTabs;+ const cloudProviderFallback = reconcileProviderSelection(selectedCloudProvider, cloudProviders);+ const displayedCloudProvider = cloudProviderFallback ?? selectedCloudProvider;++ const {++ models: tinfoilModels,++ loading: tinfoilModelsLoading,++ error: tinfoilModelsError,++ } = useTinfoilModels(displayedCloudProvider === "tinfoil");++ const modeTabs = [++ ...(isModeAllowedByPolicy(policyState, "llm", "providers") && cloudProviders.length > 0++ ? [{ id: "cloud", name: t("reasoning.mode.cloud") }]++ : []),++ ...(isModeAllowedByPolicy(policyState, "llm", "local")++ ? [{ id: "local", name: t("reasoning.mode.local") }]++ : []),++ ];++ const effectiveMode =++ mode ??++ (modeTabs.some((tab) => tab.id === selectedMode)++ ? selectedMode++ : (modeTabs[0]?.id as "cloud" | "local" | undefined));const localProviders = useMemo<LocalProvider[]>(() => {return modelRegistry.getAllProviders().map((provider) => ({@@@ -463,30 -454,27 +475,33 @@@return new Set<string>();}, []);- const selectDefaultModelForProvider = (provider: string) => {- // Custom/OpenRouter fetch their model list dynamically — clear instead of- // presetting so another provider's model id can't persist under this one.- if (provider === "custom" || provider === OPENROUTER_TAB) {- setReasoningModel("");- return;- }+ const selectDefaultModelForProvider = useCallback(+ (provider: string) => {+ // Custom/OpenRouter fetch their model list dynamically — clear instead of+ // presetting so another provider's model id can't persist under this one.+ if (provider === "custom" || provider === OPENROUTER_TAB) {+ setReasoningModel("");+ return;+ }- if (provider === "tinfoil") {- const defaultModel = pickDefaultTinfoilModel(tinfoilModels);- if (defaultModel) setReasoningModel(defaultModel.id);- return;- }+ if (provider === "tinfoil") {+ const defaultModel = pickDefaultTinfoilModel(tinfoilModels);+ if (defaultModel) setReasoningModel(defaultModel.id);+ return;+ }- const providerData = REASONING_PROVIDERS[provider as keyof typeof REASONING_PROVIDERS];- if (providerData?.models?.length > 0) {- setReasoningModel(providerData.models[0].value);- }- };+ const providerData = REASONING_PROVIDERS[provider as keyof typeof REASONING_PROVIDERS];+ if (providerData?.models?.length > 0) {+ setReasoningModel(providerData.models[0].value);+ }+ },+ [setReasoningModel, tinfoilModels]+ );const handleModeChange = async (newMode: "cloud" | "local") => {++ const policyMode = newMode === "local" ? "local" : "providers";++ if (!isModeAllowedByPolicy(policyState, "llm", policyMode)) return;++ if (newMode === "cloud" && cloudProviders.length === 0) return;setSelectedMode(newMode);setReasoningModeProp?.(newMode === "local" ? "local" : "providers");@@@ -549,11 -534,11 +564,6 @@@setReasoningModel(modelId);};-- const MODE_TABS = [-- { id: "cloud", name: t("reasoning.mode.cloud") },-- { id: "local", name: t("reasoning.mode.local") },-- ];--const renderModeIcon = (id: string) => {if (id === "cloud") return <Cloud className="w-4 h-4" />;return <Lock className="w-4 h-4" />;@@@ -563,18 -548,18 +573,24 @@@<div className="space-y-4">{!mode && (<div className="space-y-2">-- <ProviderTabs-- providers={MODE_TABS}-- selectedId={effectiveMode}-- onSelect={(id) => handleModeChange(id as "cloud" | "local")}-- renderIcon={renderModeIcon}-- colorScheme="purple"-- />-- <p className="text-xs text-muted-foreground text-center">-- {effectiveMode === "local"-- ? t("reasoning.mode.localDescription")-- : t("reasoning.mode.cloudDescription")}-- </p>++ {modeTabs.length > 0 ? (++ <>++ <ProviderTabs++ providers={modeTabs}++ selectedId={effectiveMode}++ onSelect={(id) => handleModeChange(id as "cloud" | "local")}++ renderIcon={renderModeIcon}++ colorScheme="purple"++ />++ <p className="text-xs text-muted-foreground text-center">++ {effectiveMode === "local"++ ? t("reasoning.mode.localDescription")++ : t("reasoning.mode.cloudDescription")}++ </p>++ </>++ ) : (++ <p className="text-xs text-muted-foreground text-center">{t("common.managedByOrg")}</p>++ )}</div>)}diff --cc src/components/SettingsPage.tsxindex c186d3cb8,12b0c90a0..8cbf95bfb--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@@ -106,7 -106,7 +106,11 @@@ import { Popover, PopoverContent, Popovimport { startMigration, useMigration } from "../stores/noteStore.js";import { syncService } from "../services/SyncService.js";import { formatBytes } from "../utils/formatBytes";--import { clearMissingLocalModelSelections, useSettingsStore } from "../stores/settingsStore";++import {++ clearMissingLocalModelSelections,++ TRANSCRIPTION_POLICY_PROVIDER_IDS,++ useSettingsStore,++} from "../stores/settingsStore";import { useWorkspaceStore } from "../stores/workspaceStore";import {canChangeCloudBackupPreference,@@@ -313,9 -307,9 +317,10 @@@ function TranscriptionSection(icon: <Network className="w-4 h-4" />,},],- "transcription"+ "transcription",- transcriptionMode++ transcriptionMode,++ { byokProviders: TRANSCRIPTION_POLICY_PROVIDER_IDS });-const handleTranscriptionModeSelect = (mode: InferenceMode) => {if (!isModeAllowed(mode)) return;if (mode === "openwhispr" && !isSignedIn) {diff --cc src/components/TranscriptionModelPicker.tsxindex db3be70f9,be7e17a1c..1de7423e4--- a/src/components/TranscriptionModelPicker.tsx+++ b/src/components/TranscriptionModelPicker.tsx@@@ -485,22 -482,23 +485,24 @@@ export default function TranscriptionMo// Every provider's URL counts as known, including policy-blocked ones:// otherwise a blocked provider's stored URL reads as a custom endpoint and// reconciliation would keep pointing "custom" at what policy just denied.-- const knownProviderUrls = availableCloudProviders.map((provider) => provider.baseUrl);++ const knownProviderUrls = new Set(++ availableCloudProviders.map((provider) => normalizeBaseUrl(provider.baseUrl))++ );++ const normalizedBaseUrl = normalizeBaseUrl(cloudTranscriptionBaseUrl);const hasCustomUrl = Boolean(-- cloudTranscriptionBaseUrl &&-- cloudTranscriptionBaseUrl.trim() !== "" &&-- cloudTranscriptionBaseUrl !== API_ENDPOINTS.TRANSCRIPTION_BASE &&-- !knownProviderUrls.includes(cloudTranscriptionBaseUrl)++ normalizedBaseUrl &&++ normalizedBaseUrl !== normalizeBaseUrl(API_ENDPOINTS.TRANSCRIPTION_BASE) &&++ !knownProviderUrls.has(normalizedBaseUrl)+ );+ return (+ reconcileCloudProviderSelection({+ selectedProvider: selectedCloudProvider,+ selectedModel: selectedCloudModel,+ allowedProviders: cloudProviders,+ customAllowed: !streamingOnly && providerAllowed("custom"),+ hasCustomUrl,+ }) ?? { provider: selectedCloudProvider, model: selectedCloudModel });- const selection = reconcileCloudProviderSelection({- selectedProvider: selectedCloudProvider,- selectedModel: selectedCloudModel,- allowedProviders: cloudProviders,- customAllowed: providerAllowed("custom"),- hasCustomUrl,- });- if (!selection) return;- if (selection.provider !== selectedCloudProvider) onCloudProviderSelect(selection.provider);- if (selection.model !== selectedCloudModel) onCloudModelSelect(selection.model);}, [availableCloudProviders,cloudProviders,@@@ -661,10 -637,14 +663,13 @@@const handleModeChange = useCallback((isLocal: boolean) => {onModeChange(isLocal);- if (!isLocal) ensureValidCloudSelection();},- [onModeChange, ensureValidCloudSelection]+ [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).const handleCloudProviderChange = useCallback((providerId: string) => {if (!providerAllowed(providerId)) return;diff --cc src/components/notes/NotesOnboarding.tsxindex 3cfadecd6,3cfadecd6..9bd670546--- a/src/components/notes/NotesOnboarding.tsx+++ b/src/components/notes/NotesOnboarding.tsx@@@ -1,9 -1,9 +1,14 @@@import { useState, useEffect, useCallback } from "react";++import { useShallow } from "zustand/react/shallow";import { useTranslation } from "react-i18next";import { Sparkles, Plus, ChevronRight, Zap, Loader2, Check, Monitor } from "lucide-react";import { Button } from "../ui/button";import { cn } from "../lib/utils";--import { useSettingsStore } from "../../stores/settingsStore";++import {++ selectPolicyEffectiveSettings,++ selectResolvedLLMConfig,++ useSettingsStore,++} from "../../stores/settingsStore";import { useNotesOnboarding } from "../../hooks/useNotesOnboarding";import {useActions,@@@ -17,6 -17,6 +22,7 @@@ import { AlertDialog } from "../ui/dialimport ReasoningModelSelector from "../ReasoningModelSelector";import { useSystemAudioPermission } from "../../hooks/useSystemAudioPermission";import { canManageSystemAudioInApp } from "../../utils/systemAudioAccess";++import { usePolicySnapshot } from "../../hooks/usePolicy";interface NotesOnboardingProps {onComplete: () => void;@@@ -34,14 -34,14 +40,19 @@@ export default function NotesOnboardingconst [isSaving, setIsSaving] = useState(false);const [justCreated, setJustCreated] = useState(false);-- const cleanupModel = useSettingsStore((s) => s.cleanupModel);++ const policyState = usePolicySnapshot();++ const cleanupConfig = useSettingsStore(++ useShallow((settings) =>++ selectResolvedLLMConfig(++ selectPolicyEffectiveSettings(settings, policyState),++ "dictationCleanup"++ )++ )++ );const setCleanupModel = useSettingsStore((s) => s.setCleanupModel);-- const cleanupProvider = useSettingsStore((s) => s.cleanupProvider);const setCleanupProvider = useSettingsStore((s) => s.setCleanupProvider);const setCleanupMode = useSettingsStore((s) => s.setCleanupMode);-- const cleanupCloudBaseUrl = useSettingsStore((s) => s.cleanupCloudBaseUrl);const setCleanupCloudBaseUrl = useSettingsStore((s) => s.setCleanupCloudBaseUrl);-- const cleanupCustomApiKey = useSettingsStore((s) => s.cleanupCustomApiKey);const setCleanupCustomApiKey = useSettingsStore((s) => s.setCleanupCustomApiKey);const { alertDialog, hideAlertDialog } = useDialogs();@@@ -159,13 -159,13 +170,13 @@@</p><ReasoningModelSelector-- reasoningModel={cleanupModel}++ reasoningModel={cleanupConfig.model}setReasoningModel={setCleanupModel}-- localReasoningProvider={cleanupProvider}++ localReasoningProvider={cleanupConfig.provider}setLocalReasoningProvider={setCleanupProvider}-- cloudReasoningBaseUrl={cleanupCloudBaseUrl}++ cloudReasoningBaseUrl={cleanupConfig.cloudBaseUrl ?? ""}setCloudReasoningBaseUrl={setCleanupCloudBaseUrl}-- customReasoningApiKey={cleanupCustomApiKey}++ customReasoningApiKey={cleanupConfig.customApiKey ?? ""}setCustomReasoningApiKey={setCleanupCustomApiKey}setReasoningMode={setCleanupMode}/>diff --cc src/components/settings/InferenceConfigEditor.tsxindex ab897b221,4539d095d..c2080c533--- a/src/components/settings/InferenceConfigEditor.tsx+++ b/src/components/settings/InferenceConfigEditor.tsx@@@ -3,8 -3,7 +3,10 @@@ import { useShallow } from "zustand/reaimport { useTranslation } from "react-i18next";import { Cloud, Key, Cpu, Network, Building2 } from "lucide-react";import {++ LLM_ENTERPRISE_POLICY_PROVIDER_IDS,++ LLM_POLICY_PROVIDER_IDS,useSettingsStore,+ selectPolicyEffectiveSettings,selectResolvedLLMConfig,setResolvedLLMConfig,} from "../../stores/settingsStore";@@@ -85,8 -79,7 +87,12 @@@ export default function InferenceConfigicon: <Building2 className="w-4 h-4" />,},],- "llm"+ "llm",- config.mode++ config.mode,++ {++ byokProviders: LLM_POLICY_PROVIDER_IDS,++ enterpriseProviders: LLM_ENTERPRISE_POLICY_PROVIDER_IDS,++ });const setField = useCallback(diff --cc src/components/settings/MeetingSettings.tsxindex 3bb1cde32,a7a2a6a25..98445f12d--- a/src/components/settings/MeetingSettings.tsx+++ b/src/components/settings/MeetingSettings.tsx@@@ -86,14 -77,16 +86,17 @@@ export function MeetingTranscriptionPanlabel: t("settingsPage.transcription.modes.selfHosted"),description: t("settingsPage.transcription.modes.selfHostedDesc"),icon: <Network className="w-4 h-4" />,+ disabled: true,+ badge: t("settings.meeting.comingSoon"),},],- "transcription"+ "transcription",+ meetingTranscriptionMode,+ { byokProviders: MEETING_BYOK_PROVIDER_IDS });-const handleTranscriptionModeSelect = (mode: InferenceMode) => {if (!isModeAllowed(mode)) return;+ if (mode === "self-hosted") return;if (mode === "openwhispr" && !isSignedIn) {startOnboarding();return;@@@ -145,13 -138,8 +148,8 @@@onSelect={handleTranscriptionModeSelect}/>- {meetingTranscriptionMode === "providers" && renderTranscriptionPicker("cloud")}- {meetingTranscriptionMode === "local" && renderTranscriptionPicker("local")}+ {effectiveTranscriptionMode === "providers" && renderTranscriptionPicker("cloud")}+ {effectiveTranscriptionMode === "local" && renderTranscriptionPicker("local")}- {effectiveTranscriptionMode === "self-hosted" && (- <p className="text-xs text-muted-foreground/80 px-1">- {t("settingsPage.speechToText.selfHostedStreamingNote")}- </p>- )}<MeetingSpeakerDetectionRow /></div>);diff --cc src/components/settings/UploadSettings.tsxindex 628d6e1be,a1c2772ad..1c977cb33--- a/src/components/settings/UploadSettings.tsx+++ b/src/components/settings/UploadSettings.tsx@@@ -1,7 -1,7 +1,7 @@@import { useCallback } from "react";import { useTranslation } from "react-i18next";-import { Cloud, Key, Cpu } from "lucide-react";-import { useSettingsStore } from "../../stores/settingsStore";+import { Cloud, Key, Cpu, Network } from "lucide-react";- import { useSettingsStore } from "../../stores/settingsStore";++import { TRANSCRIPTION_POLICY_PROVIDER_IDS, useSettingsStore } from "../../stores/settingsStore";import { usePolicyModeOptions } from "../../hooks/usePolicy";import { InferenceModeSelector } from "../ui/SettingsSection";import type { InferenceModeOption } from "../ui/SettingsSection";@@@ -63,16 -54,10 +63,17 @@@ export function UploadTranscriptionPanedescription: t("settingsPage.transcription.modes.localDesc"),icon: <Cpu className="w-4 h-4" />,},+ {+ id: "self-hosted",+ label: t("settingsPage.transcription.modes.selfHosted"),+ description: t("settingsPage.transcription.modes.selfHostedDesc"),+ icon: <Network className="w-4 h-4" />,+ },],- "transcription"+ "transcription",- uploadTranscriptionMode++ uploadTranscriptionMode,++ { byokProviders: TRANSCRIPTION_POLICY_PROVIDER_IDS });-const handleTranscriptionModeSelect = (mode: InferenceMode) => {if (!isModeAllowed(mode)) return;if (mode === "openwhispr" && !isSignedIn) {diff --cc src/helpers/audioManager.jsindex ad73e3745,71f1f6fbb..26f5d9d1c--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@@ -3290,12 -3306,18 +3315,24 @@@ registerProcessor("pcm-streaming-proces}}+ // 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 ||diff --cc src/helpers/ipcHandlers.jsindex 0d453b6bb,45f77c4ba..50f264418--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@@ -8001,11 -8026,7 +8032,13 @@@ class IPCHandlersreturn { success: true, text };}-- if (!apiKey) throw new Error("No API key configured. Add your key in Settings.");++ if (!apiKey && 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.");}@@@ -8068,9 -8089,9 +8101,8 @@@);const url = new URL(transcriptionUrl);-- const data = await postMultipart(url, body, boundary, {-- Authorization: `Bearer ${apiKey}`,-- });++ const headers = apiKey ? { Authorization: `Bearer ${apiKey}` } : undefined;++ const data = await postMultipart(url, body, boundary, headers);if (data.statusCode === 401) {return { success: false, error: "Invalid API key. Check your key in Settings." };diff --cc src/helpers/noteFormattingOverrides.jsindex 431ccdb58,431ccdb58..cadba6134--- a/src/helpers/noteFormattingOverrides.js+++ b/src/helpers/noteFormattingOverrides.js@@@ -1,6 -1,6 +1,6 @@@// Provider overrides for note-formatting ReasoningService.processText calls.// Self-hosted must forward remoteUrl as lanUrl — without it, processText--// guesses the provider from the model and can silently hit a cloud API.++// would use the dictation-cleanup scope instead of this scope's endpoint.export function buildNoteFormattingOverrides(noteFormatting, isCloudMode) {if (isCloudMode) {return {@@@ -22,13 -22,13 +22,12 @@@};}-- // Local must pin its provider for the same reason: an empty local selection-- // resolves to the cleanup scope's model, and processText would derive a cloud-- // provider from that id — sending note content off-device.++ // Local and enterprise must pin their providers too, or processText would++ // use the dictation-cleanup scope when this scope has no route override.const provider =mode === "local"? "local"-- : mode === "providers"++ : mode === "providers" || mode === "enterprise"? noteFormatting?.provider || undefined: undefined;const isCustom = provider === "custom";diff --cc src/hooks/useNotesOnboarding.tsindex cc1b56fef,cc1b56fef..84870f84a--- a/src/hooks/useNotesOnboarding.ts+++ b/src/hooks/useNotesOnboarding.ts@@@ -1,6 -1,6 +1,12 @@@import { useState, useCallback } from "react";--import { useSettingsStore, selectIsCloudCleanupMode } from "../stores/settingsStore";++import { useShallow } from "zustand/react/shallow";++import {++ selectIsCloudCleanupMode,++ selectPolicyEffectiveSettings,++ useSettingsStore,++} from "../stores/settingsStore";import { useUsage } from "./useUsage";++import { usePolicySnapshot } from "./usePolicy";interface UseNotesOnboardingReturn {isComplete: boolean;@@@ -14,9 -14,9 +20,17 @@@ export function useNotesOnboarding(): Uconst usage = useUsage();const isProUser = usage?.hasPaidAccess === true;const isProLoading = usage !== null && usage.status !== "success";-- const useCleanupModel = useSettingsStore((s) => s.useCleanupModel);-- const effectiveModel = useSettingsStore((s) => s.cleanupModel);-- const isCloudCleanup = useSettingsStore(selectIsCloudCleanupMode);++ const policyState = usePolicySnapshot();++ const { useCleanupModel, effectiveModel, isCloudCleanup } = useSettingsStore(++ useShallow((settings) => {++ const effective = selectPolicyEffectiveSettings(settings, policyState);++ return {++ useCleanupModel: effective.useCleanupModel,++ effectiveModel: effective.cleanupModel,++ isCloudCleanup: selectIsCloudCleanupMode(effective),++ };++ })++ );const [isComplete, setIsComplete] = useState(() => localStorage.getItem("notesOnboardingComplete") === "true"diff --cc src/services/ReasoningService.tsindex 63213ea36,8f1124516..d618a13ee--- a/src/services/ReasoningService.ts+++ b/src/services/ReasoningService.ts@@@ -107,9 -107,9 +107,9 @@@ class ReasoningService extends BaseReas}}-- private isLanCleanupMode(): boolean {++ private hasLanCleanupConfiguration(): boolean {const settings = getSettings();-- return settings.cleanupMode === "self-hosted" && !!settings.cleanupRemoteUrl;++ return settings.cleanupMode === "self-hosted" && !!settings.cleanupRemoteUrl?.trim();}private async getApiKey(@@@ -364,26 -364,12 +364,33 @@@config: ReasoningConfig = {}): Promise<string> {const trimmedModel = model?.trim?.() || "";- const isLanCleanup = !!config.lanUrl || this.isLanCleanupMode();+ const settings = getSettings();++ const isImplicitCleanup =++ config.provider === undefined && config.baseUrl === undefined && config.lanUrl === undefined;++ const implicitProvider =++ settings.cleanupMode === "openwhispr"++ ? "openwhispr"++ : settings.cleanupMode === "self-hosted"++ ? "lan"++ : settings.cleanupProvider || undefined;+ const isImplicitCustomCleanup =- config.provider === undefined &&- config.baseUrl === undefined &&- settings.cleanupMode === "providers" &&- settings.cleanupProvider === "custom";- const dispatchConfig: ReasoningConfig = isImplicitCustomCleanup++ isImplicitCleanup && settings.cleanupMode === "providers" && implicitProvider === "custom";++ const dispatchConfig: ReasoningConfig = isImplicitCleanup+ ? {+ ...config,- provider: "custom",- baseUrl: settings.cleanupCloudBaseUrl,- customApiKey: config.customApiKey ?? settings.cleanupCustomApiKey,++ provider: implicitProvider,++ baseUrl: isImplicitCustomCleanup ? settings.cleanupCloudBaseUrl : undefined,++ customApiKey: isImplicitCustomCleanup++ ? (config.customApiKey ?? settings.cleanupCustomApiKey)++ : config.customApiKey,+ }+ : config;- const isLanCleanup = !!dispatchConfig.lanUrl || this.isLanCleanupMode();++ const isLanCleanup = !!dispatchConfig.lanUrl || dispatchConfig.provider === "lan";const providerId = isLanCleanup? "lan"- : resolveInferenceProvider(config.provider, trimmedModel);- if (config.requiresAgent) assertAgentAllowedByPolicy();- assertReasoningAllowedByPolicy(providerId, resolveLlmDispatchMode(providerId, config));+ : resolveInferenceProvider(dispatchConfig.provider, trimmedModel);+ if (dispatchConfig.requiresAgent) assertAgentAllowedByPolicy();+ assertReasoningAllowedByPolicy(providerId, resolveLlmDispatchMode(providerId, dispatchConfig));if (!trimmedModel && providerId !== "openwhispr" && providerId !== "lan") {throw new Error("No reasoning model selected");@@@ -973,7 -957,7 +980,7 @@@return true;}-- if (this.isLanCleanupMode()) {++ if (this.hasLanCleanupConfiguration()) {logger.logReasoning("API_KEY_CHECK", { lanCleanup: true });return true;}diff --cc src/services/fileTranscription.tsindex 275663e10,af5b0d375..75fb63abd--- a/src/services/fileTranscription.ts+++ b/src/services/fileTranscription.ts@@@ -1,5 -1,10 +1,11 @@@import { withSessionRefresh } from "../lib/auth";+import { resolveCustomTranscriptionRoute } from "../helpers/retryTranscriptionRouting.js";+ import { getTranscriptionProviders } from "../models/ModelRegistry";+ import {+ TINFOIL_PROXY_REQUIRED_ERROR,+ isTinfoilInferenceUrl,+ resolveByokBaseUrl,+ } from "./transcriptionBaseUrl";export interface FileTranscriptionResult {success: boolean;@@@ -62,16 -67,23 +68,39 @@@ export async function transcribeFile});}- const customRoute = resolveCustomTranscriptionRoute({- provider: cfg.cloudTranscriptionProvider,- baseUrl: cfg.cloudTranscriptionBaseUrl,- });- if (customRoute?.kind === "configuration-error") {- return {- success: false,- error: customRoute.error,- code: "CUSTOM_ENDPOINT_INVALID",- };+ // Built-in providers resolve from the registry; only Custom uses the+ // stored URL, which provider tab switches no longer overwrite (#1459).+ const providers = getTranscriptionProviders();- const baseUrl = resolveByokBaseUrl(++ 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);}// Self-hosted fields make the handler route to the configured serverdiff --cc src/stores/policyRules.tsindex 9cbe89b87,6a53e69fb..155dee6c8--- a/src/stores/policyRules.ts+++ b/src/stores/policyRules.ts@@@ -130,65 -130,6 +130,66 @@@ export interface LlmSelectionprovider: string;}+export interface PolicySelectionCatalog {+ modes: readonly InferenceMode[];+ byokProviders: readonly string[];+ enterpriseProviders?: readonly string[];+}++/**+ * Derive the selection used for future work without mutating the user's saved+ * preference. Managed users keep an allowed selection; stale selections use+ * the first usable choice in the same order as the settings UI.+ */+export function resolveEffectivePolicySelection(+ state: PolicyDecisionSnapshot,+ scope: PolicyScope,+ selection: LlmSelection,+ catalog: PolicySelectionCatalog+): LlmSelection | null {+ if (state.status === "idle" || state.status === "unmanaged") return selection;+ if (!isPolicyActionAllowed(state)) return null;+ const policy = managedPolicy(state);+ if (!policy) return null;++ const allowedByokProviders = catalog.byokProviders.filter((provider) =>+ policy[scope].allowedByokProviders.includes(provider)+ );+ const allowedEnterpriseProviders = (catalog.enterpriseProviders ?? []).filter((provider) =>+ policy.llm.allowedEnterpriseProviders.includes(provider)+ );+ const modeIsUsable = (mode: InferenceMode): boolean => {++ if (!catalog.modes.includes(mode)) return false;+ if (!policy[scope].allowedModes.includes(mode)) return false;+ if (mode === "providers") return allowedByokProviders.length > 0;+ if (mode === "enterprise") return scope === "llm" && allowedEnterpriseProviders.length > 0;+ return true;+ };++ const mode = modeIsUsable(selection.mode)+ ? selection.mode+ : (catalog.modes.find(modeIsUsable) ?? null);+ if (!mode) return null;++ if (mode === "providers") {+ return {+ mode,+ provider: allowedByokProviders.includes(selection.provider)+ ? selection.provider+ : allowedByokProviders[0],+ };+ }+ if (mode === "enterprise") {+ return {+ mode,+ provider: allowedEnterpriseProviders.includes(selection.provider)+ ? selection.provider+ : allowedEnterpriseProviders[0],+ };+ }+ return { mode, provider: selection.provider };+}+export function isLlmSelectionAllowed(state: PolicyDecisionSnapshot,selection: LlmSelection@@@ -376,57 -263,6 +372,57 @@@ export function filterModeOptionsByPoli);}+/** Return the first usable allowed mode only when a managed selection must change. */+export function reconcilePolicyModeSelection<T extends { id: InferenceMode; disabled?: boolean }>(+ options: T[],+ scope: PolicyScope,+ state: PolicyDecisionSnapshot,+ selectedMode: InferenceMode,+ providerCatalog?: Pick<PolicySelectionCatalog, "byokProviders" | "enterpriseProviders">+): InferenceMode | null {+ if (state.status !== "managed") return null;+ const allowedOptions = filterModeOptionsByPolicy(options, scope, state, providerCatalog);+ if (allowedOptions.some((option) => option.id === selectedMode && !option.disabled)) return null;+ return allowedOptions.find((option) => !option.disabled)?.id ?? null;+}++export function filterByokProviderOptionsByPolicy<T extends { id: string }>(+ options: T[],+ scope: PolicyScope,+ state: PolicyDecisionSnapshot+): T[] {+ if (state.status === "idle" || state.status === "unmanaged") return options;+ if (state.status !== "managed" || !state.policy) return [];+ return options.filter((option) => isProviderAllowedByPolicy(state, scope, option.id));+}++export function filterEnterpriseProviderOptionsByPolicy<T extends { id: string }>(+ options: T[],+ state: PolicyDecisionSnapshot+): T[] {+ if (state.status === "idle" || state.status === "unmanaged") return options;+ if (state.status !== "managed" || !state.policy) return [];+ return options.filter((option) => isEnterpriseProviderAllowed(state, option.id));+}+- /** Preserve legacy cleanup writes only when no managed policy can be overwritten. */++/** Preserve legacy fallback writes only when no managed policy can be overwritten. */+export function shouldPersistProviderFallback(+ state: PolicyDecisionSnapshot,+ isSignedIn: boolean+): boolean {+ return state.status === "unmanaged" || (state.status === "idle" && !isSignedIn);+}++export function reconcileProviderSelection<T extends { id: string; disabled?: boolean }>(+ selectedProvider: string,+ allowedProviders: readonly T[]+): string | null {+ if (allowedProviders.some((provider) => provider.id === selectedProvider && !provider.disabled)) {+ return null;+ }+ return allowedProviders.find((provider) => !provider.disabled)?.id ?? null;+}+interface CloudProviderOption {id: string;models?: ReadonlyArray<{ id: string }>;@@@ -448,7 -284,7 +444,9 @@@ export function reconcileCloudProviderSif (selectedProvider === "custom" && customAllowed) return null;const selected = allowedProviders.find((provider) => provider.id === selectedProvider);if (selected) {-- if (selectedModel || !selected.models?.length) return null;++ if (!selected.models?.length || selected.models.some((model) => model.id === selectedModel)) {++ return null;++ }return { provider: selected.id, model: selected.models[0].id };}if (hasCustomUrl && customAllowed) {diff --cc src/stores/settingsStore.tsindex 0d1001ca1,10e306b53..e0a5e3eaf--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@@ -52,85 -43,6 +52,90 @@@ let _ReasoningService: typeof import(".const isBrowser = typeof window !== "undefined";++export const TRANSCRIPTION_POLICY_PROVIDER_IDS = [++ ...modelRegistryData.transcriptionProviders.map((provider) => provider.id),++ "custom",++] as const;++++export const LLM_POLICY_PROVIDER_IDS = [++ ...modelRegistryData.cloudProviders.map((provider) => provider.id),++ "openrouter",++ "custom",++] as const;++++// Azure and Vertex remain intentionally unavailable in the desktop picker.++export const LLM_ENTERPRISE_POLICY_PROVIDER_IDS = ["bedrock"] as const;+++const TRANSCRIPTION_POLICY_CATALOG = {+ modes: ["openwhispr", "providers", "local", "self-hosted"] as const,- byokProviders: [- ...modelRegistryData.transcriptionProviders.map((provider) => provider.id),- "custom",- ],++ byokProviders: TRANSCRIPTION_POLICY_PROVIDER_IDS,+};++const MEETING_TRANSCRIPTION_POLICY_CATALOG = {- // Meeting self-hosted deliberately streams through the managed realtime- // pipeline, so it is not a private destination a policy fallback may select.++ // Self-hosted realtime is not implemented for Note Recording.+ modes: ["openwhispr", "providers", "local"] as const,+ byokProviders: modelRegistryData.transcriptionProviders+ .filter((provider) => provider.models.some((model) => model.streaming))+ .map((provider) => provider.id),+};++const LLM_POLICY_CATALOG = {+ modes: ["openwhispr", "providers", "local", "self-hosted", "enterprise"] as const,- byokProviders: [- ...modelRegistryData.cloudProviders.map((provider) => provider.id),- "openrouter",- "custom",- ],- // Azure and Vertex remain intentionally unavailable in the desktop picker.- enterpriseProviders: ["bedrock"],++ byokProviders: LLM_POLICY_PROVIDER_IDS,++ enterpriseProviders: LLM_ENTERPRISE_POLICY_PROVIDER_IDS,+};++const localLlmProviderIds = new Set(+ modelRegistryData.localProviders.map((provider) => provider.id)+);++function transcriptionProviderModels(+ providerId: string,+ context: TranscriptionPolicyContext+): Array<{ id: string; streaming?: boolean }> {+ const models =+ modelRegistryData.transcriptionProviders.find((provider) => provider.id === providerId)+ ?.models ?? [];+ return context === "meeting" ? models.filter((model) => model.streaming) : models;+}++function defaultTranscriptionModel(+ providerId: string,+ context: TranscriptionPolicyContext+): string {+ return transcriptionProviderModels(providerId, context)[0]?.id ?? "whisper-1";+}++function transcriptionModelBelongsToProvider(+ providerId: string,+ modelId: string,+ context: TranscriptionPolicyContext+): boolean {+ if (providerId === "custom") return Boolean(modelId);+ return transcriptionProviderModels(providerId, context).some((model) => model.id === modelId);+}++function canonicalTranscriptionBaseUrl(providerId: string): string | null {+ return (+ modelRegistryData.transcriptionProviders.find((provider) => provider.id === providerId)+ ?.baseUrl ?? null+ );+}++function defaultLlmModel(mode: InferenceMode, providerId: string, bedrockRegion: string): string {+ const providers =+ mode === "local"+ ? modelRegistryData.localProviders+ : mode === "enterprise"+ ? modelRegistryData.enterpriseProviders+ : modelRegistryData.cloudProviders;+ const defaultModel =+ providers.find((provider) => provider.id === providerId)?.models[0]?.id ?? "";+ return mode === "enterprise" && providerId === "bedrock"+ ? adjustBedrockModelForRegion(defaultModel, bedrockRegion)+ : defaultModel;+}+function readString(key: string, fallback: string): string {if (!isBrowser) return fallback;return localStorage.getItem(key) ?? fallback;diff --cc test/helpers/noteFormattingOverrides.test.jsindex 5d2789894,5d2789894..05168ba06--- a/test/helpers/noteFormattingOverrides.test.js+++ b/test/helpers/noteFormattingOverrides.test.js@@@ -100,3 -100,3 +100,17 @@@ test("local mode with no model stays loassert.equal(overrides.provider, "local");assert.equal(overrides.customApiKey, undefined);});++++test("enterprise mode pins its provider instead of inheriting cleanup routing", async () => {++ const { buildNoteFormattingOverrides } = await load();++ const overrides = buildNoteFormattingOverrides(++ { mode: "enterprise", provider: "bedrock", customApiKey: "irrelevant" },++ false++ );++ assert.deepEqual(overrides, {++ provider: "bedrock",++ baseUrl: undefined,++ customApiKey: undefined,++ lanUrl: undefined,++ });++});diff --cc test/helpers/policyEffectiveSettings.test.jsindex b2ccf6dd2,000000000..b334db961mode 100644,000000..100644--- a/test/helpers/policyEffectiveSettings.test.js+++ b/test/helpers/policyEffectiveSettings.test.js@@@ -1,201 -1,0 +1,238 @@@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++const managedPolicy = {+ version: 1,+ transcription: {+ allowedModes: ["local"],+ allowedByokProviders: [],+ },+ llm: {+ allowedModes: ["enterprise"],+ allowedByokProviders: [],+ allowedEnterpriseProviders: ["bedrock"],+ },+ features: { agentEnabled: true, webSearchEnabled: true },+ sharing: { externalLinkSharing: "allowed" },+ dataRetention: {+ audioRetentionMaxDays: null,+ localHistoryMode: "user_choice",+ cloudBackupAllowed: true,+ },+ minAppVersion: null,+};++test("runtime settings use managed fallbacks without overwriting raw preferences", async (t) => {+ const browser = installBrowserGlobals(t, {+ initialStorage: {+ transcriptionMode: "providers",+ useLocalWhisper: "false",+ cloudTranscriptionMode: "byok",+ cloudTranscriptionProvider: "groq",+ cleanupMode: "providers",+ cleanupCloudMode: "byok",+ cleanupProvider: "openai",+ cleanupModel: "gpt-5.6-sol",+ bedrockRegion: "eu-west-2",+ },+ });+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-policy-effective-settings-test-",+ });+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");+ const { isLlmSelectionAllowed, isTranscriptionContextAllowed } =+ await vite.ssrLoadModule("/stores/policyRules.ts");+ const { getSettings, useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");++ usePolicyStore.setState({+ status: "managed",+ managed: true,+ policy: managedPolicy,+ appVersion: "1.8.1",+ });++ const effective = getSettings();+ assert.equal(effective.transcriptionMode, "local");+ assert.equal(effective.useLocalWhisper, true);+ assert.equal(effective.cleanupMode, "enterprise");+ assert.equal(effective.cleanupProvider, "bedrock");+ assert.ok(effective.cleanupModel);+ assert.match(effective.cleanupModel, /^eu\./);+ assert.equal(+ isTranscriptionContextAllowed(usePolicyStore.getState(), effective, "dictation"),+ true+ );+ assert.equal(+ isLlmSelectionAllowed(usePolicyStore.getState(), {+ mode: effective.cleanupMode,+ provider: effective.cleanupProvider,+ }),+ true+ );++ const raw = useSettingsStore.getState();+ assert.equal(raw.transcriptionMode, "providers");+ assert.equal(raw.useLocalWhisper, false);+ assert.equal(raw.cleanupMode, "providers");+ assert.equal(raw.cleanupProvider, "openai");+ assert.equal(browser.storage.getItem("transcriptionMode"), "providers");+ assert.equal(browser.storage.getItem("cleanupProvider"), "openai");++ usePolicyStore.setState({+ status: "unmanaged",+ managed: false,+ policy: null,+ appVersion: "1.8.1",+ });++ const unmanaged = getSettings();+ assert.equal(unmanaged.transcriptionMode, "providers");+ assert.equal(unmanaged.useLocalWhisper, false);+ assert.equal(unmanaged.cloudTranscriptionProvider, "groq");+});++test("managed transcription fallback binds known providers to their canonical endpoint", async (t) => {+ const customEndpoint = "https://custom.example.invalid/v1";+ installBrowserGlobals(t, {+ initialStorage: {+ transcriptionMode: "providers",+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionModel: "custom-model",+ cloudTranscriptionBaseUrl: customEndpoint,+ meetingTranscriptionMode: "providers",+ meetingCloudTranscriptionProvider: "custom",+ meetingCloudTranscriptionModel: "custom-model",+ meetingCloudTranscriptionBaseUrl: customEndpoint,+ uploadTranscriptionMode: "providers",+ uploadCloudTranscriptionProvider: "custom",+ uploadCloudTranscriptionModel: "custom-model",+ uploadCloudTranscriptionBaseUrl: customEndpoint,+ },+ });+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-policy-effective-endpoint-test-",+ });+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");+ const { getSettings, useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");+ const registry = await vite.ssrLoadModule("/models/modelRegistryData.json");+ const openai = registry.default.transcriptionProviders.find(+ (provider) => provider.id === "openai"+ );+ const providerPolicy = {+ ...managedPolicy,+ transcription: {+ allowedModes: ["providers"],+ allowedByokProviders: ["openai"],+ },+ };++ usePolicyStore.setState({+ status: "managed",+ managed: true,+ policy: providerPolicy,+ appVersion: "1.8.1",+ });++ const effective = getSettings();+ assert.equal(effective.cloudTranscriptionProvider, "openai");+ assert.equal(effective.cloudTranscriptionBaseUrl, openai.baseUrl);+ assert.equal(effective.cloudTranscriptionModel, openai.models[0].id);+ assert.equal(effective.meetingCloudTranscriptionProvider, "openai");+ assert.equal(effective.meetingCloudTranscriptionBaseUrl, openai.baseUrl);+ assert.equal(effective.uploadCloudTranscriptionProvider, "openai");+ assert.equal(effective.uploadCloudTranscriptionBaseUrl, openai.baseUrl);++ const raw = useSettingsStore.getState();+ assert.equal(raw.cloudTranscriptionProvider, "custom");+ assert.equal(raw.cloudTranscriptionBaseUrl, customEndpoint);+ assert.equal(raw.meetingCloudTranscriptionBaseUrl, customEndpoint);+ assert.equal(raw.uploadCloudTranscriptionBaseUrl, customEndpoint);+});++test("automatic Custom fallbacks never inherit another provider's endpoint", async (t) => {+ const unrelatedEndpoint = "https://unrelated.example.invalid/v1";+ installBrowserGlobals(t, {+ initialStorage: {+ transcriptionMode: "providers",+ cloudTranscriptionProvider: "openai",+ cloudTranscriptionBaseUrl: unrelatedEndpoint,+ cleanupMode: "providers",+ cleanupProvider: "openai",+ cleanupCloudBaseUrl: unrelatedEndpoint,+ },+ });+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-policy-effective-custom-endpoint-test-",+ });+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");+ const { getSettings, useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");+ const customOnlyPolicy = {+ ...managedPolicy,+ transcription: {+ allowedModes: ["providers"],+ allowedByokProviders: ["custom"],+ },+ llm: {+ allowedModes: ["providers"],+ allowedByokProviders: ["custom"],+ allowedEnterpriseProviders: [],+ },+ };++ usePolicyStore.setState({+ status: "managed",+ managed: true,+ policy: customOnlyPolicy,+ appVersion: "1.8.1",+ });++ const effective = getSettings();+ assert.equal(effective.cloudTranscriptionProvider, "custom");+ assert.equal(effective.cloudTranscriptionBaseUrl, "");+ assert.equal(effective.cleanupProvider, "custom");+ assert.equal(effective.cleanupCloudBaseUrl, "");++ const raw = useSettingsStore.getState();+ assert.equal(raw.cloudTranscriptionProvider, "openai");+ assert.equal(raw.cloudTranscriptionBaseUrl, unrelatedEndpoint);+ assert.equal(raw.cleanupProvider, "openai");+ assert.equal(raw.cleanupCloudBaseUrl, unrelatedEndpoint);+});++++test("Note Recording never inherits an unsupported self-hosted policy fallback", async (t) => {++ installBrowserGlobals(t, {++ initialStorage: {++ _providerSettingsMigrated: "1",++ uploadTranscriptionMigrated: "true",++ transcriptionMode: "self-hosted",++ meetingTranscriptionMode: "self-hosted",++ uploadTranscriptionMode: "self-hosted",++ },++ });++ const vite = await createRendererServer(t, {++ cachePrefix: "openwhispr-policy-effective-meeting-self-hosted-test-",++ });++ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");++ const { getSettings } = await vite.ssrLoadModule("/stores/settingsStore.ts");++ const selfHostedPolicy = {++ ...managedPolicy,++ transcription: {++ allowedModes: ["self-hosted", "local"],++ allowedByokProviders: [],++ },++ };++++ usePolicyStore.setState({++ status: "managed",++ managed: true,++ policy: selfHostedPolicy,++ appVersion: "1.8.1",++ });++++ const effective = getSettings();++ assert.equal(effective.transcriptionMode, "self-hosted");++ assert.equal(effective.uploadTranscriptionMode, "self-hosted");++ assert.equal(effective.meetingTranscriptionMode, "local");++ assert.equal(effective.meetingUseLocalWhisper, true);++});diff --cc test/helpers/policyRules.test.jsindex c6c935ece,c2b940a85..255ad2155--- a/test/helpers/policyRules.test.js+++ b/test/helpers/policyRules.test.js@@@ -95,217 -95,6 +95,259 @@@ test("mode and provider decisions failassert.equal(isProviderAllowedByPolicy(snapshot, "transcription", "openai"), false);});+test("managed mode lists hide denied options while unmanaged lists remain unchanged", async () => {+ const { filterModeOptionsByPolicy } = await load();+ const options = [+ { id: "openwhispr", label: "Cloud" },+ { id: "providers", label: "Providers" },+ { id: "local", label: "Local" },+ { id: "self-hosted", label: "Self-hosted" },+ ];+ const managed = { status: "managed", policy, appVersion: "1.8.1" };+ const unmanaged = { status: "unmanaged", policy: null, appVersion: "1.8.1" };++ assert.deepEqual(+ filterModeOptionsByPolicy(options, "transcription", managed).map((option) => option.id),+ ["openwhispr", "local"]+ );+ assert.deepEqual(filterModeOptionsByPolicy(options, "transcription", unmanaged), options);+});++test("provider-backed modes are hidden when their provider allowlist is empty", async () => {+ const { filterModeOptionsByPolicy, reconcilePolicyModeSelection } = await load();+ const noProviderPolicy = {+ ...policy,+ transcription: { allowedModes: ["providers", "local"], allowedByokProviders: [] },+ llm: {+ allowedModes: ["enterprise", "local"],+ allowedByokProviders: [],+ allowedEnterpriseProviders: [],+ },+ };+ const managed = { status: "managed", policy: noProviderPolicy, appVersion: "1.8.1" };+ const transcriptionOptions = [{ id: "providers" }, { id: "local" }];+ const llmOptions = [{ id: "enterprise" }, { id: "local" }];++ assert.deepEqual(+ filterModeOptionsByPolicy(transcriptionOptions, "transcription", managed).map(+ (option) => option.id+ ),+ ["local"]+ );+ assert.deepEqual(+ filterModeOptionsByPolicy(llmOptions, "llm", managed).map((option) => option.id),+ ["local"]+ );+ assert.equal(+ reconcilePolicyModeSelection(transcriptionOptions, "transcription", managed, "providers"),+ "local"+ );+});+++test("provider-backed modes are hidden when policy providers are unavailable in the surface", async () => {++ const { filterModeOptionsByPolicy, reconcilePolicyModeSelection } = await load();++ const unknownProviderPolicy = {++ ...policy,++ transcription: {++ allowedModes: ["providers", "local"],++ allowedByokProviders: ["server-only-provider"],++ },++ };++ const snapshot = {++ status: "managed",++ policy: unknownProviderPolicy,++ appVersion: "1.8.1",++ };++ const options = [{ id: "providers" }, { id: "local" }];++ const catalog = { byokProviders: ["openai", "custom"] };++++ assert.deepEqual(++ filterModeOptionsByPolicy(options, "transcription", snapshot, catalog).map(++ (option) => option.id++ ),++ ["local"]++ );++ assert.equal(++ reconcilePolicyModeSelection(options, "transcription", snapshot, "providers", catalog),++ "local"++ );++});+++test("enterprise mode stays hidden when policy allows only unavailable desktop providers", async () => {+ const { filterModeOptionsByPolicy } = await load();+ const unavailableEnterprisePolicy = {+ ...policy,+ llm: {+ allowedModes: ["enterprise"],+ allowedByokProviders: [],+ allowedEnterpriseProviders: ["vertex"],+ },+ };++ assert.deepEqual(+ filterModeOptionsByPolicy([{ id: "enterprise" }], "llm", {+ status: "managed",+ policy: unavailableEnterprisePolicy,+ appVersion: "1.8.1",+ }),+ []+ );+});++test("denied managed modes fall back in visible catalog order", async () => {+ const { reconcilePolicyModeSelection } = await load();+ const options = [+ { id: "openwhispr" },+ { id: "providers" },+ { id: "local" },+ { id: "self-hosted" },+ ];+ const managed = { status: "managed", policy, appVersion: "1.8.1" };++ assert.equal(+ reconcilePolicyModeSelection(options, "transcription", managed, "providers"),+ "openwhispr"+ );+ assert.equal(reconcilePolicyModeSelection(options, "transcription", managed, "local"), null);+});++test("mode fallback skips unavailable choices and never invents an empty-allowlist choice", async () => {+ const { reconcilePolicyModeSelection } = await load();+ const options = [{ id: "openwhispr", disabled: true }, { id: "local" }];+ const managed = { status: "managed", policy, appVersion: "1.8.1" };+ const emptyPolicy = {+ ...policy,+ transcription: { allowedModes: [], allowedByokProviders: [] },+ };++ assert.equal(+ reconcilePolicyModeSelection(options, "transcription", managed, "providers"),+ "local"+ );+ assert.equal(+ reconcilePolicyModeSelection(+ options,+ "transcription",+ { status: "managed", policy: emptyPolicy, appVersion: "1.8.1" },+ "providers"+ ),+ null+ );+});++test("managed provider lists hide denied BYOK and enterprise providers", async () => {+ const { filterByokProviderOptionsByPolicy, filterEnterpriseProviderOptionsByPolicy } =+ await load();+ const byokOptions = [{ id: "openai" }, { id: "groq" }, { id: "custom" }];+ const enterpriseOptions = [{ id: "bedrock" }, { id: "azure" }];+ const managed = { status: "managed", policy, appVersion: "1.8.1" };++ assert.deepEqual(+ filterByokProviderOptionsByPolicy(byokOptions, "llm", managed).map((option) => option.id),+ ["openai"]+ );+ assert.deepEqual(filterEnterpriseProviderOptionsByPolicy(enterpriseOptions, managed), []);+});++test("provider fallback preserves an allowed selection and chooses the first visible alternative", async () => {+ const { reconcileProviderSelection } = await load();+ const allowedProviders = [{ id: "bedrock" }, { id: "azure", disabled: true }];++ assert.equal(reconcileProviderSelection("bedrock", allowedProviders), null);+ assert.equal(reconcileProviderSelection("vertex", allowedProviders), "bedrock");+ assert.equal(reconcileProviderSelection("vertex", []), null);+});++test("effective managed selections use allowed modes and providers without changing unmanaged choices", async () => {+ const { resolveEffectivePolicySelection } = await load();+ const managed = { status: "managed", policy, appVersion: "1.8.1" };+ const unmanaged = { status: "unmanaged", policy: null, appVersion: "1.8.1" };+ const catalog = {+ modes: ["openwhispr", "providers", "local", "self-hosted"],+ byokProviders: ["openai", "groq", "custom"],+ };++ assert.deepEqual(+ resolveEffectivePolicySelection(+ managed,+ "transcription",+ { mode: "providers", provider: "groq" },+ catalog+ ),+ { mode: "openwhispr", provider: "groq" }+ );+ assert.deepEqual(+ resolveEffectivePolicySelection(+ unmanaged,+ "transcription",+ { mode: "providers", provider: "groq" },+ catalog+ ),+ { mode: "providers", provider: "groq" }+ );+});++test("effective managed provider selection falls back inside an allowed provider mode", async () => {+ const { resolveEffectivePolicySelection } = await load();+ const providersPolicy = {+ ...policy,+ transcription: {+ allowedModes: ["providers"],+ allowedByokProviders: ["openai"],+ },+ };++ assert.deepEqual(+ resolveEffectivePolicySelection(+ { status: "managed", policy: providersPolicy, appVersion: "1.8.1" },+ "transcription",+ { mode: "providers", provider: "groq" },+ {+ modes: ["openwhispr", "providers", "local", "self-hosted"],+ byokProviders: ["openai", "groq", "custom"],+ }+ ),+ { mode: "providers", provider: "openai" }+ );+});++test("effective selection skips policy providers unavailable to a narrower surface", async () => {+ const { resolveEffectivePolicySelection } = await load();+ const meetingPolicy = {+ ...policy,+ transcription: {+ allowedModes: ["providers", "local"],+ allowedByokProviders: ["groq"],+ },+ };++ assert.deepEqual(+ resolveEffectivePolicySelection(+ { status: "managed", policy: meetingPolicy, appVersion: "1.8.1" },+ "transcription",+ { mode: "providers", provider: "groq" },+ {+ modes: ["openwhispr", "providers", "local", "self-hosted"],+ byokProviders: ["openai", "corti", "tinfoil"],+ }+ ),+ { mode: "local", provider: "groq" }+ );++++ assert.deepEqual(++ resolveEffectivePolicySelection(++ { status: "managed", policy: meetingPolicy, appVersion: "1.8.1" },++ "transcription",++ { mode: "self-hosted", provider: "openai" },++ {++ modes: ["openwhispr", "providers", "local"],++ byokProviders: ["openai", "corti", "tinfoil"],++ }++ ),++ { mode: "local", provider: "openai" }++ );+});+test("empty managed scope allowlists make that scope unavailable", async () => {const { isLlmSelectionAllowed } = await load();const emptyLlmPolicy = {@@@ -585,17 -311,6 +627,28 @@@ test("re-entering providers mode replac}),null);+++ assert.deepEqual(++ reconcileCloudProviderSelection({++ selectedProvider: "openai",++ selectedModel: "whisper-large-v3",++ allowedProviders,++ customAllowed: false,++ hasCustomUrl: false,++ }),++ { provider: "openai", model: "whisper-1" }++ );+++ assert.deepEqual(+ reconcileCloudProviderSelection({+ selectedProvider: "groq",+ selectedModel: "whisper-large-v3",+ allowedProviders: [],+ customAllowed: true,+ hasCustomUrl: false,+ }),+ { provider: "custom", model: "whisper-large-v3" }+ );});test("active control-panel views reroute on their specific policy capability", async () => {diff --cc test/services/fileTranscriptionCustomEndpoint.test.jsindex cd85f6b56,000000000..7d542baa7mode 100644,000000..100644--- a/test/services/fileTranscriptionCustomEndpoint.test.js+++ b/test/services/fileTranscriptionCustomEndpoint.test.js@@@ -1,58 -1,0 +1,91 @@@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++function customConfig(baseUrl) {+ return {+ useLocalWhisper: false,+ localTranscriptionProvider: "whisper",+ whisperModel: "base",+ parakeetModel: "parakeet-tdt-0.6b-v3",+ isOpenWhisprCloud: false,+ getApiKey: () => "must-not-leak",+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionBaseUrl: baseUrl,+ cloudTranscriptionModel: "whisper-1",+ language: "en",+ transcriptionMode: "providers",+ };+}++test("file transcription enforces Custom endpoint security before IPC", async (t) => {+ const { window } = installBrowserGlobals(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-file-custom-endpoint-test-",+ mockModules: {+ "/lib/auth": "export const withSessionRefresh = (fn) => fn();",+ },+ });+ const { transcribeFile } = await vite.ssrLoadModule("/services/fileTranscription.ts");++ let ipcCalls = 0;+ window.electronAPI.transcribeAudioFileByok = async () => {+ ipcCalls += 1;+ return { success: true, text: "must not run" };+ };++ for (const baseUrl of ["", "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(ipcCalls, 0);++ let receivedOptions = null;+ window.electronAPI.transcribeAudioFileByok = async (options) => {+ receivedOptions = options;+ return { success: true, text: "local gateway" };+ };++ const result = await transcribeFile(+ "/tmp/audio.webm",+ customConfig("http://192.168.1.20:5001/v1"),+ false+ );++ assert.equal(result.success, true);+ assert.equal(receivedOptions.baseUrl, "http://192.168.1.20:5001/v1");+});++++test("self-hosted file transcription bypasses stale Custom endpoint validation", async (t) => {++ const { window } = installBrowserGlobals(t);++ const vite = await createRendererServer(t, {++ cachePrefix: "openwhispr-file-self-hosted-endpoint-test-",++ mockModules: {++ "/lib/auth": "export const withSessionRefresh = (fn) => fn();",++ },++ });++ const { transcribeFile } = await vite.ssrLoadModule("/services/fileTranscription.ts");++++ let receivedOptions = null;++ window.electronAPI.transcribeAudioFileByok = async (options) => {++ receivedOptions = options;++ return { success: true, text: "self-hosted" };++ };++++ const result = await transcribeFile(++ "/tmp/audio.webm",++ {++ ...customConfig(""),++ transcriptionMode: "self-hosted",++ remoteTranscriptionUrl: "http://192.168.1.20:9000/v1",++ remoteTranscriptionModel: "whisper-large-v3",++ },++ false++ );++++ assert.equal(result.success, true);++ assert.equal(receivedOptions.transcriptionMode, "self-hosted");++ assert.equal(receivedOptions.remoteTranscriptionUrl, "http://192.168.1.20:9000/v1");++ assert.equal(receivedOptions.remoteTranscriptionModel, "whisper-large-v3");++});diff --cc test/services/reasoningServiceEnforcement.test.jsindex 295a712f0,c69d82e6e..e7da620dc--- a/test/services/reasoningServiceEnforcement.test.js+++ b/test/services/reasoningServiceEnforcement.test.js@@@ -132,120 -129,4 +132,179 @@@ test("ReasoningService entry points enf});await assert.rejects(stream.next(), { message: REASONING_RESTRICTED });});++ await t.test("managed Custom endpoints fail closed before inference dispatch", async () => {+ setPolicy({ llmModes: ["providers"], llmByokProviders: ["custom"] });+ const originalFetch = globalThis.fetch;+ let fetchCalls = 0;+ globalThis.fetch = async () => {+ fetchCalls += 1;+ return new Response(JSON.stringify({ error: "must not dispatch" }), {+ status: 400,+ headers: { "content-type": "application/json" },+ });+ };++ try {+ for (const baseUrl of ["", "http://public.example.com/v1", "ftp://192.168.1.20/v1"]) {+ await assert.rejects(+ reasoningService.processText("hi", "gpt-4.1", null, {+ provider: "custom",+ baseUrl,+ customApiKey: "must-not-leak",+ }),+ { message: REASONING_RESTRICTED }+ );+ }+ assert.equal(fetchCalls, 0);+ } finally {+ globalThis.fetch = originalFetch;+ }+ });++ await t.test("unmanaged Custom endpoint compatibility remains unchanged", () => {+ usePolicyStore.setState({ status: "unmanaged", appVersion: "1.8.1", policy: null });++ assert.equal(resolveConfiguredOpenAIBase("custom", ""), "https://api.openai.com/v1");+ assert.equal(+ resolveConfiguredOpenAIBase("custom", "http://public.example.com/v1"),+ "https://api.openai.com/v1"+ );+ assert.equal(+ resolveConfiguredOpenAIBase("custom", "http://192.168.1.20:11434/v1"),+ "http://192.168.1.20:11434/v1"+ );+ });++ await t.test("normal cleanup uses its saved valid Custom endpoint", async () => {+ setPolicy({ llmModes: ["providers"], llmByokProviders: ["custom"] });+ useSettingsStore.setState({+ cleanupMode: "providers",+ cleanupProvider: "custom",+ cleanupCloudBaseUrl: "https://custom.example.com/v1",+ cleanupCustomApiKey: "custom-key",+ });++ const originalFetch = globalThis.fetch;+ const requestedUrls = [];+ globalThis.fetch = async (url) => {+ requestedUrls.push(String(url));+ return new Response(JSON.stringify({ error: "expected test stop" }), {+ status: 400,+ headers: { "content-type": "application/json" },+ });+ };++ try {+ await assert.rejects(reasoningService.processText("hi", "custom-model"), {+ message: "expected test stop",+ });+ assert.ok(requestedUrls.length > 0);+ assert.ok(requestedUrls.every((url) => url.startsWith("https://custom.example.com/v1/")));+ } finally {+ globalThis.fetch = originalFetch;+ }+ });+++ await t.test("implicit cleanup pins the selected provider instead of inferring from its model", async () => {++ setPolicy({++ llmModes: ["providers"],++ llmByokProviders: ["openai", "groq"],++ });++ useSettingsStore.setState({++ cleanupMode: "providers",++ cleanupProvider: "openai",++ cleanupModel: "llama-3.3-70b-versatile",++ });++ globalThis.window.electronAPI.getOpenAIKey = async () => "openai-key";++++ const originalFetch = globalThis.fetch;++ const requestedUrls = [];++ globalThis.fetch = async (url) => {++ requestedUrls.push(String(url));++ return new Response(JSON.stringify({ error: "expected test stop" }), {++ status: 400,++ headers: { "content-type": "application/json" },++ });++ };++++ try {++ await assert.rejects(++ reasoningService.processText("hi", "llama-3.3-70b-versatile"),++ { message: "expected test stop" }++ );++ assert.ok(requestedUrls.length > 0);++ assert.ok(requestedUrls.every((url) => url.startsWith("https://api.openai.com/")));++ } finally {++ globalThis.fetch = originalFetch;++ }++ });++++ await t.test("implicit self-hosted cleanup without a URL never infers a cloud provider", async () => {++ usePolicyStore.setState({ status: "unmanaged", appVersion: "1.8.1", policy: null });++ useSettingsStore.setState({++ cleanupMode: "self-hosted",++ cleanupRemoteUrl: "",++ cleanupModel: "gpt-4.1",++ });++++ const originalFetch = globalThis.fetch;++ let fetchCalls = 0;++ globalThis.fetch = async () => {++ fetchCalls += 1;++ return new Response(null, { status: 500 });++ };++++ try {++ await assert.rejects(reasoningService.processText("hi", "gpt-4.1"), {++ message: HTTPS_REQUIRED,++ });++ assert.equal(fetchCalls, 0);++ } finally {++ globalThis.fetch = originalFetch;++ }++ });+++ await t.test(+ "self-hosted execution rejects unsafe endpoint schemes before dispatch",+ async () => {+ setPolicy({ llmModes: ["self-hosted"], llmByokProviders: [] });+ const originalFetch = globalThis.fetch;+ let fetchCalls = 0;+ globalThis.fetch = async () => {+ fetchCalls += 1;+ return new Response(null, { status: 500 });+ };++ try {+ for (const lanUrl of ["http://public.example.com/v1", "ftp://192.168.1.20/v1"]) {+ await assert.rejects(+ reasoningService.processText("hi", "custom-model", null, { lanUrl }),+ { message: HTTPS_REQUIRED }+ );++ const textStream = reasoningService.processTextStreaming(+ [{ role: "user", content: "hi" }],+ "custom-model",+ "custom",+ { systemPrompt: "s", lanUrl }+ );+ await assert.rejects(textStream.next(), { message: HTTPS_REQUIRED });++ const toolStream = reasoningService.processTextStreamingAI(+ [{ role: "user", content: "hi" }],+ "custom-model",+ "custom",+ { systemPrompt: "s", lanUrl },+ {}+ );+ await assert.rejects(toolStream.next(), { message: HTTPS_REQUIRED });+ }++ assert.equal(fetchCalls, 0);+ } finally {+ globalThis.fetch = originalFetch;+ }+ }+ );});