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): Enforce org policy beyond the settings UI

Chadpihaefc65e4c6e69
diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsx
index 722cbdc05..b6118783e 100644
--- a/src/components/SettingsModal.tsx
+++ b/src/components/SettingsModal.tsx
@@ -164,7 +164,7 @@ export default function SettingsModal({ open, onOpenChange, initialSection }: Se
>
{policyManaged && (
<div className="mx-4 mt-4 rounded-md border border-blue-200 bg-blue-50 px-3 py-2 text-sm text-blue-800 dark:border-blue-900 dark:bg-blue-950/40 dark:text-blue-200">
- {t("settingsModal.managedByOrg", "Some settings are managed by your organization.")}
+ {t("settingsModal.managedByOrg")}
</div>
)}
<SettingsPage
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index c01a0fcd9..5fdeb2fb6 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -108,7 +108,7 @@ import { syncService } from "../services/SyncService.js";
import { formatBytes } from "../utils/formatBytes";
import { clearMissingLocalModelSelections, useSettingsStore } from "../stores/settingsStore";
import { useWorkspaceStore } from "../stores/workspaceStore";
-import { usePolicyStore, enforceModeOptions } from "../stores/policyStore";
+import { usePolicyStore, enforceModeOptions, isModeAllowed } from "../stores/policyStore";
import { canManageSystemAudioInApp } from "../utils/systemAudioAccess";
import WorkspaceSection from "./settings/WorkspaceSection";
import WorkspaceBillingOverview from "./settings/WorkspaceBillingOverview";
@@ -304,10 +304,15 @@ function TranscriptionSection({
],
"transcription",
{ managed: policyManaged, policy: policyDoc },
- t("settingsPage.managedByOrg", "Managed by your organization"),
+ t("common.managedByOrg"),
);
const handleTranscriptionModeSelect = (mode: InferenceMode) => {
+ // "Disabled" mode options still fire onSelect (the sign-in gate relies on
+ // that to start onboarding), so policy must be enforced here, not in the UI.
+ if (!isModeAllowed({ managed: policyManaged, policy: policyDoc }, "transcription", mode)) {
+ return;
+ }
if (mode === "openwhispr" && !isSignedIn) {
startOnboarding();
return;
diff --git a/src/components/settings/InferenceConfigEditor.tsx b/src/components/settings/InferenceConfigEditor.tsx
index 77d5f8401..889692d70 100644
--- a/src/components/settings/InferenceConfigEditor.tsx
+++ b/src/components/settings/InferenceConfigEditor.tsx
@@ -7,6 +7,7 @@ import {
selectResolvedLLMConfig,
setResolvedLLMConfig,
} from "../../stores/settingsStore";
+import { usePolicyStore, enforceModeOptions, isModeAllowed } from "../../stores/policyStore";
import { InferenceModeSelector } from "../ui/SettingsSection";
import type { InferenceModeOption } from "../ui/SettingsSection";
import ReasoningModelSelector from "../ReasoningModelSelector";
@@ -15,29 +16,7 @@ import OpenAICompatiblePanel from "../OpenAICompatiblePanel";
import { Toggle } from "../ui/toggle";
import type { InferenceMode } from "../../types/electron";
import type { InferenceScope } from "../../config/inferenceScopes";
-import {
- modelRegistry,
- isEnterpriseProvider,
- getCloudModel,
- getLocalModel,
-} from "../../models/ModelRegistry";
-
-function isProviderValidForMode(provider: string, mode: InferenceMode): boolean {
- switch (mode) {
- case "providers":
- return (
- provider === "custom" ||
- provider === "openrouter" ||
- modelRegistry.getCloudProviders().some((p) => p.id === provider)
- );
- case "local":
- return modelRegistry.getAllProviders().some((p) => p.id === provider);
- case "enterprise":
- return isEnterpriseProvider(provider);
- default:
- return true;
- }
-}
+import { isProviderValidForMode, getCloudModel, getLocalModel } from "../../models/ModelRegistry";
const MODE_LABEL_PREFIX: Record<InferenceScope, string> = {
dictationCleanup: "settingsPage.aiModels.modes",
@@ -63,42 +42,49 @@ export default function InferenceConfigEditor({ scope, onModeChange }: Inference
const { t } = useTranslation();
const config = useSettingsStore(useShallow((s) => selectResolvedLLMConfig(s, scope)));
const isSignedIn = useSettingsStore((s) => s.isSignedIn);
+ const policyManaged = usePolicyStore((s) => s.managed);
+ const policyDoc = usePolicyStore((s) => s.policy);
const prefix = MODE_LABEL_PREFIX[scope];
- const modes: InferenceModeOption[] = [
- {
- id: "openwhispr",
- label: t(`${prefix}.openwhispr`),
- description: t(`${prefix}.openwhisprDesc`),
- icon: <Cloud className="w-4 h-4" />,
- disabled: !isSignedIn,
- badge: !isSignedIn ? t("common.freeAccountRequired") : undefined,
- },
- {
- id: "providers",
- label: t(`${prefix}.providers`),
- description: t(`${prefix}.providersDesc`),
- icon: <Key className="w-4 h-4" />,
- },
- {
- id: "local",
- label: t(`${prefix}.local`),
- description: t(`${prefix}.localDesc`),
- icon: <Cpu className="w-4 h-4" />,
- },
- {
- id: "self-hosted",
- label: t(`${prefix}.selfHosted`),
- description: t(`${prefix}.selfHostedDesc`),
- icon: <Network className="w-4 h-4" />,
- },
- {
- id: "enterprise",
- label: t(`${prefix}.enterprise`),
- description: t(`${prefix}.enterpriseDesc`),
- icon: <Building2 className="w-4 h-4" />,
- },
- ];
+ const modes: InferenceModeOption[] = enforceModeOptions(
+ [
+ {
+ id: "openwhispr",
+ label: t(`${prefix}.openwhispr`),
+ description: t(`${prefix}.openwhisprDesc`),
+ icon: <Cloud className="w-4 h-4" />,
+ disabled: !isSignedIn,
+ badge: !isSignedIn ? t("common.freeAccountRequired") : undefined,
+ },
+ {
+ id: "providers",
+ label: t(`${prefix}.providers`),
+ description: t(`${prefix}.providersDesc`),
+ icon: <Key className="w-4 h-4" />,
+ },
+ {
+ id: "local",
+ label: t(`${prefix}.local`),
+ description: t(`${prefix}.localDesc`),
+ icon: <Cpu className="w-4 h-4" />,
+ },
+ {
+ id: "self-hosted",
+ label: t(`${prefix}.selfHosted`),
+ description: t(`${prefix}.selfHostedDesc`),
+ icon: <Network className="w-4 h-4" />,
+ },
+ {
+ id: "enterprise",
+ label: t(`${prefix}.enterprise`),
+ description: t(`${prefix}.enterpriseDesc`),
+ icon: <Building2 className="w-4 h-4" />,
+ },
+ ],
+ "llm",
+ { managed: policyManaged, policy: policyDoc },
+ t("common.managedByOrg")
+ );
const setField = useCallback(
<K extends keyof Omit<typeof config, "scope">>(field: K) =>
@@ -110,6 +96,11 @@ export default function InferenceConfigEditor({ scope, onModeChange }: Inference
const handleModeSelect = useCallback(
(mode: InferenceMode) => {
+ // "Disabled" mode options still fire onSelect (the sign-in gate relies on
+ // that to start onboarding), so policy must be enforced here, not in the UI.
+ if (!isModeAllowed({ managed: policyManaged, policy: policyDoc }, "llm", mode)) {
+ return;
+ }
if (mode === "openwhispr" && !isSignedIn) {
startCloudOnboarding();
return;
@@ -132,7 +123,7 @@ export default function InferenceConfigEditor({ scope, onModeChange }: Inference
onModeChange?.(mode);
},
- [scope, config.mode, config.provider, isSignedIn, onModeChange]
+ [scope, config.mode, config.provider, isSignedIn, onModeChange, policyManaged, policyDoc]
);
const setMode = setField("mode");
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index a2a553c91..09ceee81e 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -10,6 +10,7 @@ const tokenStore = require("./tokenStore");
const { createCloudApiRequestHandler } = require("./cloudApiRequest");
const { classifyAndLog } = require("./networkErrors");
const { resolveLocalServerNeeds } = require("./localServerPolicy");
+const { isValidPolicyShape } = require("./policyValidation");
const GnomeShortcutManager = require("./gnomeShortcut");
const HyprlandShortcutManager = require("./hyprlandShortcut");
const AssemblyAiStreaming = require("./assemblyAiStreaming");
@@ -7630,6 +7631,11 @@ class IPCHandlers {
}
});
+ const withAppVersion = (headers) => ({
+ ...headers,
+ "x-openwhispr-version": app.getVersion(),
+ });
+
ipcMain.handle("cloud-api-request", (_event, opts) => handleCloudApiRequest(opts));
ipcMain.handle("get-stt-config", async (event) => {
@@ -7641,7 +7647,7 @@ class IPCHandlers {
if (!Object.keys(authHeader).length) throw new Error("Not authenticated");
const response = await proxyFetch(`${apiUrl}/api/stt-config`, {
- headers: { ...authHeader, "x-openwhispr-version": app.getVersion() },
+ headers: withAppVersion(authHeader),
});
if (!response.ok) {
@@ -7677,7 +7683,7 @@ class IPCHandlers {
if (!Object.keys(authHeader).length) throw new Error("Not authenticated");
const response = await proxyFetch(`${apiUrl}/api/workspace-policy`, {
- headers: { ...authHeader, "x-openwhispr-version": app.getVersion() },
+ headers: withAppVersion(authHeader),
});
if (!response.ok) throw new Error(`API error: ${response.status}`);
@@ -7686,7 +7692,11 @@ class IPCHandlers {
// Treat a malformed 200 body as a failure, not an authoritative
// "unmanaged" verdict, so the catch serves the cached policy (fail-closed)
// instead of deleting it and unlocking the user.
- if (!data || typeof data.managed !== "boolean") {
+ if (
+ !data ||
+ typeof data.managed !== "boolean" ||
+ (data.managed && !isValidPolicyShape(data.policy))
+ ) {
throw new Error("Malformed policy response");
}
if (data.managed) {
@@ -7707,7 +7717,11 @@ class IPCHandlers {
try {
if (fs.existsSync(cachePath)) {
const cached = JSON.parse(fs.readFileSync(cachePath, "utf8"));
- return { success: true, status: "cached", ...cached };
+ // Re-validate: a cache written by a build that predates shape
+ // validation (or a corrupted file) must not reach the renderer.
+ if (cached?.managed === true && isValidPolicyShape(cached.policy)) {
+ return { success: true, status: "cached", ...cached };
+ }
}
} catch (err) {
debugLogger.error("Policy cache read failed:", err);
diff --git a/src/helpers/policyValidation.js b/src/helpers/policyValidation.js
new file mode 100644
index 000000000..6b9d8dafd
--- /dev/null
+++ b/src/helpers/policyValidation.js
@@ -0,0 +1,20 @@
+// Structural validation for the org policy delivered by /api/workspace-policy.
+// The renderer dereferences policy.<scope>.allowedModes etc. unchecked, and
+// treats a null policy as "allow everything" — so a managed response must
+// carry a structurally valid policy or the whole response is malformed.
+const POLICY_SCOPES = ["transcription", "llm"];
+
+function isValidPolicyShape(policy) {
+ return (
+ Boolean(policy) &&
+ typeof policy === "object" &&
+ POLICY_SCOPES.every(
+ (scope) =>
+ Array.isArray(policy[scope]?.allowedModes) &&
+ Array.isArray(policy[scope]?.allowedByokProviders)
+ ) &&
+ Array.isArray(policy.llm?.allowedEnterpriseProviders)
+ );
+}
+
+module.exports = { isValidPolicyShape };
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 792f68cad..b1ae8dbcc 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -144,6 +144,7 @@
"cancel": "Abbrechen",
"recommended": "Empfohlen",
"active": "Aktiv",
+ "managedByOrg": "Von Ihrer Organisation verwaltet",
"freeAccountRequired": "Kostenloses Konto erforderlich",
"cloud": "Cloud",
"local": "Lokal",
@@ -1168,6 +1169,7 @@
"defaultTestInputTranslate": "Das Wetter ist heute wunderschön, hast du Lust auf einen Spaziergang?"
},
"settingsModal": {
+ "managedByOrg": "Einige Einstellungen werden von Ihrer Organisation verwaltet.",
"groups": {
"account": "Konto",
"app": "App",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 606eec015..505776338 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -144,6 +144,7 @@
"cancel": "Cancel",
"recommended": "Recommended",
"active": "Active",
+ "managedByOrg": "Managed by your organization",
"freeAccountRequired": "Free account required",
"cloud": "Cloud",
"local": "Local",
@@ -1168,6 +1169,7 @@
"defaultTestInputTranslate": "The weather is beautiful today, want to go for a walk?"
},
"settingsModal": {
+ "managedByOrg": "Some settings are managed by your organization.",
"groups": {
"account": "Account",
"app": "App",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index a7113d023..1345f0fc8 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -144,6 +144,7 @@
"cancel": "Cancelar",
"recommended": "Recomendado",
"active": "Activo",
+ "managedByOrg": "Gestionado por tu organización",
"freeAccountRequired": "Cuenta gratuita requerida",
"cloud": "Nube",
"local": "Local",
@@ -1128,6 +1129,7 @@
"defaultTestInputTranslate": "Hace un día precioso hoy, ¿te apetece dar un paseo?"
},
"settingsModal": {
+ "managedByOrg": "Algunos ajustes están gestionados por tu organización.",
"groups": {
"account": "Cuenta",
"app": "Aplicación",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index d650181c0..34749b0b0 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -144,6 +144,7 @@
"cancel": "Annuler",
"recommended": "Recommandé",
"active": "Actif",
+ "managedByOrg": "Géré par votre organisation",
"freeAccountRequired": "Compte gratuit requis",
"cloud": "Cloud",
"local": "Local",
@@ -1168,6 +1169,7 @@
"defaultTestInputTranslate": "Il fait très beau aujourd'hui, ça te dit d'aller te promener ?"
},
"settingsModal": {
+ "managedByOrg": "Certains paramètres sont gérés par votre organisation.",
"groups": {
"account": "Compte",
"app": "Application",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index be1b9d6f3..ef8c48593 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -144,6 +144,7 @@
"cancel": "Annulla",
"recommended": "Consigliato",
"active": "Attivo",
+ "managedByOrg": "Gestito dalla tua organizzazione",
"freeAccountRequired": "Account gratuito richiesto",
"cloud": "Cloud",
"local": "Locale",
@@ -1080,6 +1081,7 @@
"defaultTestInputTranslate": "Che bella giornata oggi, ti va di fare due passi?"
},
"settingsModal": {
+ "managedByOrg": "Alcune impostazioni sono gestite dalla tua organizzazione.",
"groups": {
"account": "Account",
"app": "App",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 97f38356e..14ac94d7b 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -144,6 +144,7 @@
"cancel": "キャンセル",
"recommended": "推奨",
"active": "有効",
+ "managedByOrg": "組織によって管理されています",
"freeAccountRequired": "無料アカウントが必要です",
"cloud": "クラウド",
"local": "ローカル",
@@ -1080,6 +1081,7 @@
"defaultTestInputTranslate": "今日はいい天気ですね、散歩に行きませんか?"
},
"settingsModal": {
+ "managedByOrg": "一部の設定は組織によって管理されています。",
"groups": {
"account": "アカウント",
"app": "アプリ",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 716f54ede..a1ec27002 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -123,6 +123,7 @@
"cancel": "Cancelar",
"recommended": "Recomendado",
"active": "Ativo",
+ "managedByOrg": "Gerenciado pela sua organização",
"freeAccountRequired": "Conta gratuita necessária",
"cloud": "Nuvem",
"local": "Local",
@@ -1059,6 +1060,7 @@
"defaultTestInputTranslate": "O tempo está lindo hoje, quer dar um passeio?"
},
"settingsModal": {
+ "managedByOrg": "Algumas configurações são gerenciadas pela sua organização.",
"groups": {
"account": "Conta",
"app": "Aplicativo",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 85ffbdc9c..809da6ed8 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -144,6 +144,7 @@
"cancel": "Отмена",
"recommended": "Рекомендуется",
"active": "Активно",
+ "managedByOrg": "Управляется вашей организацией",
"freeAccountRequired": "Требуется бесплатный аккаунт",
"cloud": "Облако",
"local": "Локально",
@@ -1080,6 +1081,7 @@
"defaultTestInputTranslate": "Сегодня прекрасная погода, хочешь прогуляться?"
},
"settingsModal": {
+ "managedByOrg": "Некоторые настройки управляются вашей организацией.",
"groups": {
"account": "Аккаунт",
"app": "Приложение",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index 362119d60..81e1f0294 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -144,6 +144,7 @@
"cancel": "取消",
"recommended": "推荐",
"active": "已激活",
+ "managedByOrg": "由您的组织管理",
"freeAccountRequired": "需要免费账户",
"cloud": "云端",
"local": "本地",
@@ -1080,6 +1081,7 @@
"defaultTestInputTranslate": "今天天气真好,要不要出去走走?"
},
"settingsModal": {
+ "managedByOrg": "部分设置由您的组织管理。",
"groups": {
"account": "账户",
"app": "应用",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index efa411f89..af9368e37 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -144,6 +144,7 @@
"cancel": "取消",
"recommended": "推薦",
"active": "使用中",
+ "managedByOrg": "由您的組織管理",
"freeAccountRequired": "需要免費帳戶",
"cloud": "雲端",
"local": "本機",
@@ -1080,6 +1081,7 @@
"defaultTestInputTranslate": "今天天氣真好,要不要出去走走?"
},
"settingsModal": {
+ "managedByOrg": "部分設定由您的組織管理。",
"groups": {
"account": "帳戶",
"app": "應用程式",
diff --git a/src/models/ModelRegistry.ts b/src/models/ModelRegistry.ts
index eef60b4fb..130dc9fea 100644
--- a/src/models/ModelRegistry.ts
+++ b/src/models/ModelRegistry.ts
@@ -1,6 +1,7 @@
import modelDataRaw from "./modelRegistryData.json";
import { isCloudCleanupMode, getSettings } from "../stores/settingsStore";
import { readCachedTinfoilModels } from "./tinfoilModelCache";
+import type { InferenceMode } from "../types/electron";
export interface ModelDefinition {
id: string;
@@ -250,6 +251,23 @@ export function toReasoningModel(m: CloudModelDefinition): ReasoningModel {
};
}
+export function isProviderValidForMode(provider: string, mode: InferenceMode): boolean {
+ switch (mode) {
+ case "providers":
+ return (
+ provider === "custom" ||
+ provider === "openrouter" ||
+ modelRegistry.getCloudProviders().some((p) => p.id === provider)
+ );
+ case "local":
+ return modelRegistry.getAllProviders().some((p) => p.id === provider);
+ case "enterprise":
+ return isEnterpriseProvider(provider);
+ default:
+ return true;
+ }
+}
+
function buildReasoningProviders(): ReasoningProviders {
const providers: ReasoningProviders = {};
diff --git a/src/stores/policyStore.ts b/src/stores/policyStore.ts
index 6e77be03b..df4a7243c 100644
--- a/src/stores/policyStore.ts
+++ b/src/stores/policyStore.ts
@@ -1,5 +1,12 @@
import { create } from "zustand";
import logger from "../utils/logger";
+import {
+ useSettingsStore,
+ selectResolvedLLMConfig,
+ setResolvedLLMConfig,
+} from "./settingsStore";
+import { INFERENCE_SCOPES, type InferenceScope } from "../config/inferenceScopes";
+import { isProviderValidForMode } from "../models/ModelRegistry";
import type { InferenceMode } from "../types/electron";
import type { OrgPolicy, PolicyScope } from "../types/policy";
@@ -13,29 +20,36 @@ interface PolicyState {
fetchPolicy: () => Promise<void>;
}
+// Several components mount useAuth at startup; share one in-flight fetch
+// between them instead of hitting the API once per consumer.
+let fetchInFlight: Promise<void> | null = null;
+
export const usePolicyStore = create<PolicyState>()((set) => ({
managed: false,
policy: null,
loaded: false,
- fetchPolicy: async () => {
- try {
- const result = await window.electronAPI.getWorkspacePolicy?.();
- if (result?.success) {
- set({
- managed: Boolean(result.managed),
- policy: result.policy ?? null,
- loaded: true,
- });
- return;
+ fetchPolicy: (): Promise<void> => {
+ fetchInFlight ??= (async () => {
+ try {
+ const result = await window.electronAPI.getWorkspacePolicy?.();
+ if (result?.success) {
+ const managed = Boolean(result.managed);
+ const policy = result.policy ?? null;
+ set({ managed, policy, loaded: true });
+ if (managed && policy) reconcileSettingsWithPolicy(policy);
+ return;
+ }
+ // Fetch failed with no cached policy: treat as unmanaged until a
+ // later fetch succeeds.
+ set({ loaded: true });
+ } catch (error) {
+ logger.error("Failed to fetch workspace policy:", error);
+ set({ loaded: true });
+ } finally {
+ fetchInFlight = null;
}
- // Fetch failed with no cache: treat as unmanaged until a later fetch
- // succeeds. The stt-config `managed` bootstrap flag locks provider
- // settings in the meantime for a fresh managed install.
- set({ loaded: true });
- } catch (error) {
- logger.error("Failed to fetch workspace policy:", error);
- set({ loaded: true });
- }
+ })();
+ return fetchInFlight;
},
}));
@@ -49,25 +63,6 @@ export function isModeAllowed(
return state.policy[scope].allowedModes.includes(mode);
}
-/** Whether a BYOK provider id is allowed for a scope. Unmanaged users allow everything. */
-export function isProviderAllowed(
- state: Pick<PolicyState, "managed" | "policy">,
- scope: PolicyScope,
- providerId: string
-): boolean {
- if (!state.managed || !state.policy) return true;
- return state.policy[scope].allowedByokProviders.includes(providerId);
-}
-
-/** Whether an enterprise-cloud provider id is allowed. Unmanaged users allow everything. */
-export function isEnterpriseProviderAllowed(
- state: Pick<PolicyState, "managed" | "policy">,
- providerId: string
-): boolean {
- if (!state.managed || !state.policy) return true;
- return state.policy.llm.allowedEnterpriseProviders.includes(providerId);
-}
-
/** Mark policy-disallowed mode options disabled with a "managed" badge. */
export function enforceModeOptions<
T extends { id: InferenceMode; disabled?: boolean; badge?: string },
@@ -84,3 +79,44 @@ export function enforceModeOptions<
: { ...option, disabled: true, badge: managedBadge }
);
}
+
+// Force any already-selected mode the policy disallows onto the first allowed
+// mode, mirroring what the settings UI does on a manual switch. Without this,
+// stored settings would keep using a mode the org has blocked and the policy
+// would only gate future UI clicks.
+function reconcileSettingsWithPolicy(policy: OrgPolicy): void {
+ const settings = useSettingsStore.getState();
+
+ if (!policy.transcription.allowedModes.includes(settings.transcriptionMode)) {
+ const next = policy.transcription.allowedModes[0];
+ if (next) {
+ settings.setTranscriptionMode(next);
+ settings.setUseLocalWhisper(next === "local");
+ settings.setCloudTranscriptionMode(next === "openwhispr" ? "openwhispr" : "byok");
+ }
+ }
+
+ const llmNext = policy.llm.allowedModes[0];
+ if (!llmNext) return;
+ let switched = false;
+ for (const scope of Object.keys(INFERENCE_SCOPES) as InferenceScope[]) {
+ const config = selectResolvedLLMConfig(useSettingsStore.getState(), scope);
+ if (policy.llm.allowedModes.includes(config.mode)) continue;
+ const patch: Parameters<typeof setResolvedLLMConfig>[1] = {
+ mode: llmNext,
+ cloudMode: llmNext === "openwhispr" ? "openwhispr" : "byok",
+ };
+ if (!isProviderValidForMode(config.provider, llmNext)) {
+ patch.provider = "";
+ patch.model = "";
+ }
+ setResolvedLLMConfig(scope, patch);
+ switched = true;
+ }
+ if (
+ switched &&
+ (llmNext === "openwhispr" || llmNext === "self-hosted" || llmNext === "enterprise")
+ ) {
+ window.electronAPI?.llamaServerStop?.();
+ }
+}
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 8ea11279b..01c9e569e 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -769,7 +769,6 @@ declare global {
dictation: { mode: string };
notes: { mode: string };
streamingProvider: string;
- managed?: boolean;
} | null>;
// Org policy (see src/types/policy.ts)
diff --git a/test/helpers/policyValidation.test.js b/test/helpers/policyValidation.test.js
new file mode 100644
index 000000000..99c87e22e
--- /dev/null
+++ b/test/helpers/policyValidation.test.js
@@ -0,0 +1,68 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const { isValidPolicyShape } = require("../../src/helpers/policyValidation");
+
+const validPolicy = () => ({
+ version: 1,
+ transcription: {
+ allowedModes: ["openwhispr", "local"],
+ allowedByokProviders: [],
+ },
+ llm: {
+ allowedModes: ["openwhispr"],
+ allowedByokProviders: ["openai"],
+ allowedEnterpriseProviders: ["bedrock"],
+ },
+ features: { agentEnabled: true, webSearchEnabled: false },
+ sharing: { externalLinkSharing: "allowed" },
+ dataRetention: {
+ audioRetentionMaxDays: null,
+ localHistoryMode: "user_choice",
+ cloudBackupAllowed: true,
+ },
+ minAppVersion: null,
+});
+
+test("accepts a well-formed policy", () => {
+ assert.equal(isValidPolicyShape(validPolicy()), true);
+});
+
+test("accepts empty allowlists", () => {
+ const policy = validPolicy();
+ policy.transcription.allowedModes = [];
+ policy.llm.allowedModes = [];
+ policy.llm.allowedEnterpriseProviders = [];
+ assert.equal(isValidPolicyShape(policy), true);
+});
+
+test("rejects a missing or non-object policy", () => {
+ assert.equal(isValidPolicyShape(undefined), false);
+ assert.equal(isValidPolicyShape(null), false);
+ assert.equal(isValidPolicyShape("managed"), false);
+ assert.equal(isValidPolicyShape(42), false);
+});
+
+test("rejects a policy missing a scope", () => {
+ for (const scope of ["transcription", "llm"]) {
+ const policy = validPolicy();
+ delete policy[scope];
+ assert.equal(isValidPolicyShape(policy), false, `missing ${scope}`);
+ }
+});
+
+test("rejects non-array allowlists the renderer dereferences", () => {
+ for (const [scope, field] of [
+ ["transcription", "allowedModes"],
+ ["transcription", "allowedByokProviders"],
+ ["llm", "allowedModes"],
+ ["llm", "allowedByokProviders"],
+ ["llm", "allowedEnterpriseProviders"],
+ ]) {
+ const policy = validPolicy();
+ policy[scope][field] = "openwhispr";
+ assert.equal(isValidPolicyShape(policy), false, `${scope}.${field} as string`);
+ delete policy[scope][field];
+ assert.equal(isValidPolicyShape(policy), false, `${scope}.${field} missing`);
+ }
+});