Skip to content

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

fix(policy): Hide restricted options and apply safe fallbacks

Chadpihaa37458212943
diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsx
index 1944d49c3..81bf602b5 100644
--- a/src/components/ControlPanel.tsx
+++ b/src/components/ControlPanel.tsx
@@ -31,7 +31,7 @@ import {
updateTranscription as updateInStore,
clearTranscriptions as clearStore,
} from "../stores/transcriptionStore";
-import { useSettingsStore } from "../stores/settingsStore";
+import { getSettings, useSettingsStore } from "../stores/settingsStore";
import { usePolicyStore } from "../stores/policyStore";
import {
isAgentAllowed,
@@ -592,7 +592,7 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
const retryTranscription = useCallback(
async (id: number, options?: { isRecover?: boolean }) => {
try {
- const s = useSettingsStore.getState();
+ const s = getSettings();
if (!isTranscriptionContextAllowed(usePolicyStore.getState(), s, "dictation")) {
toast({ title: t("common.managedByOrg"), variant: "default" });
return;
@@ -625,13 +625,13 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
const [
{ default: ReasoningService },
{ resolveReasoningRoute },
- { getEffectiveCleanupModel },
+ { getEffectiveCleanupModel, getSettings: getEffectiveSettings },
] = await Promise.all([
import("../services/ReasoningService"),
import("../helpers/audioManager"),
import("../stores/settingsStore"),
]);
- const settings = useSettingsStore.getState();
+ const settings = getEffectiveSettings();
const agentName = localStorage.getItem("agentName") || null;
const route = resolveReasoningRoute(rawText, settings, agentName, false, true);
if (route.kind === "translation") {
diff --git a/src/components/EnterpriseSection.tsx b/src/components/EnterpriseSection.tsx
index 7d7ddbf9d..c134e1b7a 100644
--- a/src/components/EnterpriseSection.tsx
+++ b/src/components/EnterpriseSection.tsx
@@ -1,10 +1,13 @@
-import { useTranslation } from "react-i18next";
+import { useCallback } from "react";
import { ProviderTabs } from "./ui/ProviderTabs";
import EnterpriseProviderConfig from "./EnterpriseProviderConfig";
import { REASONING_PROVIDERS } from "../models/ModelRegistry";
import { useSettingsStore } from "../stores/settingsStore";
import { adjustBedrockModelForRegion } from "../utils/bedrockRegions";
-import { isEnterpriseProviderAllowed } from "../stores/policyRules";
+import {
+ filterEnterpriseProviderOptionsByPolicy,
+ isEnterpriseProviderAllowed,
+} from "../stores/policyRules";
import { usePolicySnapshot } from "../hooks/usePolicy";
const ENTERPRISE_PROVIDER_TABS = [
@@ -26,48 +29,60 @@ export default function EnterpriseSection({
setReasoningModel,
setLocalReasoningProvider,
}: EnterpriseSectionProps) {
- const { t } = useTranslation();
const azureDeploymentName = useSettingsStore((s) => s.azureDeploymentName);
const bedrockRegion = useSettingsStore((s) => s.bedrockRegion);
const policyState = usePolicySnapshot();
- const providerAllowed = (providerId: string) =>
- isEnterpriseProviderAllowed(policyState, providerId);
+ const providerAllowed = useCallback(
+ (providerId: string) => isEnterpriseProviderAllowed(policyState, providerId),
+ [policyState]
+ );
- const providerTabs = ENTERPRISE_PROVIDER_TABS.map((tab) =>
- providerAllowed(tab.id)
- ? tab
- : { ...tab, disabled: true, disabledLabel: t("common.managedByOrg") }
+ const providerTabs = filterEnterpriseProviderOptionsByPolicy(
+ ENTERPRISE_PROVIDER_TABS,
+ policyState
);
- const selectedEnterprise = ENTERPRISE_PROVIDER_TABS.some((p) => p.id === currentProvider)
+ const selectedEnterprise = providerTabs.some((provider) => provider.id === currentProvider)
? currentProvider
: "";
- const handleEnterpriseSelect = (providerId: string) => {
- if (selectedEnterprise === providerId) return;
- if (!providerAllowed(providerId)) return;
- setLocalReasoningProvider(providerId);
+ const handleEnterpriseSelect = useCallback(
+ (providerId: string) => {
+ if (selectedEnterprise === providerId) return;
+ if (!providerAllowed(providerId)) return;
+ setLocalReasoningProvider(providerId);
- const providerData = REASONING_PROVIDERS[providerId];
- if (providerData?.models?.length) {
- const defaultModel = providerData.models[0].value;
- setReasoningModel(
- providerId === "bedrock"
- ? adjustBedrockModelForRegion(defaultModel, bedrockRegion)
- : defaultModel
- );
- } else if (providerId === "azure" && azureDeploymentName) {
- setReasoningModel(azureDeploymentName);
- }
- };
+ const providerData = REASONING_PROVIDERS[providerId];
+ if (providerData?.models?.length) {
+ const defaultModel = providerData.models[0].value;
+ setReasoningModel(
+ providerId === "bedrock"
+ ? adjustBedrockModelForRegion(defaultModel, bedrockRegion)
+ : defaultModel
+ );
+ } else if (providerId === "azure" && azureDeploymentName) {
+ setReasoningModel(azureDeploymentName);
+ }
+ },
+ [
+ azureDeploymentName,
+ bedrockRegion,
+ providerAllowed,
+ selectedEnterprise,
+ setLocalReasoningProvider,
+ setReasoningModel,
+ ]
+ );
return (
<div className="space-y-2">
- <ProviderTabs
- providers={providerTabs}
- selectedId={selectedEnterprise}
- onSelect={handleEnterpriseSelect}
- colorScheme="purple"
- />
+ {providerTabs.length > 0 && (
+ <ProviderTabs
+ providers={providerTabs}
+ selectedId={selectedEnterprise}
+ onSelect={handleEnterpriseSelect}
+ colorScheme="purple"
+ />
+ )}
{selectedEnterprise && (
<EnterpriseProviderConfig
diff --git a/src/components/OnboardingFlow.tsx b/src/components/OnboardingFlow.tsx
index da299e058..02a77630b 100644
--- a/src/components/OnboardingFlow.tsx
+++ b/src/components/OnboardingFlow.tsx
@@ -29,6 +29,8 @@ import { useClipboard } from "../hooks/useClipboard";
import { useSystemAudioPermission } from "../hooks/useSystemAudioPermission";
import { useSettings } from "../hooks/useSettings";
import { useSettingsStore } from "../stores/settingsStore";
+import { usePolicyStore } from "../stores/policyStore";
+import { isAgentAllowed } from "../stores/policyRules";
import LanguageSelector from "./ui/LanguageSelector";
import AuthenticationStep from "./AuthenticationStep";
import EmailVerificationStep from "./EmailVerificationStep";
@@ -71,6 +73,7 @@ interface OnboardingFlowProps {
export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
const { t } = useTranslation();
const { isSignedIn } = useAuth();
+ const agentAllowed = usePolicyStore(isAgentAllowed);
const [currentStep, setCurrentStep, removeCurrentStep] = useLocalStorage(
"onboardingCurrentStep",
@@ -215,7 +218,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
}
list.push({ id: "activation", title: t("onboarding.steps.activation"), icon: Command });
// Hidden for continue-without-account users: they have no LLM, so the agent can't run.
- if (isSignedIn && !skipAuth) {
+ if (isSignedIn && !skipAuth && agentAllowed) {
list.push({ id: "voiceAgent", title: t("onboarding.steps.voiceAgent"), icon: Sparkles });
}
if (showMeetingStep) {
@@ -223,7 +226,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {
}
list.push({ id: "finish", title: t("onboarding.steps.finish"), icon: Flag });
return list;
- }, [isSignedIn, skipAuth, showMeetingStep, t]);
+ }, [agentAllowed, isSignedIn, skipAuth, showMeetingStep, t]);
const currentStepId = steps[currentStep]?.id;
diff --git a/src/components/OpenAICompatiblePanel.tsx b/src/components/OpenAICompatiblePanel.tsx
index 6a3847285..1b5b72d9d 100644
--- a/src/components/OpenAICompatiblePanel.tsx
+++ b/src/components/OpenAICompatiblePanel.tsx
@@ -6,7 +6,7 @@ import ApiKeyInput from "./ui/ApiKeyInput";
import ModelCardList from "./ui/ModelCardList";
import SearchableModelList, { MODEL_SEARCH_THRESHOLD } from "./ui/SearchableModelList";
import { buildApiUrl, getModelListBaseCandidates, normalizeBaseUrl } from "../config/constants";
-import { isSecureEndpoint } from "../utils/urlUtils";
+import { isSecureHttpEndpoint } from "../utils/urlUtils";
import { GetApiKeyLink } from "./ui/GetApiKeyLink";
interface ModelOption {
@@ -122,7 +122,7 @@ export default function OpenAICompatiblePanel({
return;
}
- if (!isSecureEndpoint(normalized)) {
+ if (!isSecureHttpEndpoint(normalized)) {
if (isMountedRef.current && latestBaseRef.current === normalized) {
setModelsError(t("reasoning.custom.httpsRequired"));
setModelsLoading(false);
diff --git a/src/components/ReasoningModelSelector.tsx b/src/components/ReasoningModelSelector.tsx
index 64f8b3a88..c4bee3fca 100644
--- a/src/components/ReasoningModelSelector.tsx
+++ b/src/components/ReasoningModelSelector.tsx
@@ -24,7 +24,11 @@ import { getRemoteProviderIcon } from "../utils/providerIcons";
import { GetApiKeyLink } from "./ui/GetApiKeyLink";
import { getCachedPlatform } from "../utils/platform";
import { useSettingsStore } from "../stores/settingsStore";
-import { isProviderAllowedByPolicy } from "../stores/policyRules";
+import {
+ filterByokProviderOptionsByPolicy,
+ isProviderAllowedByPolicy,
+ reconcileProviderSelection,
+} from "../stores/policyRules";
import { usePolicySnapshot } from "../hooks/usePolicy";
type CloudModelOption = {
@@ -358,21 +362,26 @@ export default function ReasoningModelSelector({
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 localProviders = useMemo<LocalProvider[]>(() => {
return modelRegistry.getAllProviders().map((provider) => ({
@@ -404,15 +413,15 @@ export default function ReasoningModelSelector({
}, [t]);
const selectedCloudModels = useMemo<CloudModelOption[]>(() => {
- if (selectedCloudProvider === "openai") return openaiModelOptions;
- if (selectedCloudProvider === "custom" || selectedCloudProvider === OPENROUTER_TAB) return [];
+ if (displayedCloudProvider === "openai") return openaiModelOptions;
+ if (displayedCloudProvider === "custom" || displayedCloudProvider === OPENROUTER_TAB) return [];
- const { icon: iconUrl, invertInDark } = getRemoteProviderIcon(selectedCloudProvider);
+ const { icon: iconUrl, invertInDark } = getRemoteProviderIcon(displayedCloudProvider);
const models =
- selectedCloudProvider === "tinfoil"
+ displayedCloudProvider === "tinfoil"
? tinfoilModels.map(toReasoningModel)
- : REASONING_PROVIDERS[selectedCloudProvider as keyof typeof REASONING_PROVIDERS]?.models;
+ : REASONING_PROVIDERS[displayedCloudProvider as keyof typeof REASONING_PROVIDERS]?.models;
if (!models) return [];
@@ -424,7 +433,7 @@ export default function ReasoningModelSelector({
icon: iconUrl,
invertInDark,
}));
- }, [selectedCloudProvider, openaiModelOptions, tinfoilModels, t]);
+ }, [displayedCloudProvider, openaiModelOptions, tinfoilModels, t]);
useEffect(() => {
const localProviderIds = localProviders.map((p) => p.id);
@@ -454,25 +463,28 @@ export default function ReasoningModelSelector({
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") => {
setSelectedMode(newMode);
@@ -482,11 +494,11 @@ export default function ReasoningModelSelector({
window.electronAPI?.llamaServerStop?.();
// The remembered cloud provider may have become policy-disallowed while
// the user was in local mode — fall back to the first allowed one.
- const nextProvider = providerAllowed(selectedCloudProvider)
- ? selectedCloudProvider
+ const nextProvider = providerAllowed(displayedCloudProvider)
+ ? displayedCloudProvider
: cloudProviders[0]?.id;
if (!nextProvider) return;
- if (nextProvider !== selectedCloudProvider) setSelectedCloudProvider(nextProvider);
+ if (nextProvider !== displayedCloudProvider) setSelectedCloudProvider(nextProvider);
setLocalReasoningProvider(nextProvider);
selectDefaultModelForProvider(nextProvider);
} else {
@@ -505,12 +517,15 @@ export default function ReasoningModelSelector({
}
};
- const handleCloudProviderChange = (provider: string) => {
- if (!providerAllowed(provider)) return;
- setSelectedCloudProvider(provider);
- setLocalReasoningProvider(provider);
- selectDefaultModelForProvider(provider);
- };
+ const handleCloudProviderChange = useCallback(
+ (provider: string) => {
+ if (!providerAllowed(provider)) return;
+ setSelectedCloudProvider(provider);
+ setLocalReasoningProvider(provider);
+ selectDefaultModelForProvider(provider);
+ },
+ [providerAllowed, selectDefaultModelForProvider, setLocalReasoningProvider]
+ );
const handleLocalProviderChange = async (providerId: string) => {
setSelectedLocalProvider(providerId);
@@ -565,159 +580,163 @@ export default function ReasoningModelSelector({
{effectiveMode === "cloud" && (
<div className="space-y-2">
- <ProviderTabs
- providers={cloudProviderTabs}
- selectedId={selectedCloudProvider}
- onSelect={handleCloudProviderChange}
- colorScheme="purple"
- wrap
- />
-
- <div>
- {selectedCloudProvider === OPENROUTER_TAB ? (
- <OpenAICompatiblePanel
- key={OPENROUTER_TAB}
- baseUrl={API_ENDPOINTS.OPENROUTER_BASE}
- setBaseUrl={() => {}}
- apiKey={openrouterApiKey}
- setApiKey={setOpenrouterApiKey}
- model={reasoningModel}
- setModel={setReasoningModel}
- lockedBaseUrl
- apiKeyRequired
- getKeyUrl={OPENROUTER_KEYS_URL}
- />
- ) : selectedCloudProvider === "custom" ? (
- <OpenAICompatiblePanel
- key="custom"
- baseUrl={cloudReasoningBaseUrl}
- setBaseUrl={setCloudReasoningBaseUrl}
- apiKey={customReasoningApiKey}
- setApiKey={setCustomReasoningApiKey || (() => {})}
- model={reasoningModel}
- setModel={setReasoningModel}
- defaultBaseUrl={API_ENDPOINTS.OPENAI_BASE}
- />
- ) : (
- <>
- {selectedCloudProvider === "openai" && (
- <div className="space-y-2">
- <div className="flex items-baseline justify-between">
- <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>
- <GetApiKeyLink url="https://platform.openai.com/api-keys" />
+ {cloudProviderTabs.length > 0 && (
+ <ProviderTabs
+ providers={cloudProviderTabs}
+ selectedId={displayedCloudProvider}
+ onSelect={handleCloudProviderChange}
+ colorScheme="purple"
+ wrap
+ />
+ )}
+
+ {providerAllowed(displayedCloudProvider) && (
+ <div>
+ {displayedCloudProvider === OPENROUTER_TAB ? (
+ <OpenAICompatiblePanel
+ key={OPENROUTER_TAB}
+ baseUrl={API_ENDPOINTS.OPENROUTER_BASE}
+ setBaseUrl={() => {}}
+ apiKey={openrouterApiKey}
+ setApiKey={setOpenrouterApiKey}
+ model={reasoningModel}
+ setModel={setReasoningModel}
+ lockedBaseUrl
+ apiKeyRequired
+ getKeyUrl={OPENROUTER_KEYS_URL}
+ />
+ ) : displayedCloudProvider === "custom" ? (
+ <OpenAICompatiblePanel
+ key="custom"
+ baseUrl={cloudReasoningBaseUrl}
+ setBaseUrl={setCloudReasoningBaseUrl}
+ apiKey={customReasoningApiKey}
+ setApiKey={setCustomReasoningApiKey || (() => {})}
+ model={reasoningModel}
+ setModel={setReasoningModel}
+ defaultBaseUrl={API_ENDPOINTS.OPENAI_BASE}
+ />
+ ) : (
+ <>
+ {displayedCloudProvider === "openai" && (
+ <div className="space-y-2">
+ <div className="flex items-baseline justify-between">
+ <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>
+ <GetApiKeyLink url="https://platform.openai.com/api-keys" />
+ </div>
+ <ApiKeyInput
+ apiKey={openaiApiKey}
+ setApiKey={setOpenaiApiKey}
+ label=""
+ helpText=""
+ />
</div>
- <ApiKeyInput
- apiKey={openaiApiKey}
- setApiKey={setOpenaiApiKey}
- label=""
- helpText=""
- />
- </div>
- )}
+ )}
- {selectedCloudProvider === "anthropic" && (
- <div className="space-y-2">
- <div className="flex items-baseline justify-between">
- <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>
- <GetApiKeyLink url="https://console.anthropic.com/settings/keys" />
+ {displayedCloudProvider === "anthropic" && (
+ <div className="space-y-2">
+ <div className="flex items-baseline justify-between">
+ <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>
+ <GetApiKeyLink url="https://console.anthropic.com/settings/keys" />
+ </div>
+ <ApiKeyInput
+ apiKey={anthropicApiKey}
+ setApiKey={setAnthropicApiKey}
+ label=""
+ helpText=""
+ />
</div>
- <ApiKeyInput
- apiKey={anthropicApiKey}
- setApiKey={setAnthropicApiKey}
- label=""
- helpText=""
- />
- </div>
- )}
+ )}
- {selectedCloudProvider === "gemini" && (
- <div className="space-y-2">
- <div className="flex items-baseline justify-between">
- <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>
- <GetApiKeyLink url="https://aistudio.google.com/app/api-keys" />
+ {displayedCloudProvider === "gemini" && (
+ <div className="space-y-2">
+ <div className="flex items-baseline justify-between">
+ <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>
+ <GetApiKeyLink url="https://aistudio.google.com/app/api-keys" />
+ </div>
+ <ApiKeyInput
+ apiKey={geminiApiKey}
+ setApiKey={setGeminiApiKey}
+ label=""
+ helpText=""
+ />
</div>
- <ApiKeyInput
- apiKey={geminiApiKey}
- setApiKey={setGeminiApiKey}
- label=""
- helpText=""
- />
- </div>
- )}
+ )}
- {selectedCloudProvider === "groq" && (
- <div className="space-y-2">
- <div className="flex items-baseline justify-between">
- <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>
- <GetApiKeyLink url="https://console.groq.com/keys" />
+ {displayedCloudProvider === "groq" && (
+ <div className="space-y-2">
+ <div className="flex items-baseline justify-between">
+ <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>
+ <GetApiKeyLink url="https://console.groq.com/keys" />
+ </div>
+ <ApiKeyInput
+ apiKey={groqApiKey}
+ setApiKey={setGroqApiKey}
+ label=""
+ helpText=""
+ />
</div>
- <ApiKeyInput
- apiKey={groqApiKey}
- setApiKey={setGroqApiKey}
- label=""
- helpText=""
- />
- </div>
- )}
+ )}
- {selectedCloudProvider === "tinfoil" && (
- <div className="space-y-2">
- <div className="flex items-baseline justify-between">
- <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>
- <GetApiKeyLink url="https://tinfoil.sh/inference?utm_source=referral&utm_campaign=openwhispr" />
+ {displayedCloudProvider === "tinfoil" && (
+ <div className="space-y-2">
+ <div className="flex items-baseline justify-between">
+ <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>
+ <GetApiKeyLink url="https://tinfoil.sh/inference?utm_source=referral&utm_campaign=openwhispr" />
+ </div>
+ <ApiKeyInput
+ apiKey={tinfoilApiKey}
+ setApiKey={setTinfoilApiKey}
+ label=""
+ helpText=""
+ />
</div>
- <ApiKeyInput
- apiKey={tinfoilApiKey}
- setApiKey={setTinfoilApiKey}
- label=""
- helpText=""
- />
- </div>
- )}
-
- {selectedCloudProvider === "corti" && (
- <div className="space-y-2">
- <p className="text-xs text-muted-foreground">{t("reasoning.corti.euOnly")}</p>
- <div className="flex items-baseline justify-between">
- <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>
- <GetApiKeyLink url="https://www.corti.ai/?utm_source=referral&utm_campaign=openwhispr" />
+ )}
+
+ {displayedCloudProvider === "corti" && (
+ <div className="space-y-2">
+ <p className="text-xs text-muted-foreground">{t("reasoning.corti.euOnly")}</p>
+ <div className="flex items-baseline justify-between">
+ <h4 className="font-medium text-foreground">{t("common.apiKey")}</h4>
+ <GetApiKeyLink url="https://www.corti.ai/?utm_source=referral&utm_campaign=openwhispr" />
+ </div>
+ <ApiKeyInput
+ apiKey={cortiApiKey}
+ setApiKey={setCortiApiKey}
+ label=""
+ helpText=""
+ />
</div>
- <ApiKeyInput
- apiKey={cortiApiKey}
- setApiKey={setCortiApiKey}
- label=""
- helpText=""
+ )}
+
+ <div className="pt-3 space-y-2">
+ <h4 className="text-sm font-medium text-foreground">
+ {t("reasoning.selectModel")}
+ </h4>
+ <ModelCardList
+ models={selectedCloudModels}
+ selectedModel={reasoningModel}
+ onModelSelect={setReasoningModel}
/>
+ {displayedCloudProvider === "tinfoil" && (
+ <>
+ {tinfoilModelsLoading && (
+ <p className="text-xs text-muted-foreground">
+ {t("reasoning.tinfoil.refreshingModels")}
+ </p>
+ )}
+ {!tinfoilModelsLoading && tinfoilModelsError && (
+ <p className="text-xs text-destructive">
+ {t("reasoning.custom.unableToLoadModels")}
+ </p>
+ )}
+ </>
+ )}
</div>
- )}
-
- <div className="pt-3 space-y-2">
- <h4 className="text-sm font-medium text-foreground">
- {t("reasoning.selectModel")}
- </h4>
- <ModelCardList
- models={selectedCloudModels}
- selectedModel={reasoningModel}
- onModelSelect={setReasoningModel}
- />
- {selectedCloudProvider === "tinfoil" && (
- <>
- {tinfoilModelsLoading && (
- <p className="text-xs text-muted-foreground">
- {t("reasoning.tinfoil.refreshingModels")}
- </p>
- )}
- {!tinfoilModelsLoading && tinfoilModelsError && (
- <p className="text-xs text-destructive">
- {t("reasoning.custom.unableToLoadModels")}
- </p>
- )}
- </>
- )}
- </div>
- </>
- )}
- </div>
+ </>
+ )}
+ </div>
+ )}
</div>
)}
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index 12b0c90a0..c186d3cb8 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -112,11 +112,13 @@ import {
canChangeCloudBackupPreference,
effectiveAudioRetentionDays,
effectiveLocalHistoryEnabled,
+ isAgentAllowed,
isCloudBackupAllowed,
lockedLocalHistoryValue,
maxAudioRetentionDays,
} from "../stores/policyRules";
import { usePolicyModeOptions, usePolicySnapshot } from "../hooks/usePolicy";
+import { usePolicyStore } from "../stores/policyStore";
import { canManageSystemAudioInApp } from "../utils/systemAudioAccess";
import WorkspaceSection from "./settings/WorkspaceSection";
import WorkspaceBillingOverview from "./settings/WorkspaceBillingOverview";
@@ -278,7 +280,11 @@ function TranscriptionSection({
toast,
}: TranscriptionSectionProps) {
const { t } = useTranslation();
- const { modes: transcriptionModes, isModeAllowed } = usePolicyModeOptions<InferenceModeOption>(
+ const {
+ modes: transcriptionModes,
+ effectiveMode: effectiveTranscriptionMode,
+ isModeAllowed,
+ } = usePolicyModeOptions<InferenceModeOption>(
[
{
id: "openwhispr",
@@ -307,16 +313,16 @@ function TranscriptionSection({
icon: <Network className="w-4 h-4" />,
},
],
- "transcription"
+ "transcription",
+ transcriptionMode
);
-
const handleTranscriptionModeSelect = (mode: InferenceMode) => {
if (!isModeAllowed(mode)) return;
if (mode === "openwhispr" && !isSignedIn) {
startOnboarding();
return;
}
- if (mode === transcriptionMode) return;
+ if (mode === effectiveTranscriptionMode) return;
setTranscriptionMode(mode);
setUseLocalWhisper(mode === "local");
updateTranscriptionSettings({ useLocalWhisper: mode === "local" });
@@ -391,19 +397,19 @@ function TranscriptionSection({
<div className="space-y-4">
<InferenceModeSelector
modes={transcriptionModes}
- activeMode={transcriptionMode}
+ activeMode={effectiveTranscriptionMode}
onSelect={handleTranscriptionModeSelect}
/>
- {transcriptionMode === "providers" && renderTranscriptionPicker("cloud")}
- {transcriptionMode === "local" && (
+ {effectiveTranscriptionMode === "providers" && renderTranscriptionPicker("cloud")}
+ {effectiveTranscriptionMode === "local" && (
<>
{renderTranscriptionPicker("local")}
{renderPreviewToggle()}
</>
)}
- {transcriptionMode === "self-hosted" && (
+ {effectiveTranscriptionMode === "self-hosted" && (
<SelfHostedPanel
service="transcription"
url={remoteTranscriptionUrl}
@@ -511,6 +517,7 @@ const LLM_TABS: LlmTab[] = [
"noteFormatting",
"chatIntelligence",
];
+const AGENT_LLM_TABS = new Set<LlmTab>(["dictationAgent", "chatIntelligence"]);
function useSubTab<T extends string>(storageKey: string, options: readonly T[], initial?: T) {
const [tab, setTab] = useLocalStorage<T>(storageKey, initial ?? options[0]);
@@ -633,7 +640,11 @@ function LlmsTabs({
renderChatIntelligence: () => React.ReactNode;
}) {
const { t } = useTranslation();
- const [tab, setTab] = useSubTab<LlmTab>("settings.llmsTab", LLM_TABS, initialTab);
+ const agentAllowed = usePolicyStore(isAgentAllowed);
+ const visibleTabIds = agentAllowed
+ ? LLM_TABS
+ : LLM_TABS.filter((tabId) => !AGENT_LLM_TABS.has(tabId));
+ const [tab, setTab] = useSubTab<LlmTab>("settings.llmsTab", visibleTabIds, initialTab);
const subTabs = [
{ id: "dictationCleanup", name: t("settingsPage.llms.tabs.dictationCleanup") },
@@ -641,7 +652,7 @@ function LlmsTabs({
{ id: "dictationTranslation", name: t("settingsPage.llms.tabs.dictationTranslation") },
{ id: "noteFormatting", name: t("settingsPage.llms.tabs.noteFormatting") },
{ id: "chatIntelligence", name: t("settingsPage.llms.tabs.chatIntelligence") },
- ];
+ ].filter((item) => visibleTabIds.includes(item.id as LlmTab));
return (
<div className="space-y-4">
@@ -662,10 +673,14 @@ function LlmsTabs({
}}
/>
<TabPanel active={tab === "dictationCleanup"}>{renderDictationCleanup()}</TabPanel>
- <TabPanel active={tab === "dictationAgent"}>{renderDictationAgent()}</TabPanel>
+ {agentAllowed && (
+ <TabPanel active={tab === "dictationAgent"}>{renderDictationAgent()}</TabPanel>
+ )}
<TabPanel active={tab === "dictationTranslation"}>{renderDictationTranslation()}</TabPanel>
<TabPanel active={tab === "noteFormatting"}>{renderNoteFormatting()}</TabPanel>
- <TabPanel active={tab === "chatIntelligence"}>{renderChatIntelligence()}</TabPanel>
+ {agentAllowed && (
+ <TabPanel active={tab === "chatIntelligence"}>{renderChatIntelligence()}</TabPanel>
+ )}
</div>
);
}
@@ -866,6 +881,7 @@ export default function SettingsPage({
const setTranslationKey = useSettingsStore((s) => s.setTranslationKey);
const settingsPolicyState = usePolicySnapshot();
+ const agentAllowedByPolicy = isAgentAllowed(settingsPolicyState);
const historyLockedByPolicy = lockedLocalHistoryValue(settingsPolicyState) !== null;
const effectiveDataRetentionEnabled = effectiveLocalHistoryEnabled(
settingsPolicyState,
@@ -3397,24 +3413,26 @@ EOF`,
</div>
{/* Voice Agent Hotkey */}
- <div>
- <SectionHeader
- title={t("settingsPage.general.voiceAgentHotkey.title")}
- description={t("settingsPage.general.voiceAgentHotkey.description")}
- />
- <SettingsPanel>
- <SettingsPanelRow>
- <HotkeyListInput
- value={voiceAgentKey}
- onChange={(list) => commitAgentHotkey(setVoiceAgentKey, list)}
- onClear={() => commitAgentHotkey(setVoiceAgentKey, "")}
- validate={validateVoiceAgentHotkey}
- disabled={isAgentHotkeyCommitting}
- maxHotkeys={isUsingNativeShortcut ? 1 : undefined}
- />
- </SettingsPanelRow>
- </SettingsPanel>
- </div>
+ {agentAllowedByPolicy && (
+ <div>
+ <SectionHeader
+ title={t("settingsPage.general.voiceAgentHotkey.title")}
+ description={t("settingsPage.general.voiceAgentHotkey.description")}
+ />
+ <SettingsPanel>
+ <SettingsPanelRow>
+ <HotkeyListInput
+ value={voiceAgentKey}
+ onChange={(list) => commitAgentHotkey(setVoiceAgentKey, list)}
+ onClear={() => commitAgentHotkey(setVoiceAgentKey, "")}
+ validate={validateVoiceAgentHotkey}
+ disabled={isAgentHotkeyCommitting}
+ maxHotkeys={isUsingNativeShortcut ? 1 : undefined}
+ />
+ </SettingsPanelRow>
+ </SettingsPanel>
+ </div>
+ )}
{/* Translation Hotkey */}
<div>
@@ -3489,24 +3507,26 @@ EOF`,
</div>
{/* Chat Agent Hotkey */}
- <div>
- <SectionHeader
- title={t("agentMode.settings.hotkey")}
- description={t("agentMode.settings.hotkeyDescription")}
- />
- <SettingsPanel>
- <SettingsPanelRow>
- <HotkeyListInput
- value={chatAgentKey}
- onChange={(list) => commitAgentHotkey(setChatAgentKey, list)}
- onClear={() => commitAgentHotkey(setChatAgentKey, "")}
- validate={validateChatAgentHotkey}
- disabled={isAgentHotkeyCommitting}
- maxHotkeys={isUsingNativeShortcut ? 1 : undefined}
- />
- </SettingsPanelRow>
- </SettingsPanel>
- </div>
+ {agentAllowedByPolicy && (
+ <div>
+ <SectionHeader
+ title={t("agentMode.settings.hotkey")}
+ description={t("agentMode.settings.hotkeyDescription")}
+ />
+ <SettingsPanel>
+ <SettingsPanelRow>
+ <HotkeyListInput
+ value={chatAgentKey}
+ onChange={(list) => commitAgentHotkey(setChatAgentKey, list)}
+ onClear={() => commitAgentHotkey(setChatAgentKey, "")}
+ validate={validateChatAgentHotkey}
+ disabled={isAgentHotkeyCommitting}
+ maxHotkeys={isUsingNativeShortcut ? 1 : undefined}
+ />
+ </SettingsPanelRow>
+ </SettingsPanel>
+ </div>
+ )}
</div>
);
diff --git a/src/components/TranscriptionModelPicker.tsx b/src/components/TranscriptionModelPicker.tsx
index 08a2ae1e9..db3be70f9 100644
--- a/src/components/TranscriptionModelPicker.tsx
+++ b/src/components/TranscriptionModelPicker.tsx
@@ -25,7 +25,12 @@ import {
type ModelPickerStyles,
} from "../utils/modelPickerStyles";
import { useSettingsStore } from "../stores/settingsStore";
-import { isProviderAllowedByPolicy, reconcileCloudProviderSelection } from "../stores/policyRules";
+import {
+ filterByokProviderOptionsByPolicy,
+ isProviderAllowedByPolicy,
+ reconcileCloudProviderSelection,
+ shouldPersistProviderFallback,
+} from "../stores/policyRules";
import { usePolicySnapshot } from "../hooks/usePolicy";
import { getRemoteProviderIcon } from "../utils/providerIcons";
import { createExternalLinkHandler } from "../utils/externalLinks";
@@ -360,6 +365,7 @@ export default function TranscriptionModelPicker({
const setTinfoilApiKey = useSettingsStore((s) => s.setTinfoilApiKey);
const customTranscriptionApiKey = useSettingsStore((s) => s.customTranscriptionApiKey);
const setCustomTranscriptionApiKey = useSettingsStore((s) => s.setCustomTranscriptionApiKey);
+ const isSignedIn = useSettingsStore((s) => s.isSignedIn);
const effectiveLocal = mode === "local" ? true : mode === "cloud" ? false : useLocalWhisper;
const [localModels, setLocalModels] = useState<LocalModel[]>([]);
const [parakeetModels, setParakeetModels] = useState<LocalModel[]>([]);
@@ -386,7 +392,6 @@ export default function TranscriptionModelPicker({
const parakeetModelsLoadQueueRef = useRef<Promise<void>>(Promise.resolve());
const loadLocalModelsRef = useRef<(() => Promise<void>) | null>(null);
const loadParakeetModelsRef = useRef<(() => Promise<void>) | null>(null);
- const ensureValidCloudSelectionRef = useRef<(() => void) | null>(null);
const selectedLocalModelRef = useRef(selectedLocalModel);
const onLocalModelSelectRef = useRef(onLocalModelSelect);
@@ -403,22 +408,20 @@ export default function TranscriptionModelPicker({
[streamingOnly]
);
const cloudProviders = useMemo(
- () => availableCloudProviders.filter((p) => providerAllowed(p.id)),
- [availableCloudProviders, providerAllowed]
+ () => filterByokProviderOptionsByPolicy(availableCloudProviders, "transcription", policyState),
+ [availableCloudProviders, policyState]
);
const cloudProviderTabs = useMemo(() => {
const availableIds = new Set(availableCloudProviders.map((p) => p.id));
if (!streamingOnly) availableIds.add("custom");
- return CLOUD_PROVIDER_TABS.filter((p) => availableIds.has(p.id)).map((provider) => {
- const named =
+ const tabs = CLOUD_PROVIDER_TABS.filter((provider) => availableIds.has(provider.id)).map(
+ (provider) =>
provider.id === "custom"
? { ...provider, name: t("transcription.customProvider") }
- : provider;
- return providerAllowed(named.id)
- ? named
- : { ...named, disabled: true, disabledLabel: t("common.managedByOrg") };
- });
- }, [availableCloudProviders, providerAllowed, streamingOnly, t]);
+ : provider
+ );
+ return filterByokProviderOptionsByPolicy(tabs, "transcription", policyState);
+ }, [availableCloudProviders, policyState, streamingOnly, t]);
useEffect(() => {
selectedLocalModelRef.current = selectedLocalModel;
@@ -478,7 +481,7 @@ export default function TranscriptionModelPicker({
return queuedLoad;
}, []);
- const ensureValidCloudSelection = useCallback(() => {
+ const effectiveCloudSelection = useMemo(() => {
// 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.
@@ -489,25 +492,51 @@ export default function TranscriptionModelPicker({
cloudTranscriptionBaseUrl !== API_ENDPOINTS.TRANSCRIPTION_BASE &&
!knownProviderUrls.includes(cloudTranscriptionBaseUrl)
);
- 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);
+ return (
+ reconcileCloudProviderSelection({
+ selectedProvider: selectedCloudProvider,
+ selectedModel: selectedCloudModel,
+ allowedProviders: cloudProviders,
+ customAllowed: !streamingOnly && providerAllowed("custom"),
+ hasCustomUrl,
+ }) ?? { provider: selectedCloudProvider, model: selectedCloudModel }
+ );
}, [
availableCloudProviders,
cloudProviders,
cloudTranscriptionBaseUrl,
selectedCloudProvider,
selectedCloudModel,
- onCloudProviderSelect,
- onCloudModelSelect,
providerAllowed,
+ streamingOnly,
+ ]);
+ const displayedCloudProvider = effectiveCloudSelection.provider;
+ const displayedCloudModel = effectiveCloudSelection.model;
+
+ useEffect(() => {
+ if (
+ effectiveLocal ||
+ !shouldPersistProviderFallback(policyState, isSignedIn) ||
+ (effectiveCloudSelection.provider === selectedCloudProvider &&
+ effectiveCloudSelection.model === selectedCloudModel)
+ ) {
+ return;
+ }
+ if (effectiveCloudSelection.provider !== selectedCloudProvider) {
+ onCloudProviderSelect(effectiveCloudSelection.provider);
+ }
+ if (effectiveCloudSelection.model !== selectedCloudModel) {
+ onCloudModelSelect(effectiveCloudSelection.model);
+ }
+ }, [
+ effectiveCloudSelection,
+ effectiveLocal,
+ isSignedIn,
+ onCloudModelSelect,
+ onCloudProviderSelect,
+ policyState,
+ selectedCloudModel,
+ selectedCloudProvider,
]);
useEffect(() => {
@@ -516,10 +545,6 @@ export default function TranscriptionModelPicker({
useEffect(() => {
loadParakeetModelsRef.current = loadParakeetModels;
}, [loadParakeetModels]);
- useEffect(() => {
- ensureValidCloudSelectionRef.current = ensureValidCloudSelection;
- }, [ensureValidCloudSelection]);
-
useEffect(() => {
if (!effectiveLocal) return;
@@ -537,7 +562,6 @@ export default function TranscriptionModelPicker({
hasLoadedRef.current = false;
hasLoadedParakeetRef.current = false;
- ensureValidCloudSelectionRef.current?.();
}, [effectiveLocal]);
useEffect(() => {
@@ -637,9 +661,8 @@ export default function TranscriptionModelPicker({
const handleModeChange = useCallback(
(isLocal: boolean) => {
onModeChange(isLocal);
- if (!isLocal) ensureValidCloudSelection();
},
- [onModeChange, ensureValidCloudSelection]
+ [onModeChange]
);
const handleCloudProviderChange = useCallback(
@@ -748,12 +771,12 @@ export default function TranscriptionModelPicker({
);
const currentCloudProvider = useMemo<TranscriptionProviderData | undefined>(
- () => cloudProviders.find((p) => p.id === selectedCloudProvider),
- [cloudProviders, selectedCloudProvider]
+ () => cloudProviders.find((p) => p.id === displayedCloudProvider),
+ [cloudProviders, displayedCloudProvider]
);
const providerCredentials =
- PROVIDER_CREDENTIALS[selectedCloudProvider] ?? PROVIDER_CREDENTIALS.openai;
+ PROVIDER_CREDENTIALS[displayedCloudProvider] ?? PROVIDER_CREDENTIALS.openai;
const credentialValues: Record<ProviderCredentialField["key"], string> = {
openaiApiKey,
groqApiKey,
@@ -779,7 +802,7 @@ export default function TranscriptionModelPicker({
const cloudModelOptions = useMemo(() => {
if (!currentCloudProvider) return [];
- const { icon, invertInDark } = getRemoteProviderIcon(selectedCloudProvider);
+ const { icon, invertInDark } = getRemoteProviderIcon(displayedCloudProvider);
return currentCloudProvider.models.map((m) => ({
value: m.id,
label: m.name,
@@ -789,7 +812,7 @@ export default function TranscriptionModelPicker({
icon,
invertInDark,
}));
- }, [currentCloudProvider, selectedCloudProvider, t]);
+ }, [currentCloudProvider, displayedCloudProvider, t]);
const progressDisplay = useMemo(() => {
if (!effectiveLocal) return null;
@@ -964,127 +987,133 @@ export default function TranscriptionModelPicker({
{!effectiveLocal ? (
<>
- <ProviderTabs
- providers={cloudProviderTabs}
- selectedId={selectedCloudProvider}
- onSelect={handleCloudProviderChange}
- colorScheme="purple"
- wrap
- />
+ {cloudProviderTabs.length > 0 && (
+ <ProviderTabs
+ providers={cloudProviderTabs}
+ selectedId={displayedCloudProvider}
+ onSelect={handleCloudProviderChange}
+ colorScheme="purple"
+ wrap
+ />
+ )}
- <div>
- {selectedCloudProvider === "custom" ? (
- <div className="space-y-2">
- <div className="space-y-1.5">
- <label className="block text-xs font-medium text-foreground">
- {t("transcription.endpointUrl")}
- </label>
- <Input
- value={cloudTranscriptionBaseUrl}
- onChange={(e) => setCloudTranscriptionBaseUrl?.(e.target.value)}
- onBlur={handleBaseUrlBlur}
- placeholder="https://your-api.example.com/v1"
- className="h-8 text-sm"
- />
- </div>
+ {providerAllowed(displayedCloudProvider) && (
+ <div>
+ {displayedCloudProvider === "custom" ? (
+ <div className="space-y-2">
+ <div className="space-y-1.5">
+ <label className="block text-xs font-medium text-foreground">
+ {t("transcription.endpointUrl")}
+ </label>
+ <Input
+ value={cloudTranscriptionBaseUrl}
+ onChange={(e) => setCloudTranscriptionBaseUrl?.(e.target.value)}
+ onBlur={handleBaseUrlBlur}
+ placeholder="https://your-api.example.com/v1"
+ className="h-8 text-sm"
+ />
+ </div>
- <ApiKeyInput
- apiKey={customTranscriptionApiKey}
- setApiKey={setCustomTranscriptionApiKey}
- label={t("transcription.apiKeyOptional")}
- helpText=""
- />
-
- <div className="space-y-1.5">
- <label className="block text-xs font-medium text-foreground">
- {t("common.model")}
- </label>
- <Input
- value={selectedCloudModel}
- onChange={(e) => onCloudModelSelect(e.target.value)}
- placeholder="whisper-1"
- className="h-8 text-sm"
+ <ApiKeyInput
+ apiKey={customTranscriptionApiKey}
+ setApiKey={setCustomTranscriptionApiKey}
+ label={t("transcription.apiKeyOptional")}
+ helpText=""
/>
- </div>
- {/azure\.com/i.test(cloudTranscriptionBaseUrl || "") && (
- <p className="text-xs text-muted-foreground">{t("transcription.azureHint")}</p>
- )}
- </div>
- ) : (
- <div className="space-y-2">
- {providerCredentials.fields.map((field, index) => (
- <div key={field.key} className="space-y-1.5">
- <div className="flex items-center justify-between">
- <label className="text-xs font-medium text-foreground">
- {field.labelKey ? t(field.labelKey) : t("common.apiKey")}
- </label>
- {index === 0 && (
- <GetApiKeyLink
- url={providerCredentials.consoleUrl}
- labelKey="transcription.getKey"
- className="text-xs text-primary/70 hover:text-primary transition-colors cursor-pointer"
+ <div className="space-y-1.5">
+ <label className="block text-xs font-medium text-foreground">
+ {t("common.model")}
+ </label>
+ <Input
+ value={displayedCloudModel}
+ onChange={(e) => onCloudModelSelect(e.target.value)}
+ placeholder="whisper-1"
+ className="h-8 text-sm"
+ />
+ </div>
+
+ {/azure\.com/i.test(cloudTranscriptionBaseUrl || "") && (
+ <p className="text-xs text-muted-foreground">{t("transcription.azureHint")}</p>
+ )}
+ </div>
+ ) : (
+ <div className="space-y-2">
+ {providerCredentials.fields.map((field, index) => (
+ <div key={field.key} className="space-y-1.5">
+ <div className="flex items-center justify-between">
+ <label className="text-xs font-medium text-foreground">
+ {field.labelKey ? t(field.labelKey) : t("common.apiKey")}
+ </label>
+ {index === 0 && (
+ <GetApiKeyLink
+ url={providerCredentials.consoleUrl}
+ labelKey="transcription.getKey"
+ className="text-xs text-primary/70 hover:text-primary transition-colors cursor-pointer"
+ />
+ )}
+ </div>
+ {field.input === "secret" ? (
+ <ApiKeyInput
+ apiKey={credentialValues[field.key]}
+ setApiKey={credentialSetters[field.key]}
+ label=""
+ helpText=""
+ />
+ ) : field.input === "select" ? (
+ <Select
+ value={credentialValues[field.key]}
+ onValueChange={credentialSetters[field.key]}
+ >
+ <SelectTrigger className="h-8 text-sm">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {field.options?.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : (
+ <Input
+ value={credentialValues[field.key]}
+ onChange={(e) => credentialSetters[field.key](e.target.value)}
+ placeholder={field.placeholder}
+ className="h-8 text-sm"
/>
)}
</div>
- {field.input === "secret" ? (
- <ApiKeyInput
- apiKey={credentialValues[field.key]}
- setApiKey={credentialSetters[field.key]}
- label=""
- helpText=""
- />
- ) : field.input === "select" ? (
- <Select
- value={credentialValues[field.key]}
- onValueChange={credentialSetters[field.key]}
- >
- <SelectTrigger className="h-8 text-sm">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {field.options?.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- ) : (
- <Input
- value={credentialValues[field.key]}
- onChange={(e) => credentialSetters[field.key](e.target.value)}
- placeholder={field.placeholder}
- className="h-8 text-sm"
- />
+ ))}
+
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-foreground">
+ {t("common.model")}
+ </label>
+ <ModelCardList
+ models={cloudModelOptions}
+ selectedModel={displayedCloudModel}
+ onModelSelect={onCloudModelSelect}
+ colorScheme="purple"
+ />
+ {displayedCloudProvider === "tinfoil" && (
+ <p className="text-xs text-muted-foreground/70">
+ {t("transcription.tinfoil.transportNote")}{" "}
+ <a
+ href={TINFOIL_AUDIO_DOCS_URL}
+ onClick={createExternalLinkHandler(TINFOIL_AUDIO_DOCS_URL)}
+ className="text-primary/70 hover:text-primary transition-colors"
+ >
+ {t("transcription.tinfoil.docsLink")}
+ </a>
+ </p>
)}
</div>
- ))}
-
- <div className="space-y-1.5">
- <label className="text-xs font-medium text-foreground">{t("common.model")}</label>
- <ModelCardList
- models={cloudModelOptions}
- selectedModel={selectedCloudModel}
- onModelSelect={onCloudModelSelect}
- colorScheme="purple"
- />
- {selectedCloudProvider === "tinfoil" && (
- <p className="text-xs text-muted-foreground/70">
- {t("transcription.tinfoil.transportNote")}{" "}
- <a
- href={TINFOIL_AUDIO_DOCS_URL}
- onClick={createExternalLinkHandler(TINFOIL_AUDIO_DOCS_URL)}
- className="text-primary/70 hover:text-primary transition-colors"
- >
- {t("transcription.tinfoil.docsLink")}
- </a>
- </p>
- )}
</div>
- </div>
- )}
- </div>
+ )}
+ </div>
+ )}
</>
) : (
<>
diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsx
index f03aff028..992876820 100644
--- a/src/components/notes/PersonalNotesView.tsx
+++ b/src/components/notes/PersonalNotesView.tsx
@@ -1,5 +1,6 @@
import { useState, useEffect, useRef, useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
+import { useShallow } from "zustand/react/shallow";
import { Plus, SquarePen, Search, Sparkles } from "lucide-react";
import { useToast } from "../ui/useToast";
import NoteEditor from "./NoteEditor";
@@ -15,6 +16,7 @@ import type { NoteItem } from "../../types/electron";
import {
useSettingsStore,
selectIsCloudNoteFormattingMode,
+ selectPolicyEffectiveSettings,
selectResolvedNoteFormatting,
} from "../../stores/settingsStore";
import { cn } from "../lib/utils";
@@ -54,7 +56,7 @@ import { useNotesOnboarding } from "../../hooks/useNotesOnboarding";
import { useTeamSpacesCapability } from "../../hooks/useTeamSpacesCapability";
import { useWorkspaceStore } from "../../stores/workspaceStore";
import { useAuth } from "../../hooks/useAuth";
-import { useTranscriptionContextAllowed } from "../../hooks/usePolicy";
+import { usePolicySnapshot, useTranscriptionContextAllowed } from "../../hooks/usePolicy";
import NotesOnboarding from "./NotesOnboarding";
import { isRegenerableNoteTitle } from "../../helpers/regenerableNoteTitle";
import { handleMeetingRecordingRequest } from "../../helpers/meetingRecordingRequest";
@@ -198,8 +200,18 @@ export default function PersonalNotesView({
[commitDraft, persistPendingWrites, takePendingSnapshots]
);
const { toast } = useToast();
- const isCloudMode = useSettingsStore(selectIsCloudNoteFormattingMode);
- const effectiveModelId = useSettingsStore((s) => selectResolvedNoteFormatting(s).model);
+ const policyState = usePolicySnapshot();
+ const noteFormatting = useSettingsStore(
+ useShallow((settings) => {
+ const effectiveSettings = selectPolicyEffectiveSettings(settings, policyState);
+ return {
+ isCloudMode: selectIsCloudNoteFormattingMode(effectiveSettings),
+ modelId: selectResolvedNoteFormatting(effectiveSettings).model,
+ };
+ })
+ );
+ const isCloudMode = noteFormatting.isCloudMode;
+ const effectiveModelId = noteFormatting.modelId;
const { isComplete: isOnboardingComplete, complete: completeOnboarding } = useNotesOnboarding();
const { isSignedIn } = useAuth();
const teamSpacesAvailable = useTeamSpacesCapability(isSignedIn);
diff --git a/src/components/notes/ShareNoteDialog.tsx b/src/components/notes/ShareNoteDialog.tsx
index c6e8972d0..d441f0cf4 100644
--- a/src/components/notes/ShareNoteDialog.tsx
+++ b/src/components/notes/ShareNoteDialog.tsx
@@ -31,6 +31,8 @@ import {
import { useToast } from "../ui/useToast";
import MemberAvatar from "../MemberAvatar";
import {
+ filterShareVisibilityOptions,
+ hasUsableExternalShareVisibility,
isShareActionAllowed,
isShareVisibilityAllowed,
type SharePolicyAction,
@@ -47,6 +49,12 @@ import type {
} from "../../types/electron";
const SHARE_VIEWER_BASE_URL = "https://notes.openwhispr.com";
+const SHARE_VISIBILITY_OPTIONS: Array<{ id: ShareVisibility }> = [
+ { id: "private" },
+ { id: "invited" },
+ { id: "link" },
+ { id: "domain" },
+];
interface ShareNoteDialogProps {
open: boolean;
@@ -114,13 +122,21 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD
[currentVisibility, policyState]
);
const canManageAccess = access?.can_manage_access ?? true;
- const canInvite = canManageAccess && shareActionAllowed("invite");
- const sharingRestrictedByPolicy =
- !visibilityAllowed("link") && !visibilityAllowed("domain") && !visibilityAllowed("invited");
+ const inviteAllowedByPolicy = shareActionAllowed("invite");
+ const canInvite = canManageAccess && inviteAllowedByPolicy;
+ const sharingRestrictedByPolicy = !hasUsableExternalShareVisibility(
+ policyState,
+ showDomainOption
+ );
const canBeginSharing = canManageAccess && !sharingRestrictedByPolicy;
- const canUseLink =
- canManageAccess &&
- shareActionAllowed(currentVisibility === "private" ? "create-link" : "copy-link");
+ const linkActionAllowedByPolicy = shareActionAllowed(
+ currentVisibility === "private" ? "create-link" : "copy-link"
+ );
+ const canUseLink = canManageAccess && linkActionAllowedByPolicy;
+ const visibleShareVisibilities = useMemo(
+ () => filterShareVisibilityOptions(SHARE_VISIBILITY_OPTIONS, policyState).map(({ id }) => id),
+ [policyState]
+ );
// Principal search needs the ACL API; legacy servers only take raw emails.
const canSearchPrincipals = canInvite && Boolean(access?.can_manage_access);
const invitations = useMemo(() => cached?.invitations ?? [], [cached?.invitations]);
@@ -646,18 +662,21 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD
{!cloudId ? (
<>
<DialogDescription className="text-xs text-foreground/50">
- {t("noteEditor.share.dialog.syncPrompt")}
+ {sharingRestrictedByPolicy
+ ? t("common.managedByOrg")
+ : t("noteEditor.share.dialog.syncPrompt")}
</DialogDescription>
- <Button
- size="sm"
- onClick={() => void handleSyncAndShare()}
- disabled={syncing || !canBeginSharing}
- title={sharingRestrictedByPolicy ? t("common.managedByOrg") : undefined}
- className="h-8 px-3 text-xs gap-1.5 justify-self-start"
- >
- {syncing && <Loader2 size={12} className="animate-spin" />}
- {t("noteEditor.share.dialog.syncAndShare")}
- </Button>
+ {!sharingRestrictedByPolicy && (
+ <Button
+ size="sm"
+ onClick={() => void handleSyncAndShare()}
+ disabled={syncing || !canBeginSharing}
+ className="h-8 px-3 text-xs gap-1.5 justify-self-start"
+ >
+ {syncing && <Loader2 size={12} className="animate-spin" />}
+ {t("noteEditor.share.dialog.syncAndShare")}
+ </Button>
+ )}
</>
) : loadError ? (
<div className="flex items-center justify-between gap-2 py-1">
@@ -679,87 +698,93 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD
{t("noteEditor.share.dialog.description")}
</DialogDescription>
- <div className="relative">
- <div className="flex items-center gap-2">
- <input
- ref={emailInputRef}
- type="text"
- value={emailInput}
- onChange={(e) => {
- setEmailInput(e.target.value);
- if (inputError) setInputError(null);
- }}
- onKeyDown={onKeyDown}
- placeholder={t("noteEditor.share.dialog.searchPlaceholder")}
- disabled={loading || submitting || !canInvite}
- className={cn(
- notesInputClass,
- "flex-1 disabled:opacity-50 disabled:cursor-not-allowed"
- )}
- aria-label={t("noteEditor.share.dialog.emailLabel")}
- aria-invalid={inputError ? true : undefined}
- aria-describedby={inputError ? "share-invite-error" : undefined}
- />
- <Button
- size="sm"
- onClick={() => void handleShareInput()}
- disabled={loading || submitting || !canInvite || !emailInput.trim()}
- className="h-8 px-3 text-xs gap-1.5"
- >
- {submitting && <Loader2 size={12} className="animate-spin" />}
- {t("noteEditor.share.dialog.shareButton")}
- </Button>
- </div>
+ {inviteAllowedByPolicy && (
+ <div className="relative">
+ <div className="flex items-center gap-2">
+ <input
+ ref={emailInputRef}
+ type="text"
+ value={emailInput}
+ onChange={(e) => {
+ setEmailInput(e.target.value);
+ if (inputError) setInputError(null);
+ }}
+ onKeyDown={onKeyDown}
+ placeholder={t("noteEditor.share.dialog.searchPlaceholder")}
+ disabled={loading || submitting || !canInvite}
+ className={cn(
+ notesInputClass,
+ "flex-1 disabled:opacity-50 disabled:cursor-not-allowed"
+ )}
+ aria-label={t("noteEditor.share.dialog.emailLabel")}
+ aria-invalid={inputError ? true : undefined}
+ aria-describedby={inputError ? "share-invite-error" : undefined}
+ />
+ <Button
+ size="sm"
+ onClick={() => void handleShareInput()}
+ disabled={loading || submitting || !canInvite || !emailInput.trim()}
+ className="h-8 px-3 text-xs gap-1.5"
+ >
+ {submitting && <Loader2 size={12} className="animate-spin" />}
+ {t("noteEditor.share.dialog.shareButton")}
+ </Button>
+ </div>
- {access && emailInput.trim() && (searchingSuggestions || suggestions.length > 0) && (
- <div className="absolute z-20 top-9 left-0 right-[72px] max-h-44 overflow-y-auto rounded-lg border border-border bg-popover p-1 shadow-lg">
- {searchingSuggestions && suggestions.length === 0 ? (
- <div className="h-8 flex items-center justify-center">
- <Loader2 size={12} className="animate-spin text-foreground/40" />
- </div>
- ) : (
- suggestions.map((principal) => (
- <button
- key={`${principal.type}:${principal.id ?? principal.email}`}
- type="button"
- onClick={() => void handlePrincipalGrant(principal)}
- className="flex items-center gap-2 w-full min-w-0 px-2 h-9 rounded-md text-left hover:bg-foreground/5 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- >
- {principal.type === "team" ||
- principal.type === "folder" ||
- principal.type === "workspace" ? (
- <AudienceIcon />
- ) : (
- <MemberAvatar
- name={principal.name}
- email={principal.email ?? principal.name ?? ""}
- image={principal.image}
- />
- )}
- <span className="min-w-0 flex-1">
- <span className="block text-xs text-foreground truncate">
- {principal.name || principal.email}
- </span>
- {principal.name && principal.email && (
- <span className="block text-[11px] text-foreground/40 truncate">
- {principal.email}
+ {access &&
+ emailInput.trim() &&
+ (searchingSuggestions || suggestions.length > 0) && (
+ <div className="absolute z-20 top-9 left-0 right-[72px] max-h-44 overflow-y-auto rounded-lg border border-border bg-popover p-1 shadow-lg">
+ {searchingSuggestions && suggestions.length === 0 ? (
+ <div className="h-8 flex items-center justify-center">
+ <Loader2 size={12} className="animate-spin text-foreground/40" />
+ </div>
+ ) : (
+ suggestions.map((principal) => (
+ <button
+ key={`${principal.type}:${principal.id ?? principal.email}`}
+ type="button"
+ onClick={() => void handlePrincipalGrant(principal)}
+ className="flex items-center gap-2 w-full min-w-0 px-2 h-9 rounded-md text-left hover:bg-foreground/5 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ >
+ {principal.type === "team" ||
+ principal.type === "folder" ||
+ principal.type === "workspace" ? (
+ <AudienceIcon />
+ ) : (
+ <MemberAvatar
+ name={principal.name}
+ email={principal.email ?? principal.name ?? ""}
+ image={principal.image}
+ />
+ )}
+ <span className="min-w-0 flex-1">
+ <span className="block text-xs text-foreground truncate">
+ {principal.name || principal.email}
+ </span>
+ {principal.name && principal.email && (
+ <span className="block text-[11px] text-foreground/40 truncate">
+ {principal.email}
+ </span>
+ )}
</span>
- )}
- </span>
- </button>
- ))
+ </button>
+ ))
+ )}
+ </div>
)}
- </div>
- )}
- </div>
+ </div>
+ )}
- <p
- id="share-invite-error"
- aria-live="polite"
- className={cn("text-xs text-red-500/90 -mt-1", !inputError && "sr-only")}
- >
- {inputError}
- </p>
+ {inviteAllowedByPolicy && (
+ <p
+ id="share-invite-error"
+ aria-live="polite"
+ className={cn("text-xs text-red-500/90 -mt-1", !inputError && "sr-only")}
+ >
+ {inputError}
+ </p>
+ )}
<div className="flex flex-col gap-1.5 mt-1">
{(access?.owner || !isTeamNote) && (
@@ -792,16 +817,12 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD
(!grant.inherited || access.can_manage_inherited_access) &&
shareActionAllowed("change-grant")
)}
+ showPermissionActions={shareActionAllowed("change-grant")}
canRemove={Boolean(
access?.can_manage_access &&
(!grant.inherited || access.can_manage_inherited_access) &&
shareActionAllowed("remove-grant")
)}
- policyRestrictedReason={
- access?.can_manage_access && !shareActionAllowed("change-grant")
- ? t("common.managedByOrg")
- : undefined
- }
busy={busyGrantId === grant.id}
onPermissionChange={(permission) => void handleGrantPermission(grant, permission)}
onRemove={() => void handleRemoveGrant(grant)}
@@ -855,16 +876,15 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" sideOffset={4}>
- <DropdownMenuItem
- className="text-xs"
- disabled={
- resendingId === invitation.id ||
- !shareActionAllowed("resend-invitation")
- }
- onClick={() => void handleResend(invitation)}
- >
- {t("noteEditor.share.dialog.resend")}
- </DropdownMenuItem>
+ {shareActionAllowed("resend-invitation") && (
+ <DropdownMenuItem
+ className="text-xs"
+ disabled={resendingId === invitation.id}
+ onClick={() => void handleResend(invitation)}
+ >
+ {t("noteEditor.share.dialog.resend")}
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem
className="text-xs text-red-500"
onClick={() => void handleRevoke(invitation)}
@@ -888,46 +908,44 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD
value={share?.visibility ?? "private"}
ownerDomain={ownerDomain}
showDomainOption={showDomainOption}
- optionDisabledReasons={{
- ...(visibilityAllowed("invited") ? {} : { invited: t("common.managedByOrg") }),
- ...(visibilityAllowed("link") ? {} : { link: t("common.managedByOrg") }),
- ...(visibilityAllowed("domain") ? {} : { domain: t("common.managedByOrg") }),
- }}
+ visibleOptions={visibleShareVisibilities}
disabled={loading || !share || !canManageAccess || savingVisibility || linkBusy}
onChange={(v) => void applyVisibility(v)}
/>
<div className="flex-1" />
- <Button
- variant={isPrivate ? "default" : "outline"}
- size="sm"
- className="h-8 px-3 text-xs gap-1.5"
- disabled={loading || !share || !canUseLink || savingVisibility || linkBusy}
- onClick={() => void handleLinkButton()}
- >
- {linkBusy ? (
- <>
- <Loader2 size={12} className="animate-spin" />
- {isPrivate
- ? t("noteEditor.share.dialog.createLink")
- : t("noteEditor.share.dialog.copyLink")}
- </>
- ) : copied ? (
- <>
- <Check size={12} />
- {t("noteEditor.share.dialog.copied")}
- </>
- ) : isPrivate ? (
- <>
- <Link2 size={12} />
- {t("noteEditor.share.dialog.createLink")}
- </>
- ) : (
- <>
- <Copy size={12} />
- {t("noteEditor.share.dialog.copyLink")}
- </>
- )}
- </Button>
+ {linkActionAllowedByPolicy && (
+ <Button
+ variant={isPrivate ? "default" : "outline"}
+ size="sm"
+ className="h-8 px-3 text-xs gap-1.5"
+ disabled={loading || !share || !canUseLink || savingVisibility || linkBusy}
+ onClick={() => void handleLinkButton()}
+ >
+ {linkBusy ? (
+ <>
+ <Loader2 size={12} className="animate-spin" />
+ {isPrivate
+ ? t("noteEditor.share.dialog.createLink")
+ : t("noteEditor.share.dialog.copyLink")}
+ </>
+ ) : copied ? (
+ <>
+ <Check size={12} />
+ {t("noteEditor.share.dialog.copied")}
+ </>
+ ) : isPrivate ? (
+ <>
+ <Link2 size={12} />
+ {t("noteEditor.share.dialog.createLink")}
+ </>
+ ) : (
+ <>
+ <Copy size={12} />
+ {t("noteEditor.share.dialog.copyLink")}
+ </>
+ )}
+ </Button>
+ )}
</div>
</>
)}
@@ -967,16 +985,16 @@ function AudienceIcon() {
function AccessGrantRow({
grant,
canChangePermission,
+ showPermissionActions,
canRemove,
- policyRestrictedReason,
busy,
onPermissionChange,
onRemove,
}: {
grant: NoteAccessGrant;
canChangePermission: boolean;
+ showPermissionActions: boolean;
canRemove: boolean;
- policyRestrictedReason?: string;
busy: boolean;
onPermissionChange: (permission: NoteAccessGrant["permission"]) => void;
onRemove: () => void;
@@ -1035,32 +1053,26 @@ function AccessGrantRow({
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" sideOffset={4}>
- <DropdownMenuItem
- className="text-xs gap-2"
- disabled={!canChangePermission}
- onClick={() => onPermissionChange("viewer")}
- >
- {grant.permission === "viewer" && <Check size={11} />}
- {t("noteEditor.share.dialog.viewer")}
- {!canChangePermission && policyRestrictedReason && (
- <span className="ml-auto text-[10px] uppercase tracking-wide text-muted-foreground/70">
- {policyRestrictedReason}
- </span>
- )}
- </DropdownMenuItem>
- <DropdownMenuItem
- className="text-xs gap-2"
- disabled={!canChangePermission}
- onClick={() => onPermissionChange("editor")}
- >
- {grant.permission === "editor" && <Check size={11} />}
- {t("noteEditor.share.dialog.editor")}
- {!canChangePermission && policyRestrictedReason && (
- <span className="ml-auto text-[10px] uppercase tracking-wide text-muted-foreground/70">
- {policyRestrictedReason}
- </span>
- )}
- </DropdownMenuItem>
+ {showPermissionActions && (
+ <>
+ <DropdownMenuItem
+ className="text-xs gap-2"
+ disabled={!canChangePermission}
+ onClick={() => onPermissionChange("viewer")}
+ >
+ {grant.permission === "viewer" && <Check size={11} />}
+ {t("noteEditor.share.dialog.viewer")}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ className="text-xs gap-2"
+ disabled={!canChangePermission}
+ onClick={() => onPermissionChange("editor")}
+ >
+ {grant.permission === "editor" && <Check size={11} />}
+ {t("noteEditor.share.dialog.editor")}
+ </DropdownMenuItem>
+ </>
+ )}
<DropdownMenuItem
className="text-xs text-red-500"
disabled={!canRemove}
diff --git a/src/components/notes/ShareVisibilityMenu.tsx b/src/components/notes/ShareVisibilityMenu.tsx
index 42f493e1a..afac48d04 100644
--- a/src/components/notes/ShareVisibilityMenu.tsx
+++ b/src/components/notes/ShareVisibilityMenu.tsx
@@ -14,8 +14,7 @@ interface ShareVisibilityMenuProps {
value: ShareVisibility;
ownerDomain: string;
showDomainOption: boolean;
- /** Policy-restricted options render disabled with this reason instead of hiding. */
- optionDisabledReasons?: Partial<Record<ShareVisibility, string>>;
+ visibleOptions?: readonly ShareVisibility[];
disabled?: boolean;
onChange: (visibility: ShareVisibility) => void;
}
@@ -24,13 +23,15 @@ export default function ShareVisibilityMenu({
value,
ownerDomain,
showDomainOption,
- optionDisabledReasons,
+ visibleOptions = ["private", "invited", "link", "domain"],
disabled,
onChange,
}: ShareVisibilityMenuProps) {
const { t } = useTranslation();
const current = renderCurrent(value, ownerDomain, t);
+ const isVisible = (visibility: ShareVisibility): boolean =>
+ visibility === "private" || visibleOptions.includes(visibility);
return (
<DropdownMenu>
@@ -60,26 +61,27 @@ export default function ShareVisibilityMenu({
active={value === "private"}
onSelect={() => onChange("private")}
/>
- <VisibilityItem
- icon={<Users size={13} className="text-foreground/50" />}
- label={t("noteEditor.share.dialog.visibility.invited")}
- active={value === "invited"}
- disabledReason={optionDisabledReasons?.invited}
- onSelect={() => onChange("invited")}
- />
- <VisibilityItem
- icon={<Globe size={13} className="text-foreground/50" />}
- label={t("noteEditor.share.dialog.visibility.link")}
- active={value === "link"}
- disabledReason={optionDisabledReasons?.link}
- onSelect={() => onChange("link")}
- />
- {showDomainOption && (
+ {isVisible("invited") && (
+ <VisibilityItem
+ icon={<Users size={13} className="text-foreground/50" />}
+ label={t("noteEditor.share.dialog.visibility.invited")}
+ active={value === "invited"}
+ onSelect={() => onChange("invited")}
+ />
+ )}
+ {isVisible("link") && (
+ <VisibilityItem
+ icon={<Globe size={13} className="text-foreground/50" />}
+ label={t("noteEditor.share.dialog.visibility.link")}
+ active={value === "link"}
+ onSelect={() => onChange("link")}
+ />
+ )}
+ {showDomainOption && isVisible("domain") && (
<VisibilityItem
icon={<Building2 size={13} className="text-foreground/50" />}
label={t("noteEditor.share.dialog.visibility.domain", { domain: ownerDomain })}
active={value === "domain"}
- disabledReason={optionDisabledReasons?.domain}
onSelect={() => onChange("domain")}
/>
)}
@@ -122,30 +124,18 @@ function VisibilityItem({
icon,
label,
active,
- disabledReason,
onSelect,
}: {
icon: React.ReactNode;
label: string;
active: boolean;
- disabledReason?: string;
onSelect: () => void;
}) {
return (
- <DropdownMenuItem
- onClick={onSelect}
- disabled={!!disabledReason}
- className="text-xs gap-2 py-1.5"
- >
+ <DropdownMenuItem onClick={onSelect} className="text-xs gap-2 py-1.5">
{icon}
<span className="flex-1">{label}</span>
- {disabledReason ? (
- <span className="text-[10px] uppercase tracking-wide text-muted-foreground/70">
- {disabledReason}
- </span>
- ) : (
- active && <Check size={12} className="text-primary" />
- )}
+ {active && <Check size={12} className="text-primary" />}
</DropdownMenuItem>
);
}
diff --git a/src/components/notes/UploadAudioView.tsx b/src/components/notes/UploadAudioView.tsx
index 0511241fe..733aba9c7 100644
--- a/src/components/notes/UploadAudioView.tsx
+++ b/src/components/notes/UploadAudioView.tsx
@@ -39,6 +39,7 @@ import { getAllReasoningModels, getBatchTranscriptionModel } from "../../models/
import {
useSettingsStore,
selectIsCloudCleanupMode,
+ selectPolicyEffectiveSettings,
selectResolvedUploadTranscription,
getSettings,
} from "../../stores/settingsStore";
@@ -56,7 +57,8 @@ import { generateNoteTitle } from "../../utils/generateTitle";
import { getBaseLanguageCode } from "../../utils/languageSupport";
import { isTranscriptionContextAllowed } from "../../stores/policyRules";
import { usePolicyStore } from "../../stores/policyStore";
-import { useTranscriptionContextAllowed } from "../../hooks/usePolicy";
+import { usePolicySnapshot, useTranscriptionContextAllowed } from "../../hooks/usePolicy";
+import { resolveCustomTranscriptionRoute } from "../../helpers/retryTranscriptionRouting";
type UploadState = "idle" | "selected" | "downloading" | "transcribing" | "complete" | "error";
@@ -241,6 +243,7 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
tinfoilApiKey,
customTranscriptionApiKey,
} = useSettings();
+ const policyState = usePolicySnapshot();
const {
useLocalWhisper,
@@ -252,7 +255,11 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
cloudTranscriptionBaseUrl,
cloudTranscriptionMode,
transcriptionMode,
- } = useSettingsStore(useShallow(selectResolvedUploadTranscription));
+ } = useSettingsStore(
+ useShallow((settings) =>
+ selectResolvedUploadTranscription(selectPolicyEffectiveSettings(settings, policyState))
+ )
+ );
const uploadAllowedByPolicy = useTranscriptionContextAllowed("upload");
const remoteTranscriptionUrl = useSettingsStore((s) => s.remoteTranscriptionUrl);
@@ -269,10 +276,13 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
const cortiEnvironment = useSettingsStore((s) => s.cortiEnvironment);
const cortiTenant = useSettingsStore((s) => s.cortiTenant);
const preferredLanguage = useSettingsStore((s) => s.preferredLanguage);
- const isCloudCleanup = useSettingsStore(selectIsCloudCleanupMode);
- const effectiveCleanupModel = useSettingsStore((s) =>
- selectIsCloudCleanupMode(s) ? "" : s.cleanupModel
+ const isCloudCleanup = useSettingsStore((settings) =>
+ selectIsCloudCleanupMode(selectPolicyEffectiveSettings(settings, policyState))
);
+ const effectiveCleanupModel = useSettingsStore((settings) => {
+ const effectiveSettings = selectPolicyEffectiveSettings(settings, policyState);
+ return selectIsCloudCleanupMode(effectiveSettings) ? "" : effectiveSettings.cleanupModel;
+ });
const useCleanupModel = useSettingsStore((s) => s.useCleanupModel);
const isOpenWhisprCloud =
@@ -368,8 +378,11 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
if (isSelfHosted) {
if (!cancelled) setProviderReady(!!remoteTranscriptionUrl?.trim());
} else if (cloudTranscriptionProvider === "custom") {
- // Custom providers only need a base URL; API key is truly optional
- if (!cancelled) setProviderReady(!!cloudTranscriptionBaseUrl?.trim());
+ const customRoute = resolveCustomTranscriptionRoute({
+ provider: cloudTranscriptionProvider,
+ baseUrl: cloudTranscriptionBaseUrl,
+ });
+ if (!cancelled) setProviderReady(customRoute?.kind === "custom");
} else if (cloudTranscriptionProvider === "corti") {
if (!cancelled) setProviderReady(!!(cortiClientId && cortiClientSecret));
} else {
diff --git a/src/components/settings/InferenceConfigEditor.tsx b/src/components/settings/InferenceConfigEditor.tsx
index 4539d095d..ab897b221 100644
--- a/src/components/settings/InferenceConfigEditor.tsx
+++ b/src/components/settings/InferenceConfigEditor.tsx
@@ -4,10 +4,11 @@ import { useTranslation } from "react-i18next";
import { Cloud, Key, Cpu, Network, Building2 } from "lucide-react";
import {
useSettingsStore,
+ selectPolicyEffectiveSettings,
selectResolvedLLMConfig,
setResolvedLLMConfig,
} from "../../stores/settingsStore";
-import { usePolicyModeOptions } from "../../hooks/usePolicy";
+import { usePolicyModeOptions, usePolicySnapshot } from "../../hooks/usePolicy";
import { InferenceModeSelector } from "../ui/SettingsSection";
import type { InferenceModeOption } from "../ui/SettingsSection";
import ReasoningModelSelector from "../ReasoningModelSelector";
@@ -40,11 +41,16 @@ interface InferenceConfigEditorProps {
export default function InferenceConfigEditor({ scope, onModeChange }: InferenceConfigEditorProps) {
const { t } = useTranslation();
- const config = useSettingsStore(useShallow((s) => selectResolvedLLMConfig(s, scope)));
+ const policyState = usePolicySnapshot();
+ const config = useSettingsStore(
+ useShallow((settings) =>
+ selectResolvedLLMConfig(selectPolicyEffectiveSettings(settings, policyState), scope)
+ )
+ );
const isSignedIn = useSettingsStore((s) => s.isSignedIn);
const prefix = MODE_LABEL_PREFIX[scope];
- const { modes, isModeAllowed } = usePolicyModeOptions<InferenceModeOption>(
+ const { modes, effectiveMode, isModeAllowed } = usePolicyModeOptions<InferenceModeOption>(
[
{
id: "openwhispr",
@@ -79,7 +85,8 @@ export default function InferenceConfigEditor({ scope, onModeChange }: Inference
icon: <Building2 className="w-4 h-4" />,
},
],
- "llm"
+ "llm",
+ config.mode
);
const setField = useCallback(
@@ -97,7 +104,7 @@ export default function InferenceConfigEditor({ scope, onModeChange }: Inference
startCloudOnboarding();
return;
}
- if (mode === config.mode) return;
+ if (mode === effectiveMode) return;
const patch: Parameters<typeof setResolvedLLMConfig>[1] = {
mode,
@@ -115,7 +122,7 @@ export default function InferenceConfigEditor({ scope, onModeChange }: Inference
onModeChange?.(mode);
},
- [scope, config.mode, config.provider, isSignedIn, onModeChange, isModeAllowed]
+ [scope, config.provider, effectiveMode, isSignedIn, onModeChange, isModeAllowed]
);
const setMode = setField("mode");
@@ -138,21 +145,21 @@ export default function InferenceConfigEditor({ scope, onModeChange }: Inference
);
const showThinkingToggle =
- config.mode === "self-hosted" ||
- (config.mode === "providers" &&
+ effectiveMode === "self-hosted" ||
+ (effectiveMode === "providers" &&
(config.provider === "custom" ||
config.provider === "openrouter" ||
!!getCloudModel(config.model)?.supportsThinking)) ||
- (config.mode === "local" && !!getLocalModel(config.model)?.supportsThinking);
+ (effectiveMode === "local" && !!getLocalModel(config.model)?.supportsThinking);
return (
<div className="space-y-3">
- <InferenceModeSelector modes={modes} activeMode={config.mode} onSelect={handleModeSelect} />
+ <InferenceModeSelector modes={modes} activeMode={effectiveMode} onSelect={handleModeSelect} />
- {config.mode === "providers" && renderModelSelector("cloud")}
- {config.mode === "local" && renderModelSelector("local")}
+ {effectiveMode === "providers" && renderModelSelector("cloud")}
+ {effectiveMode === "local" && renderModelSelector("local")}
- {config.mode === "self-hosted" && (
+ {effectiveMode === "self-hosted" && (
<OpenAICompatiblePanel
baseUrl={config.remoteUrl ?? ""}
setBaseUrl={setField("remoteUrl")}
@@ -181,7 +188,7 @@ export default function InferenceConfigEditor({ scope, onModeChange }: Inference
</div>
)}
- {config.mode === "enterprise" && (
+ {effectiveMode === "enterprise" && (
<EnterpriseSection
currentProvider={config.provider}
reasoningModel={config.model}
diff --git a/src/components/settings/MeetingSettings.tsx b/src/components/settings/MeetingSettings.tsx
index a7a2a6a25..98445f12d 100644
--- a/src/components/settings/MeetingSettings.tsx
+++ b/src/components/settings/MeetingSettings.tsx
@@ -9,6 +9,11 @@ import { Toggle } from "../ui/toggle";
import TranscriptionModelPicker from "../TranscriptionModelPicker";
import type { InferenceMode } from "../../types/electron";
import { useStartOnboarding } from "../../hooks/useStartOnboarding";
+import { getStreamingTranscriptionProviders } from "../../models/ModelRegistry";
+
+const MEETING_BYOK_PROVIDER_IDS = getStreamingTranscriptionProviders().map(
+ (provider) => provider.id
+);
export function MeetingSpeakerDetectionRow() {
const { t } = useTranslation();
@@ -50,7 +55,11 @@ export function MeetingTranscriptionPanel() {
setMeetingCloudTranscriptionBaseUrl,
setMeetingCloudTranscriptionMode,
} = useSettingsStore();
- const { modes: transcriptionModes, isModeAllowed } = usePolicyModeOptions<InferenceModeOption>(
+ const {
+ modes: transcriptionModes,
+ effectiveMode: effectiveTranscriptionMode,
+ isModeAllowed,
+ } = usePolicyModeOptions<InferenceModeOption>(
[
{
id: "openwhispr",
@@ -81,9 +90,10 @@ export function MeetingTranscriptionPanel() {
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;
@@ -91,7 +101,7 @@ export function MeetingTranscriptionPanel() {
startOnboarding();
return;
}
- if (mode === meetingTranscriptionMode) return;
+ if (mode === effectiveTranscriptionMode) return;
setMeetingTranscriptionMode(mode);
setMeetingUseLocalWhisper(mode === "local");
setMeetingCloudTranscriptionMode(mode === "openwhispr" ? "openwhispr" : "byok");
@@ -134,12 +144,12 @@ export function MeetingTranscriptionPanel() {
<div className="space-y-3">
<InferenceModeSelector
modes={transcriptionModes}
- activeMode={meetingTranscriptionMode}
+ activeMode={effectiveTranscriptionMode}
onSelect={handleTranscriptionModeSelect}
/>
- {meetingTranscriptionMode === "providers" && renderTranscriptionPicker("cloud")}
- {meetingTranscriptionMode === "local" && renderTranscriptionPicker("local")}
+ {effectiveTranscriptionMode === "providers" && renderTranscriptionPicker("cloud")}
+ {effectiveTranscriptionMode === "local" && renderTranscriptionPicker("local")}
<MeetingSpeakerDetectionRow />
</div>
);
diff --git a/src/components/settings/UploadSettings.tsx b/src/components/settings/UploadSettings.tsx
index a1c2772ad..eccb53382 100644
--- a/src/components/settings/UploadSettings.tsx
+++ b/src/components/settings/UploadSettings.tsx
@@ -32,7 +32,11 @@ export function UploadTranscriptionPanel() {
setUploadCloudTranscriptionBaseUrl,
setUploadCloudTranscriptionMode,
} = useSettingsStore();
- const { modes: transcriptionModes, isModeAllowed } = usePolicyModeOptions<InferenceModeOption>(
+ const {
+ modes: transcriptionModes,
+ effectiveMode: effectiveTranscriptionMode,
+ isModeAllowed,
+ } = usePolicyModeOptions<InferenceModeOption>(
[
{
id: "openwhispr",
@@ -55,16 +59,16 @@ export function UploadTranscriptionPanel() {
icon: <Cpu className="w-4 h-4" />,
},
],
- "transcription"
+ "transcription",
+ uploadTranscriptionMode
);
-
const handleTranscriptionModeSelect = (mode: InferenceMode) => {
if (!isModeAllowed(mode)) return;
if (mode === "openwhispr" && !isSignedIn) {
startOnboarding();
return;
}
- if (mode === uploadTranscriptionMode) return;
+ if (mode === effectiveTranscriptionMode) return;
setUploadTranscriptionMode(mode);
setUploadUseLocalWhisper(mode === "local");
setUploadCloudTranscriptionMode(mode === "openwhispr" ? "openwhispr" : "byok");
@@ -106,12 +110,12 @@ export function UploadTranscriptionPanel() {
<div className="space-y-3">
<InferenceModeSelector
modes={transcriptionModes}
- activeMode={uploadTranscriptionMode}
+ activeMode={effectiveTranscriptionMode}
onSelect={handleTranscriptionModeSelect}
/>
- {uploadTranscriptionMode === "providers" && renderTranscriptionPicker("cloud")}
- {uploadTranscriptionMode === "local" && renderTranscriptionPicker("local")}
+ {effectiveTranscriptionMode === "providers" && renderTranscriptionPicker("cloud")}
+ {effectiveTranscriptionMode === "local" && renderTranscriptionPicker("local")}
</div>
);
}
diff --git a/src/components/ui/PromptStudio.tsx b/src/components/ui/PromptStudio.tsx
index be30e0c7d..4071099de 100644
--- a/src/components/ui/PromptStudio.tsx
+++ b/src/components/ui/PromptStudio.tsx
@@ -1,5 +1,6 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
+import { useShallow } from "zustand/react/shallow";
import { Button } from "./button";
import { Textarea } from "./textarea";
import {
@@ -22,10 +23,12 @@ import logger from "../../utils/logger";
import { getDefaultPromptText, resolvePrompt, type PromptKind } from "../../config/prompts";
import {
useSettingsStore,
+ selectPolicyEffectiveSettings,
selectIsCloudCleanupMode,
selectIsCloudDictationAgentMode,
selectIsCloudTranslationMode,
} from "../../stores/settingsStore";
+import { usePolicySnapshot } from "../../hooks/usePolicy";
import { getLanguageLabel } from "../../utils/languageSupport";
import { getDictionaryHintWords } from "../../utils/snippets";
import { resolveDictationAgentInference } from "../../helpers/dictationAgentInference";
@@ -74,25 +77,29 @@ export default function PromptStudio({ className = "", kind = "cleanup" }: Promp
const { alertDialog, showAlertDialog, hideAlertDialog } = useDialogs();
const { agentName } = useAgentName();
- const uiLanguage = useSettingsStore((s) => s.uiLanguage);
-
- const isCloudMode = useSettingsStore(selectIsCloudCleanupMode);
- const useCleanupModel = useSettingsStore((s) => s.useCleanupModel);
- const cleanupModel = useSettingsStore((s) => s.cleanupModel);
-
- const isCloudDictationAgent = useSettingsStore(selectIsCloudDictationAgentMode);
- const useDictationAgent = useSettingsStore((s) => s.useDictationAgent);
- const dictationAgentMode = useSettingsStore((s) => s.dictationAgentMode);
- const dictationAgentProvider = useSettingsStore((s) => s.dictationAgentProvider);
- const dictationAgentModel = useSettingsStore((s) => s.dictationAgentModel);
-
- const isCloudTranslation = useSettingsStore(selectIsCloudTranslationMode);
- const useDictationTranslation = useSettingsStore((s) => s.useDictationTranslation);
- const translationMode = useSettingsStore((s) => s.translationMode);
- const translationProvider = useSettingsStore((s) => s.translationProvider);
- const translationModel = useSettingsStore((s) => s.translationModel);
- const translationRemoteUrl = useSettingsStore((s) => s.translationRemoteUrl);
- const translationTargetLanguage = useSettingsStore((s) => s.translationTargetLanguage);
+ const policyState = usePolicySnapshot();
+ const effectiveSettings = useSettingsStore(
+ useShallow((settings) => selectPolicyEffectiveSettings(settings, policyState))
+ );
+ const uiLanguage = effectiveSettings.uiLanguage;
+
+ const isCloudMode = selectIsCloudCleanupMode(effectiveSettings);
+ const useCleanupModel = effectiveSettings.useCleanupModel;
+ const cleanupModel = effectiveSettings.cleanupModel;
+
+ const isCloudDictationAgent = selectIsCloudDictationAgentMode(effectiveSettings);
+ const useDictationAgent = effectiveSettings.useDictationAgent;
+ const dictationAgentMode = effectiveSettings.dictationAgentMode;
+ const dictationAgentProvider = effectiveSettings.dictationAgentProvider;
+ const dictationAgentModel = effectiveSettings.dictationAgentModel;
+
+ const isCloudTranslation = selectIsCloudTranslationMode(effectiveSettings);
+ const useDictationTranslation = effectiveSettings.useDictationTranslation;
+ const translationMode = effectiveSettings.translationMode;
+ const translationProvider = effectiveSettings.translationProvider;
+ const translationModel = effectiveSettings.translationModel;
+ const translationRemoteUrl = effectiveSettings.translationRemoteUrl;
+ const translationTargetLanguage = effectiveSettings.translationTargetLanguage;
const isTranslate = kind === "translate";
const isAgent = kind === "dictationAgent";
@@ -142,7 +149,7 @@ export default function PromptStudio({ className = "", kind = "cleanup" }: Promp
return;
}
- const translation = resolveDictationTranslationInference(useSettingsStore.getState(), {
+ const translation = resolveDictationTranslationInference(effectiveSettings, {
isCloudTranslation,
});
if (!translation.reachable) {
@@ -166,7 +173,7 @@ export default function PromptStudio({ className = "", kind = "cleanup" }: Promp
systemPrompt: resolvePrompt("translate", {
agentName,
targetLanguageLabel: getLanguageLabel(translationTargetLanguage),
- customDictionary: getDictionaryHintWords(useSettingsStore.getState()),
+ customDictionary: getDictionaryHintWords(effectiveSettings),
uiLanguage,
}),
}
@@ -186,7 +193,7 @@ export default function PromptStudio({ className = "", kind = "cleanup" }: Promp
return;
}
- const settings = useSettingsStore.getState();
+ const settings = effectiveSettings;
const agent = resolveDictationAgentInference(settings, {
isCloudAgent: isCloudDictationAgent,
});
@@ -251,7 +258,7 @@ export default function PromptStudio({ className = "", kind = "cleanup" }: Promp
};
if (providerConfig.baseStorageKey) {
- const baseUrl = (useSettingsStore.getState().cleanupCloudBaseUrl || "").trim();
+ const baseUrl = (effectiveSettings.cleanupCloudBaseUrl || "").trim();
if (!baseUrl) {
setTestResult(
t("promptStudio.test.baseUrlMissing", {
@@ -272,7 +279,7 @@ export default function PromptStudio({ className = "", kind = "cleanup" }: Promp
setCustomPrompt(kind, editedPrompt);
try {
const result = await ReasoningService.processText(testText, modelToUse, agentName, {
- disableThinking: useSettingsStore.getState().cleanupDisableThinking,
+ disableThinking: effectiveSettings.cleanupDisableThinking,
});
setTestResult(result);
} finally {
diff --git a/src/components/ui/SettingsSection.tsx b/src/components/ui/SettingsSection.tsx
index ac1c0e3b2..6eb89d472 100644
--- a/src/components/ui/SettingsSection.tsx
+++ b/src/components/ui/SettingsSection.tsx
@@ -144,7 +144,7 @@ export function InferenceModeSelector({
onSelect,
}: {
modes: InferenceModeOption[];
- activeMode: InferenceMode;
+ activeMode: InferenceMode | null;
onSelect: (mode: InferenceMode) => void;
}) {
const { t } = useTranslation();
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index 0bf0cede2..ad73e3745 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -3,7 +3,7 @@ import { API_ENDPOINTS, buildApiUrl, normalizeBaseUrl } from "../config/constant
import logger from "../utils/logger";
import { isBuiltInMicrophone } from "../utils/audioDeviceUtils";
import {
- isSecureEndpoint,
+ isSecureHttpEndpoint,
isAzureOpenAIEndpoint,
buildAzureTranscriptionUrl,
} from "../utils/urlUtils";
@@ -3272,15 +3272,30 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
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";
+ throw error;
+ };
// Never fall back to the cloud default for self-hosted — fail closed instead.
if (isSelfHosted) {
const normalizedRemote = normalizeBaseUrl(remoteUrl);
- if (!normalizedRemote || !isSecureEndpoint(normalizedRemote)) {
+ 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();
+ }
+
if (
this.cachedTranscriptionEndpoint &&
(this.cachedEndpointProvider !== currentProvider ||
@@ -3376,7 +3391,10 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
}
// Only validate HTTPS for custom endpoints (known providers are already HTTPS)
- if (isCustomEndpoint && !isSecureEndpoint(normalizedBase)) {
+ if (isCustomEndpoint && !isSecureHttpEndpoint(normalizedBase)) {
+ if (isManagedCustomEndpoint) {
+ rejectManagedCustomEndpoint();
+ }
logger.warn(
"STT endpoint: HTTPS required, falling back to default",
{ attemptedUrl: normalizedBase },
@@ -3429,7 +3447,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
{ error: error.message, stack: error.stack },
"transcription"
);
- if (isSelfHosted) throw error;
+ if (isSelfHosted || isManagedCustomEndpoint) throw error;
this.cachedTranscriptionEndpoint = API_ENDPOINTS.TRANSCRIPTION;
this.cachedEndpointProvider = currentProvider;
this.cachedEndpointBaseUrl = currentBaseUrl;
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 99e2004e1..0d453b6bb 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -4818,7 +4818,8 @@ class IPCHandlers {
preferredLanguage && preferredLanguage !== "auto"
? preferredLanguage.split("-")[0]
: undefined;
- const { resolveSelfHostedRetryRoute } = await import("./retryTranscriptionRouting.js");
+ const { resolveCustomTranscriptionRoute, resolveSelfHostedRetryRoute } =
+ await import("./retryTranscriptionRouting.js");
const selfHostedRoute = resolveSelfHostedRetryRoute(settings);
if (selfHostedRoute?.kind === "configuration-error") {
@@ -4939,12 +4940,16 @@ class IPCHandlers {
endpoint = MISTRAL_TRANSCRIPTION_URL;
} else if (provider === "custom") {
apiKey = this.environmentManager.getCustomTranscriptionKey();
- const base = (settings?.cloudTranscriptionBaseUrl || "").trim();
- endpoint = base
- ? /\/audio\/(transcriptions|translations)$/i.test(base)
- ? base
- : `${base}/audio/transcriptions`
- : "https://api.openai.com/v1/audio/transcriptions";
+ 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";
@@ -7925,7 +7930,8 @@ class IPCHandlers {
const realByok = resolveAllowedAudioPath(filePath);
if (!realByok) return { success: false, error: "File path not allowed" };
- const { resolveSelfHostedRetryRoute } = await import("./retryTranscriptionRouting.js");
+ const { resolveCustomTranscriptionRoute, resolveSelfHostedRetryRoute } =
+ await import("./retryTranscriptionRouting.js");
const selfHostedRoute = resolveSelfHostedRetryRoute({
transcriptionMode,
remoteTranscriptionUrl,
@@ -7996,6 +8002,10 @@ class IPCHandlers {
}
if (!apiKey) 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.");
}
@@ -8015,8 +8025,8 @@ class IPCHandlers {
multipartFields.format = "true";
}
} else {
- transcriptionUrl = baseUrl.replace(/\/+$/, "");
- if (!transcriptionUrl.endsWith("/audio/transcriptions")) {
+ transcriptionUrl = customRoute?.endpoint ?? baseUrl.replace(/\/+$/, "");
+ if (!customRoute && !transcriptionUrl.endsWith("/audio/transcriptions")) {
transcriptionUrl += "/audio/transcriptions";
}
multipartFields.model = model || "whisper-1";
diff --git a/src/helpers/retryTranscriptionRouting.js b/src/helpers/retryTranscriptionRouting.js
index 8d889b546..5de56817d 100644
--- a/src/helpers/retryTranscriptionRouting.js
+++ b/src/helpers/retryTranscriptionRouting.js
@@ -1,5 +1,5 @@
import { buildApiUrl, normalizeBaseUrl } from "../config/constants.ts";
-import { isSecureEndpoint } from "../utils/urlUtils.ts";
+import { isSecureHttpEndpoint } from "../utils/urlUtils.ts";
import { resolveSelfHostedTranscriptionModel } from "./selfHostedTranscription.js";
export function resolveSelfHostedRetryRoute(settings) {
@@ -20,13 +20,7 @@ export function resolveSelfHostedRetryRoute(settings) {
const remoteUrl = configuredUrl.replace(/\/+$/, "");
const normalizedBaseUrl = normalizeBaseUrl(remoteUrl);
- let hasSupportedProtocol = false;
- try {
- const protocol = new URL(normalizedBaseUrl).protocol;
- hasSupportedProtocol = protocol === "http:" || protocol === "https:";
- } catch {}
-
- if (!normalizedBaseUrl || !hasSupportedProtocol || !isSecureEndpoint(normalizedBaseUrl)) {
+ if (!normalizedBaseUrl || !isSecureHttpEndpoint(normalizedBaseUrl)) {
return {
kind: "configuration-error",
error: "Self-hosted transcription URL is invalid or unsupported",
@@ -39,3 +33,22 @@ export function resolveSelfHostedRetryRoute(settings) {
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/hooks/usePolicy.ts b/src/hooks/usePolicy.ts
index e71b849f7..d70020836 100644
--- a/src/hooks/usePolicy.ts
+++ b/src/hooks/usePolicy.ts
@@ -1,13 +1,13 @@
import { useMemo } from "react";
-import { useTranslation } from "react-i18next";
import { useShallow } from "zustand/react/shallow";
import { usePolicyStore } from "../stores/policyStore";
-import { useSettingsStore } from "../stores/settingsStore";
+import { selectPolicyEffectiveSettings, useSettingsStore } from "../stores/settingsStore";
import {
- enforceModeOptions,
+ filterModeOptionsByPolicy,
getTranscriptionSelection,
isModeAllowedByPolicy,
isTranscriptionSelectionAllowed,
+ reconcilePolicyModeSelection,
type PolicyDecisionSnapshot,
type TranscriptionPolicyContext,
} from "../stores/policyRules";
@@ -25,28 +25,44 @@ export function usePolicySnapshot(): PolicyDecisionSnapshot {
/** Reactive to both stores — updates when the policy or the relevant settings change. */
export function useTranscriptionContextAllowed(context: TranscriptionPolicyContext): boolean {
const snapshot = usePolicySnapshot();
- const selection = useSettingsStore(useShallow((s) => getTranscriptionSelection(s, context)));
+ const selection = useSettingsStore(
+ useShallow((settings) =>
+ getTranscriptionSelection(selectPolicyEffectiveSettings(settings, snapshot), context)
+ )
+ );
return isTranscriptionSelectionAllowed(snapshot, selection);
}
interface PolicyModeOptions<T> {
modes: T[];
+ effectiveMode: InferenceMode | null;
/**
- * "Disabled" mode options still fire onSelect (the sign-in gate relies on
- * that to start onboarding), so call this at the top of the select handler —
- * policy must be enforced there, not in the UI.
+ * Selection handlers still enforce policy in case a stale renderer event
+ * arrives after an option disappears.
*/
isModeAllowed: (mode: InferenceMode) => boolean;
}
-/** Mode options with policy-disallowed entries disabled and badged. */
-export function usePolicyModeOptions<
- T extends { id: InferenceMode; disabled?: boolean; badge?: string },
->(options: T[], scope: PolicyScope): PolicyModeOptions<T> {
- const { t } = useTranslation();
+/** Visible mode options and a deterministic replacement for a denied managed selection. */
+export function usePolicyModeOptions<T extends { id: InferenceMode; disabled?: boolean }>(
+ options: T[],
+ scope: PolicyScope,
+ selectedMode: InferenceMode,
+ providerCatalog?: {
+ byokProviders: readonly string[];
+ enterpriseProviders?: readonly string[];
+ }
+): PolicyModeOptions<T> {
const snapshot = usePolicySnapshot();
+ const modes = filterModeOptionsByPolicy(options, scope, snapshot, providerCatalog);
+ const selectionIsVisible = modes.some((option) => option.id === selectedMode && !option.disabled);
+ const preservesRawSelection = snapshot.status === "idle" || snapshot.status === "unmanaged";
return {
- modes: enforceModeOptions(options, scope, snapshot, t("common.managedByOrg")),
+ modes,
+ effectiveMode:
+ preservesRawSelection || selectionIsVisible
+ ? selectedMode
+ : reconcilePolicyModeSelection(options, scope, snapshot, selectedMode, providerCatalog),
isModeAllowed: (mode: InferenceMode) => isModeAllowedByPolicy(snapshot, scope, mode),
};
}
diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.ts
index 8f1124516..63213ea36 100644
--- a/src/services/ReasoningService.ts
+++ b/src/services/ReasoningService.ts
@@ -18,7 +18,7 @@ import { streamText, stepCountIs } from "ai";
import { getAIModel } from "./ai/providers";
import { createEnterpriseChatModel } from "./ai/enterpriseChatModel";
import { PROVIDER_REGISTRY, type ProviderContext } from "./ai/inferenceProviders";
-import { getConfiguredOpenAIBase } from "./ai/openaiBase";
+import { resolveConfiguredOpenAIBase, resolveSelfHostedOpenAIBase } from "./ai/openaiBase";
import { applyThinkingSuppression } from "./ai/thinkingSuppression";
import { detectEndpointDialect } from "./ai/thinkingSuppressionDialects";
import { extractApiErrorMessage } from "./ai/apiErrorMessage";
@@ -364,12 +364,26 @@ class ReasoningService extends BaseReasoningService {
config: ReasoningConfig = {}
): Promise<string> {
const trimmedModel = model?.trim?.() || "";
- const isLanCleanup = !!config.lanUrl || this.isLanCleanupMode();
+ const settings = getSettings();
+ const isImplicitCustomCleanup =
+ config.provider === undefined &&
+ config.baseUrl === undefined &&
+ settings.cleanupMode === "providers" &&
+ settings.cleanupProvider === "custom";
+ const dispatchConfig: ReasoningConfig = isImplicitCustomCleanup
+ ? {
+ ...config,
+ provider: "custom",
+ baseUrl: settings.cleanupCloudBaseUrl,
+ customApiKey: config.customApiKey ?? settings.cleanupCustomApiKey,
+ }
+ : config;
+ const isLanCleanup = !!dispatchConfig.lanUrl || this.isLanCleanupMode();
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");
@@ -394,7 +408,7 @@ class ReasoningService extends BaseReasoningService {
text,
model: trimmedModel,
agentName,
- config,
+ config: dispatchConfig,
ctx: this.providerContext,
});
@@ -437,7 +451,7 @@ class ReasoningService extends BaseReasoningService {
let apiKey = "";
if (isLanChat) {
- const baseUrl = ensureV1Suffix(route.baseUrl);
+ const baseUrl = resolveSelfHostedOpenAIBase(route.baseUrl);
endpoint = buildApiUrl(baseUrl, "/chat/completions");
apiKey = route.apiKey;
} else if (isLocalProvider) {
@@ -468,9 +482,11 @@ class ReasoningService extends BaseReasoningService {
case "tinfoil":
throw new Error("Tinfoil streaming must use the verified SDK transport");
case "openai":
+ endpoint = buildApiUrl(API_ENDPOINTS.OPENAI_BASE, "/chat/completions");
+ break;
case "custom":
endpoint = buildApiUrl(
- config.baseUrl?.trim() || getConfiguredOpenAIBase(),
+ resolveConfiguredOpenAIBase(providerKey, config.baseUrl),
"/chat/completions"
);
break;
@@ -669,7 +685,7 @@ class ReasoningService extends BaseReasoningService {
// doStream over IPC, so no key or base URL is resolved here.
} else if (isLanChat) {
apiKey = route.apiKey;
- baseURL = ensureV1Suffix(route.baseUrl);
+ baseURL = resolveSelfHostedOpenAIBase(route.baseUrl);
} else if (isLocalProvider) {
const serverResult = await window.electronAPI.llamaServerStart(model);
if (!serverResult.success || !serverResult.port) {
@@ -685,7 +701,7 @@ class ReasoningService extends BaseReasoningService {
provider === "openrouter"
? API_ENDPOINTS.OPENROUTER_BASE
: provider === "custom"
- ? config.baseUrl?.trim() || getConfiguredOpenAIBase()
+ ? resolveConfiguredOpenAIBase(provider, config.baseUrl)
: undefined;
}
const aiProvider = isLocalProvider || isLanChat ? "local" : provider;
diff --git a/src/services/ai/inferenceProviders/lan.ts b/src/services/ai/inferenceProviders/lan.ts
index 85b5ee94f..a21610650 100644
--- a/src/services/ai/inferenceProviders/lan.ts
+++ b/src/services/ai/inferenceProviders/lan.ts
@@ -1,7 +1,8 @@
import type { InferenceProvider } from "./types";
-import { buildApiUrl, ensureV1Suffix } from "../../../config/constants";
+import { buildApiUrl } from "../../../config/constants";
import { getSettings } from "../../../stores/settingsStore";
import logger from "../../../utils/logger";
+import { resolveSelfHostedOpenAIBase } from "../openaiBase";
export const lanProvider: InferenceProvider = {
id: "lan",
@@ -12,7 +13,7 @@ export const lanProvider: InferenceProvider = {
logger.logReasoning("LAN_START", { url: lanUrl, agentName, model });
try {
- const baseUrl = ensureV1Suffix(lanUrl);
+ const baseUrl = resolveSelfHostedOpenAIBase(lanUrl);
const endpoint = buildApiUrl(baseUrl, "/chat/completions");
const apiKey =
config.customApiKey?.trim() ||
diff --git a/src/services/ai/inferenceProviders/openai.ts b/src/services/ai/inferenceProviders/openai.ts
index 76f515644..ae2ac91b7 100644
--- a/src/services/ai/inferenceProviders/openai.ts
+++ b/src/services/ai/inferenceProviders/openai.ts
@@ -4,7 +4,7 @@ import { getOpenAiApiConfig } from "../../../models/ModelRegistry";
import { getSettings } from "../../../stores/settingsStore";
import { withRetry, createApiRetryStrategy, httpError } from "../../../utils/retry";
import logger from "../../../utils/logger";
-import { getConfiguredOpenAIBase } from "../openaiBase";
+import { resolveConfiguredOpenAIBase } from "../openaiBase";
import { applyThinkingSuppression } from "../thinkingSuppression";
import { detectEndpointDialect } from "../thinkingSuppressionDialects";
import { extractApiErrorMessage } from "../apiErrorMessage";
@@ -153,7 +153,7 @@ export const openaiProvider: InferenceProvider = {
const openAiBase = isOpenRouter
? API_ENDPOINTS.OPENROUTER_BASE
- : config.baseUrl?.trim() || getConfiguredOpenAIBase();
+ : resolveConfiguredOpenAIBase(resolvedProvider, config.baseUrl);
const dialect = detectEndpointDialect(openAiBase);
// OpenRouter and known dialect hosts speak Chat Completions only — no /responses probe needed.
let endpointCandidates: Array<{ url: string; type: "responses" | "chat" }>;
diff --git a/src/services/ai/openaiBase.ts b/src/services/ai/openaiBase.ts
index da3c7aa1b..b3ae81b8f 100644
--- a/src/services/ai/openaiBase.ts
+++ b/src/services/ai/openaiBase.ts
@@ -1,86 +1,68 @@
import { API_ENDPOINTS, ensureV1Suffix } from "../../config/constants";
-import { getSettings } from "../../stores/settingsStore";
-import { isSecureEndpoint } from "../../utils/urlUtils";
+import { usePolicyStore } from "../../stores/policyStore";
+import { isSecureHttpEndpoint } from "../../utils/urlUtils";
import logger from "../../utils/logger";
+import i18n from "../../i18n";
-export function getConfiguredOpenAIBase(): string {
- if (typeof window === "undefined") {
- return API_ENDPOINTS.OPENAI_BASE;
+function invalidCustomEndpoint(reason: string, attempted?: string): string {
+ const policyStatus = usePolicyStore.getState().status;
+ if (policyStatus !== "idle" && policyStatus !== "unmanaged") {
+ throw Object.assign(new Error(i18n.t("common.policyAiProcessingRestricted")), {
+ code: "POLICY_RESTRICTED",
+ });
}
- try {
- const settings = getSettings();
- const provider = settings.cleanupProvider || "";
- const isCustomProvider = provider === "custom";
-
- if (!isCustomProvider) {
- logger.logReasoning("CUSTOM_CLEANUP_ENDPOINT_CHECK", {
- hasCustomUrl: false,
- provider,
- reason: "Provider is not 'custom', using default OpenAI endpoint",
- defaultEndpoint: API_ENDPOINTS.OPENAI_BASE,
- });
- return API_ENDPOINTS.OPENAI_BASE;
- }
-
- const stored = settings.cleanupCloudBaseUrl || "";
- const trimmed = stored.trim();
+ logger.logReasoning("OPENAI_BASE_REJECTED", {
+ reason,
+ attempted,
+ fallbackTo: API_ENDPOINTS.OPENAI_BASE,
+ });
+ return API_ENDPOINTS.OPENAI_BASE;
+}
- if (!trimmed) {
- logger.logReasoning("CUSTOM_CLEANUP_ENDPOINT_CHECK", {
- hasCustomUrl: false,
- provider,
- usingDefault: true,
- defaultEndpoint: API_ENDPOINTS.OPENAI_BASE,
- });
- return API_ENDPOINTS.OPENAI_BASE;
- }
+export function resolveConfiguredOpenAIBase(provider: string, configuredBaseUrl?: string): string {
+ if (provider !== "custom") return API_ENDPOINTS.OPENAI_BASE;
- const normalized = ensureV1Suffix(trimmed) || API_ENDPOINTS.OPENAI_BASE;
+ const trimmed = configuredBaseUrl?.trim() ?? "";
+ if (!trimmed) {
+ return invalidCustomEndpoint("Custom endpoint is not configured");
+ }
- logger.logReasoning("CUSTOM_CLEANUP_ENDPOINT_CHECK", {
- hasCustomUrl: true,
- provider,
- rawUrl: trimmed,
- normalizedUrl: normalized,
- defaultEndpoint: API_ENDPOINTS.OPENAI_BASE,
- });
+ const normalized = ensureV1Suffix(trimmed);
+ if (!normalized) {
+ return invalidCustomEndpoint("Custom endpoint could not be normalized", trimmed);
+ }
- const knownNonOpenAIUrls = [
- "api.groq.com",
- "api.anthropic.com",
- "generativelanguage.googleapis.com",
- ];
+ const knownNonOpenAIUrls = [
+ "api.groq.com",
+ "api.anthropic.com",
+ "generativelanguage.googleapis.com",
+ ];
+ if (knownNonOpenAIUrls.some((url) => normalized.includes(url))) {
+ return invalidCustomEndpoint("Custom URL is a known non-OpenAI provider", normalized);
+ }
- const isKnownNonOpenAI = knownNonOpenAIUrls.some((url) => normalized.includes(url));
- if (isKnownNonOpenAI) {
- logger.logReasoning("OPENAI_BASE_REJECTED", {
- reason: "Custom URL is a known non-OpenAI provider, using default OpenAI endpoint",
- attempted: normalized,
- });
- return API_ENDPOINTS.OPENAI_BASE;
- }
+ if (!isSecureHttpEndpoint(normalized)) {
+ return invalidCustomEndpoint(
+ "HTTPS required (HTTP allowed for local network only)",
+ normalized
+ );
+ }
- if (!isSecureEndpoint(normalized)) {
- logger.logReasoning("OPENAI_BASE_REJECTED", {
- reason: "HTTPS required (HTTP allowed for local network only)",
- attempted: normalized,
- });
- return API_ENDPOINTS.OPENAI_BASE;
- }
+ logger.logReasoning("CUSTOM_CLEANUP_ENDPOINT_RESOLVED", {
+ customEndpoint: normalized,
+ isCustom: true,
+ provider,
+ });
- logger.logReasoning("CUSTOM_CLEANUP_ENDPOINT_RESOLVED", {
- customEndpoint: normalized,
- isCustom: true,
- provider,
- });
+ return normalized;
+}
- return normalized;
- } catch (error) {
- logger.logReasoning("CUSTOM_CLEANUP_ENDPOINT_ERROR", {
- error: (error as Error).message,
- fallbackTo: API_ENDPOINTS.OPENAI_BASE,
- });
- return API_ENDPOINTS.OPENAI_BASE;
+export function resolveSelfHostedOpenAIBase(configuredBaseUrl: string): string {
+ const normalized = ensureV1Suffix(configuredBaseUrl.trim());
+ if (!normalized || !isSecureHttpEndpoint(normalized)) {
+ throw new Error(i18n.t("reasoning.custom.httpsRequired"));
}
+
+ return normalized;
}
diff --git a/src/services/fileTranscription.ts b/src/services/fileTranscription.ts
index 7e6e66d84..275663e10 100644
--- a/src/services/fileTranscription.ts
+++ b/src/services/fileTranscription.ts
@@ -1,4 +1,5 @@
import { withSessionRefresh } from "../lib/auth";
+import { resolveCustomTranscriptionRoute } from "../helpers/retryTranscriptionRouting.js";
export interface FileTranscriptionResult {
success: boolean;
@@ -61,12 +62,24 @@ 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",
+ };
+ }
+
// Self-hosted fields make the handler route to the configured server
// (fail-closed on misconfiguration) instead of stale BYOK settings.
return window.electronAPI.transcribeAudioFileByok!({
filePath,
apiKey: cfg.getApiKey(),
- baseUrl: cfg.cloudTranscriptionBaseUrl || "",
+ baseUrl: customRoute?.baseUrl ?? cfg.cloudTranscriptionBaseUrl ?? "",
model: cfg.cloudTranscriptionModel,
diarize: diarize || undefined,
provider: cfg.cloudTranscriptionProvider,
diff --git a/src/stores/policyRules.ts b/src/stores/policyRules.ts
index 6a53e69fb..11a2f3c9f 100644
--- a/src/stores/policyRules.ts
+++ b/src/stores/policyRules.ts
@@ -130,6 +130,65 @@ export interface LlmSelection {
provider: 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 (!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
@@ -203,6 +262,26 @@ export function isShareVisibilityAllowed(
});
}
+/** Hide policy-denied sharing choices while always retaining private recovery. */
+export function filterShareVisibilityOptions<T extends { id: ShareVisibility }>(
+ options: T[],
+ state: PolicyDecisionSnapshot
+): T[] {
+ return options.filter((option) => isShareVisibilityAllowed(state, option.id));
+}
+
+/** Whether this surface can offer at least one exposure-increasing share mode. */
+export function hasUsableExternalShareVisibility(
+ state: PolicyDecisionSnapshot,
+ canOfferDomainVisibility: boolean
+): boolean {
+ return (
+ isShareVisibilityAllowed(state, "link") ||
+ isShareVisibilityAllowed(state, "invited") ||
+ (canOfferDomainVisibility && isShareVisibilityAllowed(state, "domain"))
+ );
+}
+
export type SharePolicyAction =
| "create-link"
| "copy-link"
@@ -251,18 +330,98 @@ export function isControlPanelViewAllowed(
return true;
}
-/** Mark policy-disallowed mode options disabled with a "managed" badge. */
-export function enforceModeOptions<
- T extends { id: InferenceMode; disabled?: boolean; badge?: string },
->(options: T[], scope: PolicyScope, state: PolicyDecisionSnapshot, managedBadge: string): T[] {
+function policyModeHasAvailableProvider(
+ policy: OrgPolicy,
+ scope: PolicyScope,
+ mode: InferenceMode,
+ providerCatalog?: Pick<PolicySelectionCatalog, "byokProviders" | "enterpriseProviders">
+): boolean {
+ if (mode === "providers") {
+ return providerCatalog
+ ? providerCatalog.byokProviders.some((provider) =>
+ policy[scope].allowedByokProviders.includes(provider)
+ )
+ : policy[scope].allowedByokProviders.length > 0;
+ }
+ if (mode === "enterprise") {
+ const selectableProviders = providerCatalog?.enterpriseProviders ?? ["bedrock"];
+ return (
+ scope === "llm" &&
+ selectableProviders.some((provider) =>
+ policy.llm.allowedEnterpriseProviders.includes(provider)
+ )
+ );
+ }
+ return true;
+}
+
+/** Hide policy-denied modes while preserving the complete unmanaged catalog. */
+export function filterModeOptionsByPolicy<T extends { id: InferenceMode }>(
+ options: T[],
+ scope: PolicyScope,
+ state: PolicyDecisionSnapshot,
+ providerCatalog?: Pick<PolicySelectionCatalog, "byokProviders" | "enterpriseProviders">
+): T[] {
if (state.status === "idle" || state.status === "unmanaged") return options;
- return options.map((option) =>
- isModeAllowedByPolicy(state, scope, option.id)
- ? option
- : { ...option, disabled: true, badge: managedBadge }
+ if (state.status !== "managed" || !state.policy) return [];
+ return options.filter(
+ (option) =>
+ isModeAllowedByPolicy(state, scope, option.id) &&
+ policyModeHasAvailableProvider(state.policy, scope, option.id, providerCatalog)
);
}
+/** 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. */
+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 }>;
@@ -291,6 +450,8 @@ export function reconcileCloudProviderSelection({
return { provider: "custom", model: selectedModel || "whisper-1" };
}
const first = allowedProviders[0];
- if (!first) return null;
+ if (!first) {
+ return customAllowed ? { provider: "custom", model: selectedModel || "whisper-1" } : null;
+ }
return { provider: first.id, model: first.models?.[0]?.id ?? "" };
}
diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.ts
index 878057ebc..ef8e51bbc 100644
--- a/src/stores/settingsStore.ts
+++ b/src/stores/settingsStore.ts
@@ -26,6 +26,15 @@ import {
type InferenceScopeStoreKeys,
} from "../config/inferenceScopes";
import { normalizeChineseScriptPreference } from "../utils/chineseScript";
+import { adjustBedrockModelForRegion } from "../utils/bedrockRegions";
+import modelRegistryData from "../models/modelRegistryData.json";
+import {
+ getTranscriptionSelection,
+ resolveEffectivePolicySelection,
+ type PolicyDecisionSnapshot,
+ type TranscriptionPolicyContext,
+} from "./policyRules";
+import { usePolicyStore } from "./policyStore";
import type {
TranscriptionSettings,
CleanupSettings,
@@ -43,6 +52,83 @@ let _ReasoningService: typeof import("../services/ReasoningService").default | n
const isBrowser = typeof window !== "undefined";
+const TRANSCRIPTION_POLICY_CATALOG = {
+ modes: ["openwhispr", "providers", "local", "self-hosted"] as const,
+ byokProviders: [
+ ...modelRegistryData.transcriptionProviders.map((provider) => provider.id),
+ "custom",
+ ],
+};
+
+const MEETING_TRANSCRIPTION_POLICY_CATALOG = {
+ ...TRANSCRIPTION_POLICY_CATALOG,
+ 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"],
+};
+
+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;
@@ -2179,13 +2265,164 @@ export function setResolvedLLMConfig(
}
export function isCloudChatAgentMode() {
- return selectIsCloudChatAgentMode(useSettingsStore.getState());
+ return selectIsCloudChatAgentMode(getSettings());
}
// --- Convenience getters for non-React code ---
-export function getSettings() {
- return useSettingsStore.getState();
+interface TranscriptionContextKeys {
+ context: TranscriptionPolicyContext;
+ mode: keyof SettingsState;
+ useLocal: keyof SettingsState;
+ cloudMode: keyof SettingsState;
+ provider: keyof SettingsState;
+ model: keyof SettingsState;
+ baseUrl: keyof SettingsState;
+}
+
+const TRANSCRIPTION_CONTEXT_KEYS: readonly TranscriptionContextKeys[] = [
+ {
+ context: "dictation",
+ mode: "transcriptionMode",
+ useLocal: "useLocalWhisper",
+ cloudMode: "cloudTranscriptionMode",
+ provider: "cloudTranscriptionProvider",
+ model: "cloudTranscriptionModel",
+ baseUrl: "cloudTranscriptionBaseUrl",
+ },
+ {
+ context: "meeting",
+ mode: "meetingTranscriptionMode",
+ useLocal: "meetingUseLocalWhisper",
+ cloudMode: "meetingCloudTranscriptionMode",
+ provider: "meetingCloudTranscriptionProvider",
+ model: "meetingCloudTranscriptionModel",
+ baseUrl: "meetingCloudTranscriptionBaseUrl",
+ },
+ {
+ context: "upload",
+ mode: "uploadTranscriptionMode",
+ useLocal: "uploadUseLocalWhisper",
+ cloudMode: "uploadCloudTranscriptionMode",
+ provider: "uploadCloudTranscriptionProvider",
+ model: "uploadCloudTranscriptionModel",
+ baseUrl: "uploadCloudTranscriptionBaseUrl",
+ },
+];
+
+/**
+ * Overlay managed policy choices for rendering and future requests while
+ * leaving Zustand/localStorage preferences untouched for policy removal.
+ */
+export function selectPolicyEffectiveSettings(
+ state: SettingsState,
+ policyState: PolicyDecisionSnapshot
+): SettingsState {
+ if (policyState.status === "idle" || policyState.status === "unmanaged") return state;
+ if (policyState.status !== "managed" || !policyState.policy) return state;
+
+ const effective = { ...state };
+ const writable = effective as unknown as Record<string, unknown>;
+
+ for (const keys of TRANSCRIPTION_CONTEXT_KEYS) {
+ const rawSelection = getTranscriptionSelection(state, keys.context);
+ const selection = resolveEffectivePolicySelection(
+ policyState,
+ "transcription",
+ rawSelection,
+ keys.context === "meeting"
+ ? MEETING_TRANSCRIPTION_POLICY_CATALOG
+ : TRANSCRIPTION_POLICY_CATALOG
+ );
+ if (!selection) continue;
+
+ writable[keys.mode] = selection.mode;
+ writable[keys.useLocal] = selection.mode === "local";
+ writable[keys.cloudMode] = selection.mode === "openwhispr" ? "openwhispr" : "byok";
+ if (selection.mode === "providers") {
+ const providerChanged = selection.provider !== rawSelection.provider;
+ writable[keys.provider] = selection.provider;
+ if (
+ providerChanged ||
+ !transcriptionModelBelongsToProvider(
+ selection.provider,
+ state[keys.model] as string,
+ keys.context
+ )
+ ) {
+ writable[keys.model] = defaultTranscriptionModel(selection.provider, keys.context);
+ }
+
+ const canonicalBaseUrl = canonicalTranscriptionBaseUrl(selection.provider);
+ if (canonicalBaseUrl) {
+ writable[keys.baseUrl] = canonicalBaseUrl;
+ } else if (providerChanged) {
+ // A fallback to Custom must not reinterpret another provider's endpoint
+ // as user authorization to send content there.
+ writable[keys.baseUrl] = "";
+ }
+ }
+ }
+
+ const resolvedConfigs = Object.fromEntries(
+ (Object.keys(INFERENCE_SCOPES) as InferenceScope[]).map((scope) => [
+ scope,
+ selectResolvedLLMConfig(state, scope),
+ ])
+ ) as Record<InferenceScope, ResolvedLLMConfig>;
+
+ for (const scope of Object.keys(INFERENCE_SCOPES) as InferenceScope[]) {
+ const definition = INFERENCE_SCOPES[scope];
+ const config = resolvedConfigs[scope];
+ const selection = resolveEffectivePolicySelection(
+ policyState,
+ "llm",
+ { mode: config.mode, provider: config.provider },
+ LLM_POLICY_CATALOG
+ );
+ if (!selection) continue;
+
+ writable[definition.storeKeys.mode] = selection.mode;
+ if (definition.storeKeys.cloudMode) {
+ writable[definition.storeKeys.cloudMode] =
+ selection.mode === "openwhispr" ? "openwhispr" : "byok";
+ }
+
+ let provider = selection.provider;
+ if (selection.mode === "openwhispr") provider = "openwhispr";
+ if (selection.mode === "self-hosted") provider = "lan";
+ if (selection.mode === "local" && !localLlmProviderIds.has(provider)) {
+ provider = modelRegistryData.localProviders[0]?.id ?? "";
+ }
+ writable[definition.storeKeys.provider] = provider;
+
+ if (
+ definition.storeKeys.cloudBaseUrl &&
+ selection.mode === "providers" &&
+ provider === "custom" &&
+ config.provider !== "custom"
+ ) {
+ writable[definition.storeKeys.cloudBaseUrl] = "";
+ }
+
+ if (
+ selection.mode === "providers" ||
+ selection.mode === "enterprise" ||
+ selection.mode === "local"
+ ) {
+ const providerChanged = selection.mode !== config.mode || provider !== config.provider;
+ writable[definition.storeKeys.model] =
+ !providerChanged && config.model
+ ? config.model
+ : defaultLlmModel(selection.mode, provider, state.bedrockRegion);
+ }
+ }
+
+ return effective;
+}
+
+export function getSettings(): SettingsState {
+ return selectPolicyEffectiveSettings(useSettingsStore.getState(), usePolicyStore.getState());
}
/**
@@ -2215,7 +2452,7 @@ export async function reconcileLocalModelSelections(): Promise<void> {
}
export function getEffectiveCleanupModel() {
- const state = useSettingsStore.getState();
+ const state = getSettings();
if (selectIsCloudCleanupMode(state)) {
return "";
}
@@ -2223,15 +2460,15 @@ export function getEffectiveCleanupModel() {
}
export function isCloudCleanupMode() {
- return selectIsCloudCleanupMode(useSettingsStore.getState());
+ return selectIsCloudCleanupMode(getSettings());
}
export function isCloudDictationAgentMode() {
- return selectIsCloudDictationAgentMode(useSettingsStore.getState());
+ return selectIsCloudDictationAgentMode(getSettings());
}
export function isCloudTranslationMode() {
- return selectIsCloudTranslationMode(useSettingsStore.getState());
+ return selectIsCloudTranslationMode(getSettings());
}
// --- Initialization ---
diff --git a/src/utils/urlUtils.ts b/src/utils/urlUtils.ts
index 599c9155b..ffbed3dcf 100644
--- a/src/utils/urlUtils.ts
+++ b/src/utils/urlUtils.ts
@@ -51,6 +51,18 @@ export function isSecureEndpoint(url: string): boolean {
}
}
+export function isSecureHttpEndpoint(url: string): boolean {
+ try {
+ const parsed = new URL(url);
+ return (
+ parsed.protocol === "https:" ||
+ (parsed.protocol === "http:" && isPrivateHost(parsed.hostname))
+ );
+ } catch {
+ return false;
+ }
+}
+
const AZURE_HOST_SUFFIXES = [
".openai.azure.com",
".cognitiveservices.azure.com",
diff --git a/test/helpers/audioManagerCloudFallbackPolicy.test.js b/test/helpers/audioManagerCloudFallbackPolicy.test.js
index d852f536e..21485a87b 100644
--- a/test/helpers/audioManagerCloudFallbackPolicy.test.js
+++ b/test/helpers/audioManagerCloudFallbackPolicy.test.js
@@ -114,3 +114,79 @@ test("cloud->local fallback under org policy", async (t) => {
assert.equal(localWhisperCalls, 1);
});
});
+
+test("managed custom transcription never falls through to OpenAI", async (t) => {
+ installBrowserGlobals(t);
+ const vite = await createRendererServer(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;",
+ },
+ });
+
+ 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;
+ });
+
+ usePolicyStore.setState({
+ accountId: "org-user",
+ authGeneration: 1,
+ revision: 1,
+ status: "managed",
+ managed: true,
+ policy: {
+ ...buildManagedPolicy(["providers"]),
+ transcription: {
+ allowedModes: ["providers"],
+ allowedByokProviders: ["custom"],
+ },
+ },
+ 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 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 = {
+ allowLocalFallback: false,
+ cloudTranscriptionBaseUrl: baseUrl,
+ cloudTranscriptionProvider: "custom",
+ transcriptionMode: "providers",
+ useLocalWhisper: false,
+ };
+
+ await assert.rejects(manager.processWithOpenAIAPI(audioBlob), (error) => {
+ assert.equal(error.code, "POLICY_RESTRICTED");
+ assert.equal(error.messageKey, "common.policyTranscriptionRestricted");
+ return true;
+ });
+ }
+
+ assert.equal(fetchCalls, 0);
+});
diff --git a/test/helpers/policyEffectiveSettings.test.js b/test/helpers/policyEffectiveSettings.test.js
new file mode 100644
index 000000000..b2ccf6dd2
--- /dev/null
+++ b/test/helpers/policyEffectiveSettings.test.js
@@ -0,0 +1,201 @@
+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);
+});
diff --git a/test/helpers/policyRules.test.js b/test/helpers/policyRules.test.js
index c2b940a85..ff9225bc7 100644
--- a/test/helpers/policyRules.test.js
+++ b/test/helpers/policyRules.test.js
@@ -95,6 +95,217 @@ test("mode and provider decisions fail closed for empty allowlists", async () =>
assert.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("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" }
+ );
+});
+
test("empty managed scope allowlists make that scope unavailable", async () => {
const { isLlmSelectionAllowed } = await load();
const emptyLlmPolicy = {
@@ -193,6 +404,69 @@ test("domain-only sharing permits only private recovery and domain visibility",
assert.equal(isShareActionAllowed(snapshot, "copy-link", "invited"), false);
});
+test("share visibility lists hide policy-denied choices", async () => {
+ const { filterShareVisibilityOptions } = await load();
+ const options = [{ id: "private" }, { id: "invited" }, { id: "link" }, { id: "domain" }];
+ const domainOnlyPolicy = {
+ ...policy,
+ sharing: { externalLinkSharing: "domain_only" },
+ };
+ const disabledPolicy = {
+ ...policy,
+ sharing: { externalLinkSharing: "disabled" },
+ };
+
+ assert.deepEqual(
+ filterShareVisibilityOptions(options, {
+ status: "managed",
+ policy: domainOnlyPolicy,
+ appVersion: "1.8.1",
+ }).map((option) => option.id),
+ ["private", "domain"]
+ );
+ assert.deepEqual(
+ filterShareVisibilityOptions(options, {
+ status: "managed",
+ policy: disabledPolicy,
+ appVersion: "1.8.1",
+ }).map((option) => option.id),
+ ["private"]
+ );
+});
+
+test("domain-only sharing is usable only when the owner can offer a domain choice", async () => {
+ const { hasUsableExternalShareVisibility } = await load();
+ const snapshot = {
+ status: "managed",
+ policy: { ...policy, sharing: { externalLinkSharing: "domain_only" } },
+ appVersion: "1.8.1",
+ };
+
+ assert.equal(hasUsableExternalShareVisibility(snapshot, true), true);
+ assert.equal(hasUsableExternalShareVisibility(snapshot, false), false);
+});
+
+test("provider fallback persistence is limited to resolved unmanaged and signed-out idle users", async () => {
+ const { shouldPersistProviderFallback } = await load();
+
+ assert.equal(
+ shouldPersistProviderFallback({ status: "unmanaged", policy: null, appVersion: "1.8.1" }, true),
+ true
+ );
+ assert.equal(
+ shouldPersistProviderFallback({ status: "idle", policy: null, appVersion: null }, false),
+ true
+ );
+ assert.equal(
+ shouldPersistProviderFallback({ status: "idle", policy: null, appVersion: null }, true),
+ false
+ );
+ assert.equal(
+ shouldPersistProviderFallback({ status: "managed", policy, appVersion: "1.8.1" }, true),
+ false
+ );
+});
+
test("copying an existing share link follows its own visibility", async () => {
const { isShareActionAllowed } = await load();
const unmanaged = { status: "unmanaged", policy: null, appVersion: "1.8.1" };
@@ -311,6 +585,17 @@ test("re-entering providers mode replaces a dormant policy-disallowed provider",
}),
null
);
+
+ 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 --git a/test/helpers/retryTranscriptionRouting.test.js b/test/helpers/retryTranscriptionRouting.test.js
index 9e53c903d..4e3d67845 100644
--- a/test/helpers/retryTranscriptionRouting.test.js
+++ b/test/helpers/retryTranscriptionRouting.test.js
@@ -98,3 +98,48 @@ test("does not intercept non-self-hosted retry modes", async () => {
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/secureEndpoint.test.js b/test/helpers/secureEndpoint.test.js
index 8b0f712c8..880fab58b 100644
--- a/test/helpers/secureEndpoint.test.js
+++ b/test/helpers/secureEndpoint.test.js
@@ -86,3 +86,13 @@ test("unparseable input is never secure", async () => {
assert.equal(isSecureEndpoint(""), false);
assert.equal(isSecureEndpoint("not-a-url"), false);
});
+
+test("secure HTTP endpoints reject non-HTTP schemes even on private hosts", async () => {
+ const { isSecureHttpEndpoint } = await load();
+
+ assert.equal(isSecureHttpEndpoint("https://api.example.com/v1"), true);
+ assert.equal(isSecureHttpEndpoint("http://192.168.1.20:5001/v1"), true);
+ assert.equal(isSecureHttpEndpoint("http://public.example.com/v1"), false);
+ assert.equal(isSecureHttpEndpoint("ftp://192.168.1.20/v1"), false);
+ assert.equal(isSecureHttpEndpoint("ws://127.0.0.1:5001/v1"), false);
+});
diff --git a/test/services/fileTranscriptionCustomEndpoint.test.js b/test/services/fileTranscriptionCustomEndpoint.test.js
new file mode 100644
index 000000000..cd85f6b56
--- /dev/null
+++ b/test/services/fileTranscriptionCustomEndpoint.test.js
@@ -0,0 +1,58 @@
+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");
+});
diff --git a/test/services/promptStudioAgentPurpose.test.js b/test/services/promptStudioAgentPurpose.test.js
index 94f52e4e0..5ec42eab0 100644
--- a/test/services/promptStudioAgentPurpose.test.js
+++ b/test/services/promptStudioAgentPurpose.test.js
@@ -41,6 +41,7 @@ test("Prompt Studio labels dictation-agent runs for policy enforcement", async (
"react/jsx-dev-runtime": "jsx-runtime",
"react/jsx-runtime": "jsx-runtime",
"react-i18next": "i18n",
+ "zustand/react/shallow": "zustand-shallow",
"./button": "button",
"./textarea": "textarea",
"lucide-react": "icons",
@@ -48,6 +49,7 @@ test("Prompt Studio labels dictation-agent runs for policy enforcement", async (
};
if (modules[source]) return `\0prompt-studio-${modules[source]}`;
if (source.endsWith("/hooks/useDialogs")) return "\0prompt-studio-dialogs";
+ if (source.endsWith("/hooks/usePolicy")) return "\0prompt-studio-policy";
if (source.endsWith("/utils/agentName")) return "\0prompt-studio-agent-name";
if (source.endsWith("/services/ReasoningService")) return "\0prompt-studio-reasoning";
if (source.endsWith("/models/ModelRegistry")) return "\0prompt-studio-models";
@@ -86,6 +88,9 @@ test("Prompt Studio labels dictation-agent runs for policy enforcement", async (
if (id === "\0prompt-studio-i18n") {
return `export function useTranslation() { return { t: (key) => key }; }`;
}
+ if (id === "\0prompt-studio-zustand-shallow") {
+ return `export function useShallow(selector) { return selector; }`;
+ }
if (id === "\0prompt-studio-button") return "export function Button() {}";
if (id === "\0prompt-studio-textarea") return "export function Textarea() {}";
if (id === "\0prompt-studio-icons") {
@@ -113,6 +118,13 @@ test("Prompt Studio labels dictation-agent runs for policy enforcement", async (
}
`;
}
+ if (id === "\0prompt-studio-policy") {
+ return `
+ export function usePolicySnapshot() {
+ return { status: "unmanaged", policy: null, appVersion: "1.8.1" };
+ }
+ `;
+ }
if (id === "\0prompt-studio-agent-name") {
return `export function useAgentName() { return { agentName: "Whisper" }; }`;
}
@@ -164,6 +176,7 @@ test("Prompt Studio labels dictation-agent runs for policy enforcement", async (
};
export function useSettingsStore(selector) { return selector(state); }
useSettingsStore.getState = () => state;
+ export function selectPolicyEffectiveSettings(settings) { return settings; }
export const selectIsCloudCleanupMode = () => true;
export const selectIsCloudDictationAgentMode = () => true;
export const selectIsCloudTranslationMode = () => true;
diff --git a/test/services/reasoningServiceEnforcement.test.js b/test/services/reasoningServiceEnforcement.test.js
index c69d82e6e..295a712f0 100644
--- a/test/services/reasoningServiceEnforcement.test.js
+++ b/test/services/reasoningServiceEnforcement.test.js
@@ -8,6 +8,7 @@ const enTranslations = require("../../src/locales/en/translation.json");
// would surface "No reasoning model selected" or a dispatch error instead.
const AGENT_RESTRICTED = enTranslations.common.policyAgentRestricted;
const REASONING_RESTRICTED = enTranslations.common.policyAiProcessingRestricted;
+const HTTPS_REQUIRED = enTranslations.reasoning.custom.httpsRequired;
function buildPolicy({ agentEnabled = true, llmModes = [], llmByokProviders = [] } = {}) {
return {
@@ -38,6 +39,8 @@ test("ReasoningService entry points enforce the org policy", async (t) => {
const reasoningService = (await vite.ssrLoadModule("/services/ReasoningService.ts")).default;
t.after(() => reasoningService.destroy());
const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");
+ const { useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");
+ const { resolveConfiguredOpenAIBase } = await vite.ssrLoadModule("/services/ai/openaiBase.ts");
const { default: i18n } = await vite.ssrLoadModule("/i18n.ts");
await i18n.changeLanguage("en");
@@ -129,4 +132,120 @@ test("ReasoningService entry points enforce the org policy", async (t) => {
});
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(
+ "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;
+ }
+ }
+ );
});