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): Harden enforcement gaps and consolidate the policy layer

Chadpiha89d0c19dd9c5
diff --git a/preload.js b/preload.js
index c22850f40..cfbdff8d5 100644
--- a/preload.js
+++ b/preload.js
@@ -605,8 +605,8 @@ contextBridge.exposeInMainWorld("electronAPI", {
cloudPreviewSwitch: (opts) => ipcRenderer.invoke("cloud-preview-switch", opts),
cloudApiRequest: (opts) => ipcRenderer.invoke("cloud-api-request", opts),
getSttConfig: () => ipcRenderer.invoke("get-stt-config"),
- getWorkspacePolicy: (accountId, expectedAuthGeneration, reason) =>
- ipcRenderer.invoke("get-workspace-policy", accountId, expectedAuthGeneration, reason),
+ getWorkspacePolicy: (accountId, expectedAuthGeneration) =>
+ ipcRenderer.invoke("get-workspace-policy", accountId, expectedAuthGeneration),
onWorkspacePolicyChanged: (callback) => {
const listener = (_event, snapshot) => callback(snapshot);
ipcRenderer.on("workspace-policy-changed", listener);
diff --git a/src/components/AgentOverlay.tsx b/src/components/AgentOverlay.tsx
index 793287e9f..7e86e51c2 100644
--- a/src/components/AgentOverlay.tsx
+++ b/src/components/AgentOverlay.tsx
@@ -5,7 +5,8 @@ import { AgentTitleBar } from "./agent/AgentTitleBar";
import { AgentChat } from "./agent/AgentChat";
import { AgentInput } from "./agent/AgentInput";
import AudioManager from "../helpers/audioManager";
-import { usePolicyStore, isAgentAllowed } from "../stores/policyStore";
+import { isAgentAllowed } from "../stores/policyRules";
+import { usePolicyStore } from "../stores/policyStore";
import { useChatPersistence } from "./chat/useChatPersistence";
import { useChatStreaming } from "./chat/useChatStreaming";
import { useChatMessageSender } from "./chat/useChatMessageSender";
diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsx
index 94e93f97e..1944d49c3 100644
--- a/src/components/ControlPanel.tsx
+++ b/src/components/ControlPanel.tsx
@@ -32,14 +32,14 @@ import {
clearTranscriptions as clearStore,
} from "../stores/transcriptionStore";
import { useSettingsStore } from "../stores/settingsStore";
+import { usePolicyStore } from "../stores/policyStore";
import {
isAgentAllowed,
- isDesktopActionAllowed,
+ isControlPanelViewAllowed,
+ isPolicyActionAllowed,
isTranscriptionContextAllowed,
- usePolicyStore,
-} from "../stores/policyStore";
-import { isControlPanelViewAllowed } from "../stores/policyRules";
-import { compareAppVersions } from "../utils/version";
+ isUpdateRequiredByOrg,
+} from "../stores/policyRules";
import {
useIsMeetingMode,
useIsNarrowWindow,
@@ -181,28 +181,18 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
isInstalling,
downloadUpdate,
installUpdate,
- getAppVersion,
error: updateError,
} = useUpdater();
- const policyMinAppVersion = usePolicyStore((s) =>
- s.managed ? (s.policy?.minAppVersion ?? null) : null
- );
const agentAllowedByPolicy = usePolicyStore(isAgentAllowed);
- const policyActionsAllowed = usePolicyStore((state) => isDesktopActionAllowed(state, "capture"));
+ const policyActionsAllowed = usePolicyStore((state) => isPolicyActionAllowed(state));
useEffect(() => {
if (!isControlPanelViewAllowed(activeView, agentAllowedByPolicy, policyActionsAllowed)) {
setActiveView("home");
}
}, [activeView, agentAllowedByPolicy, policyActionsAllowed]);
- const [appVersion, setAppVersion] = useState<string | null>(null);
- useEffect(() => {
- if (!policyMinAppVersion) return;
- void getAppVersion().then((version: string | null) => setAppVersion(version));
- }, [policyMinAppVersion, getAppVersion]);
- const updateRequiredByOrg = Boolean(
- policyMinAppVersion && appVersion && compareAppVersions(appVersion, policyMinAppVersion) < 0
- );
+ const updateRequiredByOrg = usePolicyStore(isUpdateRequiredByOrg);
+ const policyMinAppVersion = usePolicyStore((s) => s.policy?.minAppVersion ?? null);
const {
confirmDialog,
diff --git a/src/components/ControlPanelSidebar.tsx b/src/components/ControlPanelSidebar.tsx
index 8e1853a6b..7e1bd91e9 100644
--- a/src/components/ControlPanelSidebar.tsx
+++ b/src/components/ControlPanelSidebar.tsx
@@ -19,7 +19,8 @@ import { cn } from "./lib/utils";
import SupportDropdown from "./ui/SupportDropdown";
import { getCachedPlatform } from "../utils/platform";
import type { UpsellDecision } from "../lib/upsell";
-import { isAgentAllowed, isDesktopActionAllowed, usePolicyStore } from "../stores/policyStore";
+import { isAgentAllowed, isPolicyActionAllowed } from "../stores/policyRules";
+import { usePolicyStore } from "../stores/policyStore";
const platform = getCachedPlatform();
@@ -75,7 +76,7 @@ export default function ControlPanelSidebar({
const showUpgradeBanner = upsell === "show" && !showLimitBanner && !upgradeDismissed;
const agentAllowed = usePolicyStore(isAgentAllowed);
- const policyActionsAllowed = usePolicyStore((state) => isDesktopActionAllowed(state, "capture"));
+ const policyActionsAllowed = usePolicyStore((state) => isPolicyActionAllowed(state));
const navItems: {
id: ControlPanelView;
diff --git a/src/components/EnterpriseSection.tsx b/src/components/EnterpriseSection.tsx
index ad5c8bfb1..7d7ddbf9d 100644
--- a/src/components/EnterpriseSection.tsx
+++ b/src/components/EnterpriseSection.tsx
@@ -4,7 +4,8 @@ import EnterpriseProviderConfig from "./EnterpriseProviderConfig";
import { REASONING_PROVIDERS } from "../models/ModelRegistry";
import { useSettingsStore } from "../stores/settingsStore";
import { adjustBedrockModelForRegion } from "../utils/bedrockRegions";
-import { usePolicyStore, isEnterpriseProviderAllowed } from "../stores/policyStore";
+import { isEnterpriseProviderAllowed } from "../stores/policyRules";
+import { usePolicySnapshot } from "../hooks/usePolicy";
const ENTERPRISE_PROVIDER_TABS = [
{ id: "bedrock", name: "AWS Bedrock" },
@@ -28,14 +29,9 @@ export default function EnterpriseSection({
const { t } = useTranslation();
const azureDeploymentName = useSettingsStore((s) => s.azureDeploymentName);
const bedrockRegion = useSettingsStore((s) => s.bedrockRegion);
- const policyStatus = usePolicyStore((s) => s.status);
- const policyDoc = usePolicyStore((s) => s.policy);
- const appVersion = usePolicyStore((s) => s.appVersion);
+ const policyState = usePolicySnapshot();
const providerAllowed = (providerId: string) =>
- isEnterpriseProviderAllowed(
- { status: policyStatus, policy: policyDoc, appVersion },
- providerId
- );
+ isEnterpriseProviderAllowed(policyState, providerId);
const providerTabs = ENTERPRISE_PROVIDER_TABS.map((tab) =>
providerAllowed(tab.id)
diff --git a/src/components/HistoryView.tsx b/src/components/HistoryView.tsx
index a892a9686..b22bfe7ca 100644
--- a/src/components/HistoryView.tsx
+++ b/src/components/HistoryView.tsx
@@ -10,7 +10,8 @@ import { cn } from "./lib/utils";
import { useUpcomingEvents } from "../hooks/useUpcomingEvents";
import UpcomingMeetings from "./UpcomingMeetings";
import { useSettingsStore } from "../stores/settingsStore";
-import { effectiveLocalHistoryEnabled, usePolicyStore } from "../stores/policyStore";
+import { effectiveLocalHistoryEnabled } from "../stores/policyRules";
+import { usePolicyStore } from "../stores/policyStore";
interface HistoryViewProps {
history: TranscriptionItemType[];
diff --git a/src/components/MeetingRecordingMount.tsx b/src/components/MeetingRecordingMount.tsx
index c92c47db3..19651c6ba 100644
--- a/src/components/MeetingRecordingMount.tsx
+++ b/src/components/MeetingRecordingMount.tsx
@@ -10,6 +10,11 @@ import {
const EMA_PREV = 0.5;
const EMA_NEXT = 0.5;
+// Sentinel errors set by meetingRecordingStore, translated at display time.
+const MEETING_ERROR_KEYS: Record<string, string> = {
+ policyRestricted: "notes.meeting.restrictedByOrg",
+};
+
export default function MeetingRecordingMount(): null {
const { t } = useTranslation();
const { toast } = useToast();
@@ -26,7 +31,7 @@ export default function MeetingRecordingMount(): null {
if (!error) return;
toast({
title: t("notes.meeting.title"),
- description: error,
+ description: MEETING_ERROR_KEYS[error] ? t(MEETING_ERROR_KEYS[error]) : error,
variant: "destructive",
});
}, [error, toast, t]);
diff --git a/src/components/ReasoningModelSelector.tsx b/src/components/ReasoningModelSelector.tsx
index d247695b7..9952dc3a0 100644
--- a/src/components/ReasoningModelSelector.tsx
+++ b/src/components/ReasoningModelSelector.tsx
@@ -12,7 +12,7 @@ import { Cloud, Lock, Zap } from "lucide-react";
import ApiKeyInput from "./ui/ApiKeyInput";
import ModelCardList from "./ui/ModelCardList";
import LocalModelPicker, { type LocalProvider } from "./LocalModelPicker";
-import { ProviderTabs } from "./ui/ProviderTabs";
+import { ProviderTabs, type ProviderTabItem } from "./ui/ProviderTabs";
import OpenAICompatiblePanel from "./OpenAICompatiblePanel";
import { API_ENDPOINTS } from "../config/constants";
import logger from "../utils/logger";
@@ -24,7 +24,8 @@ import { getRemoteProviderIcon } from "../utils/providerIcons";
import { GetApiKeyLink } from "./ui/GetApiKeyLink";
import { getCachedPlatform } from "../utils/platform";
import { useSettingsStore } from "../stores/settingsStore";
-import { usePolicyStore, isProviderAllowed } from "../stores/policyStore";
+import { isProviderAllowedByPolicy } from "../stores/policyRules";
+import { usePolicySnapshot } from "../hooks/usePolicy";
type CloudModelOption = {
value: string;
@@ -349,26 +350,29 @@ export default function ReasoningModelSelector({
loading: tinfoilModelsLoading,
error: tinfoilModelsError,
} = useTinfoilModels(selectedCloudProvider === "tinfoil");
- const policyStatus = usePolicyStore((s) => s.status);
- const policyDoc = usePolicyStore((s) => s.policy);
- const appVersion = usePolicyStore((s) => s.appVersion);
+ const policyState = usePolicySnapshot();
const providerAllowed = useCallback(
- (providerId: string) =>
- isProviderAllowed({ status: policyStatus, policy: policyDoc, appVersion }, "llm", providerId),
- [policyStatus, policyDoc, appVersion]
+ (providerId: string) => isProviderAllowedByPolicy(policyState, "llm", providerId),
+ [policyState]
);
const effectiveMode = mode || selectedMode;
- const cloudProviders = CLOUD_PROVIDER_IDS.filter(providerAllowed).map((id) => ({
- id,
- name:
- id === "custom"
- ? t("reasoning.custom.providerName")
- : id === OPENROUTER_TAB
- ? "OpenRouter"
- : REASONING_PROVIDERS[id as keyof typeof REASONING_PROVIDERS]?.name || id,
- }));
+ 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 localProviders = useMemo<LocalProvider[]>(() => {
return modelRegistry.getAllProviders().map((provider) => ({
@@ -556,7 +560,7 @@ export default function ReasoningModelSelector({
{effectiveMode === "cloud" && (
<div className="space-y-2">
<ProviderTabs
- providers={cloudProviders}
+ providers={cloudProviderTabs}
selectedId={selectedCloudProvider}
onSelect={handleCloudProviderChange}
colorScheme="purple"
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index cc4524f67..7980661be 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -109,16 +109,14 @@ import { formatBytes } from "../utils/formatBytes";
import { clearMissingLocalModelSelections, useSettingsStore } from "../stores/settingsStore";
import { useWorkspaceStore } from "../stores/workspaceStore";
import {
- usePolicyStore,
+ canChangeCloudBackupPreference,
effectiveAudioRetentionDays,
effectiveLocalHistoryEnabled,
- enforceModeOptions,
- isModeAllowed,
- lockedLocalHistoryValue,
isCloudBackupAllowed,
+ lockedLocalHistoryValue,
maxAudioRetentionDays,
-} from "../stores/policyStore";
-import { canChangeCloudBackupPreference } from "../stores/policyRules";
+} from "../stores/policyRules";
+import { usePolicyModeOptions, usePolicySnapshot } from "../hooks/usePolicy";
import { canManageSystemAudioInApp } from "../utils/systemAudioAccess";
import WorkspaceSection from "./settings/WorkspaceSection";
import WorkspaceBillingOverview from "./settings/WorkspaceBillingOverview";
@@ -280,12 +278,7 @@ function TranscriptionSection({
toast,
}: TranscriptionSectionProps) {
const { t } = useTranslation();
- const policyStatus = usePolicyStore((s) => s.status);
- const policyDoc = usePolicyStore((s) => s.policy);
- const policyAppVersion = usePolicyStore((s) => s.appVersion);
- const policyState = { status: policyStatus, policy: policyDoc, appVersion: policyAppVersion };
-
- const transcriptionModes: InferenceModeOption[] = enforceModeOptions(
+ const { modes: transcriptionModes, isModeAllowed } = usePolicyModeOptions<InferenceModeOption>(
[
{
id: "openwhispr",
@@ -314,17 +307,11 @@ function TranscriptionSection({
icon: <Network className="w-4 h-4" />,
},
],
- "transcription",
- policyState,
- t("common.managedByOrg")
+ "transcription"
);
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(policyState, "transcription", mode)) {
- return;
- }
+ if (!isModeAllowed(mode)) return;
if (mode === "openwhispr" && !isSignedIn) {
startOnboarding();
return;
@@ -876,14 +863,7 @@ export default function SettingsPage({
const translationKey = useSettingsStore((s) => s.translationKey);
const setTranslationKey = useSettingsStore((s) => s.setTranslationKey);
- const settingsPolicyStatus = usePolicyStore((s) => s.status);
- const settingsPolicyDoc = usePolicyStore((s) => s.policy);
- const settingsPolicyAppVersion = usePolicyStore((s) => s.appVersion);
- const settingsPolicyState = {
- status: settingsPolicyStatus,
- policy: settingsPolicyDoc,
- appVersion: settingsPolicyAppVersion,
- };
+ const settingsPolicyState = usePolicySnapshot();
const historyLockedByPolicy = lockedLocalHistoryValue(settingsPolicyState) !== null;
const effectiveDataRetentionEnabled = effectiveLocalHistoryEnabled(
settingsPolicyState,
diff --git a/src/components/TranscriptionModelPicker.tsx b/src/components/TranscriptionModelPicker.tsx
index 7750de704..35b89c84b 100644
--- a/src/components/TranscriptionModelPicker.tsx
+++ b/src/components/TranscriptionModelPicker.tsx
@@ -25,8 +25,8 @@ import {
type ModelPickerStyles,
} from "../utils/modelPickerStyles";
import { useSettingsStore } from "../stores/settingsStore";
-import { usePolicyStore, isProviderAllowed } from "../stores/policyStore";
-import { reconcileCloudProviderSelection } from "../stores/policyRules";
+import { isProviderAllowedByPolicy, reconcileCloudProviderSelection } from "../stores/policyRules";
+import { usePolicySnapshot } from "../hooks/usePolicy";
import { getRemoteProviderIcon } from "../utils/providerIcons";
import { createExternalLinkHandler } from "../utils/externalLinks";
import { API_ENDPOINTS, normalizeBaseUrl } from "../config/constants";
@@ -393,17 +393,10 @@ export default function TranscriptionModelPicker({
const { confirmDialog, showConfirmDialog, hideConfirmDialog } = useDialogs();
const colorScheme: ColorScheme = variant === "settings" ? "purple" : "blue";
const styles = useMemo(() => MODEL_PICKER_COLORS[colorScheme], [colorScheme]);
- const policyStatus = usePolicyStore((s) => s.status);
- const policyDoc = usePolicyStore((s) => s.policy);
- const appVersion = usePolicyStore((s) => s.appVersion);
+ const policyState = usePolicySnapshot();
const providerAllowed = useCallback(
- (providerId: string) =>
- isProviderAllowed(
- { status: policyStatus, policy: policyDoc, appVersion },
- "transcription",
- providerId
- ),
- [policyStatus, policyDoc, appVersion]
+ (providerId: string) => isProviderAllowedByPolicy(policyState, "transcription", providerId),
+ [policyState]
);
const cloudProviders = useMemo(
() =>
@@ -413,12 +406,22 @@ export default function TranscriptionModelPicker({
[streamingOnly, providerAllowed]
);
const cloudProviderTabs = useMemo(() => {
- const visibleIds = new Set(cloudProviders.map((p) => p.id));
- if (providerAllowed("custom")) visibleIds.add("custom");
- return CLOUD_PROVIDER_TABS.filter((p) => visibleIds.has(p.id)).map((provider) =>
- provider.id === "custom" ? { ...provider, name: t("transcription.customProvider") } : provider
+ const availableIds = new Set(
+ (streamingOnly ? getStreamingTranscriptionProviders() : getTranscriptionProviders()).map(
+ (p) => p.id
+ )
);
- }, [cloudProviders, providerAllowed, t]);
+ availableIds.add("custom");
+ return CLOUD_PROVIDER_TABS.filter((p) => availableIds.has(p.id)).map((provider) => {
+ const named =
+ provider.id === "custom"
+ ? { ...provider, name: t("transcription.customProvider") }
+ : provider;
+ return providerAllowed(named.id)
+ ? named
+ : { ...named, disabled: true, disabledLabel: t("common.managedByOrg") };
+ });
+ }, [streamingOnly, providerAllowed, t]);
useEffect(() => {
selectedLocalModelRef.current = selectedLocalModel;
diff --git a/src/components/chat/useChatStreaming.ts b/src/components/chat/useChatStreaming.ts
index f36038a1d..ee8277d0f 100644
--- a/src/components/chat/useChatStreaming.ts
+++ b/src/components/chat/useChatStreaming.ts
@@ -7,8 +7,8 @@ import {
isAgentAllowed,
isLlmSelectionAllowed,
isWebSearchAllowed,
- usePolicyStore,
-} from "../../stores/policyStore";
+} from "../../stores/policyRules";
+import { usePolicyStore } from "../../stores/policyStore";
import { getAgentSystemPrompt } from "../../config/prompts";
import { createToolRegistry } from "../../services/tools";
import type { ToolRegistry } from "../../services/tools/ToolRegistry";
@@ -120,8 +120,16 @@ export function useChatStreaming({
: settings.chatAgentProvider;
if (
!isAgentAllowed(policyState) ||
- !isLlmSelectionAllowed(policyState, chatAgentMode, policyProvider)
+ !isLlmSelectionAllowed(policyState, { mode: chatAgentMode, provider: policyProvider })
) {
+ // The user message is already appended; answer it instead of dead-ending silently.
+ const restriction = !isAgentAllowed(policyState)
+ ? t("common.policyAgentRestricted")
+ : t("common.policyAiProcessingRestricted");
+ setMessages((prev) => [
+ ...prev,
+ { id: crypto.randomUUID(), role: "assistant", content: restriction, isStreaming: false },
+ ]);
return;
}
diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsx
index cddbfef2a..f03aff028 100644
--- a/src/components/notes/PersonalNotesView.tsx
+++ b/src/components/notes/PersonalNotesView.tsx
@@ -54,7 +54,7 @@ import { useNotesOnboarding } from "../../hooks/useNotesOnboarding";
import { useTeamSpacesCapability } from "../../hooks/useTeamSpacesCapability";
import { useWorkspaceStore } from "../../stores/workspaceStore";
import { useAuth } from "../../hooks/useAuth";
-import { isTranscriptionContextAllowed, usePolicyStore } from "../../stores/policyStore";
+import { useTranscriptionContextAllowed } from "../../hooks/usePolicy";
import NotesOnboarding from "./NotesOnboarding";
import { isRegenerableNoteTitle } from "../../helpers/regenerableNoteTitle";
import { handleMeetingRecordingRequest } from "../../helpers/meetingRecordingRequest";
@@ -215,9 +215,7 @@ export default function PersonalNotesView({
const sessionDiarizationEnabled = useMeetingRecordingStore((s) => s.sessionDiarizationEnabled);
const sessionExpectedCount = useMeetingRecordingStore((s) => s.sessionExpectedCount);
const userTouchedStepper = useMeetingRecordingStore((s) => s.userTouchedStepper);
- const meetingRecordingAllowed = usePolicyStore((policyState) =>
- isTranscriptionContextAllowed(policyState, useSettingsStore.getState(), "meeting")
- );
+ const meetingRecordingAllowed = useTranscriptionContextAllowed("meeting");
const spaces = useSpaces();
const folders = useFolders();
diff --git a/src/components/notes/ShareNoteDialog.tsx b/src/components/notes/ShareNoteDialog.tsx
index 7c65d3565..c6e8972d0 100644
--- a/src/components/notes/ShareNoteDialog.tsx
+++ b/src/components/notes/ShareNoteDialog.tsx
@@ -33,9 +33,9 @@ import MemberAvatar from "../MemberAvatar";
import {
isShareActionAllowed,
isShareVisibilityAllowed,
- usePolicyStore,
-} from "../../stores/policyStore";
-import type { SharePolicyAction } from "../../stores/policyRules";
+ type SharePolicyAction,
+} from "../../stores/policyRules";
+import { usePolicySnapshot } from "../../hooks/usePolicy";
import { emailDomain, isPersonalEmailDomain } from "../../utils/personalEmailDomains";
import { EMAIL_REGEX } from "../../utils/validation";
import type {
@@ -96,22 +96,14 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD
localIsSharedRef.current = Boolean(note.is_shared);
}, [note.is_shared]);
- const policyStatus = usePolicyStore((s) => s.status);
- const policyDoc = usePolicyStore((s) => s.policy);
- const appVersion = usePolicyStore((s) => s.appVersion);
- const policyState = useMemo(
- () => ({ status: policyStatus, policy: policyDoc, appVersion }),
- [policyStatus, policyDoc, appVersion]
- );
+ const policyState = usePolicySnapshot();
const visibilityAllowed = useCallback(
(visibility: ShareVisibility) => isShareVisibilityAllowed(policyState, visibility),
[policyState]
);
const ownerDomain = useMemo(() => emailDomain(ownerEmail), [ownerEmail]);
- const showDomainOption = Boolean(
- ownerDomain && !isPersonalEmailDomain(ownerDomain) && visibilityAllowed("domain")
- );
+ const showDomainOption = Boolean(ownerDomain && !isPersonalEmailDomain(ownerDomain));
const share = cached?.share ?? null;
const access = cached?.access;
@@ -123,9 +115,9 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD
);
const canManageAccess = access?.can_manage_access ?? true;
const canInvite = canManageAccess && shareActionAllowed("invite");
- const canBeginSharing =
- canManageAccess &&
- (visibilityAllowed("link") || visibilityAllowed("domain") || visibilityAllowed("invited"));
+ const sharingRestrictedByPolicy =
+ !visibilityAllowed("link") && !visibilityAllowed("domain") && !visibilityAllowed("invited");
+ const canBeginSharing = canManageAccess && !sharingRestrictedByPolicy;
const canUseLink =
canManageAccess &&
shareActionAllowed(currentVisibility === "private" ? "create-link" : "copy-link");
@@ -660,6 +652,7 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD
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" />}
@@ -804,6 +797,11 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD
(!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)}
@@ -890,7 +888,11 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD
value={share?.visibility ?? "private"}
ownerDomain={ownerDomain}
showDomainOption={showDomainOption}
- showLinkOption={visibilityAllowed("link")}
+ optionDisabledReasons={{
+ ...(visibilityAllowed("invited") ? {} : { invited: t("common.managedByOrg") }),
+ ...(visibilityAllowed("link") ? {} : { link: t("common.managedByOrg") }),
+ ...(visibilityAllowed("domain") ? {} : { domain: t("common.managedByOrg") }),
+ }}
disabled={loading || !share || !canManageAccess || savingVisibility || linkBusy}
onChange={(v) => void applyVisibility(v)}
/>
@@ -966,6 +968,7 @@ function AccessGrantRow({
grant,
canChangePermission,
canRemove,
+ policyRestrictedReason,
busy,
onPermissionChange,
onRemove,
@@ -973,6 +976,7 @@ function AccessGrantRow({
grant: NoteAccessGrant;
canChangePermission: boolean;
canRemove: boolean;
+ policyRestrictedReason?: string;
busy: boolean;
onPermissionChange: (permission: NoteAccessGrant["permission"]) => void;
onRemove: () => void;
@@ -1038,6 +1042,11 @@ function AccessGrantRow({
>
{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"
@@ -1046,6 +1055,11 @@ function AccessGrantRow({
>
{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>
<DropdownMenuItem
className="text-xs text-red-500"
diff --git a/src/components/notes/ShareVisibilityMenu.tsx b/src/components/notes/ShareVisibilityMenu.tsx
index 71b3a440a..42f493e1a 100644
--- a/src/components/notes/ShareVisibilityMenu.tsx
+++ b/src/components/notes/ShareVisibilityMenu.tsx
@@ -14,7 +14,8 @@ interface ShareVisibilityMenuProps {
value: ShareVisibility;
ownerDomain: string;
showDomainOption: boolean;
- showLinkOption?: boolean;
+ /** Policy-restricted options render disabled with this reason instead of hiding. */
+ optionDisabledReasons?: Partial<Record<ShareVisibility, string>>;
disabled?: boolean;
onChange: (visibility: ShareVisibility) => void;
}
@@ -23,7 +24,7 @@ export default function ShareVisibilityMenu({
value,
ownerDomain,
showDomainOption,
- showLinkOption = true,
+ optionDisabledReasons,
disabled,
onChange,
}: ShareVisibilityMenuProps) {
@@ -63,21 +64,22 @@ export default function ShareVisibilityMenu({
icon={<Users size={13} className="text-foreground/50" />}
label={t("noteEditor.share.dialog.visibility.invited")}
active={value === "invited"}
+ disabledReason={optionDisabledReasons?.invited}
onSelect={() => onChange("invited")}
/>
- {showLinkOption && (
- <VisibilityItem
- icon={<Globe size={13} className="text-foreground/50" />}
- label={t("noteEditor.share.dialog.visibility.link")}
- active={value === "link"}
- onSelect={() => onChange("link")}
- />
- )}
+ <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 && (
<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")}
/>
)}
@@ -120,18 +122,30 @@ function VisibilityItem({
icon,
label,
active,
+ disabledReason,
onSelect,
}: {
icon: React.ReactNode;
label: string;
active: boolean;
+ disabledReason?: string;
onSelect: () => void;
}) {
return (
- <DropdownMenuItem onClick={onSelect} className="text-xs gap-2 py-1.5">
+ <DropdownMenuItem
+ onClick={onSelect}
+ disabled={!!disabledReason}
+ className="text-xs gap-2 py-1.5"
+ >
{icon}
<span className="flex-1">{label}</span>
- {active && <Check size={12} className="text-primary" />}
+ {disabledReason ? (
+ <span className="text-[10px] uppercase tracking-wide text-muted-foreground/70">
+ {disabledReason}
+ </span>
+ ) : (
+ active && <Check size={12} className="text-primary" />
+ )}
</DropdownMenuItem>
);
}
diff --git a/src/components/notes/UploadAudioView.tsx b/src/components/notes/UploadAudioView.tsx
index 7792ee5ed..0511241fe 100644
--- a/src/components/notes/UploadAudioView.tsx
+++ b/src/components/notes/UploadAudioView.tsx
@@ -54,7 +54,9 @@ import { MAX_SPEAKER_COUNT } from "../../constants/speakerDetection.json";
import BatchQueueView from "./BatchQueueView";
import { generateNoteTitle } from "../../utils/generateTitle";
import { getBaseLanguageCode } from "../../utils/languageSupport";
-import { isTranscriptionContextAllowed, usePolicyStore } from "../../stores/policyStore";
+import { isTranscriptionContextAllowed } from "../../stores/policyRules";
+import { usePolicyStore } from "../../stores/policyStore";
+import { useTranscriptionContextAllowed } from "../../hooks/usePolicy";
type UploadState = "idle" | "selected" | "downloading" | "transcribing" | "complete" | "error";
@@ -251,9 +253,7 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
cloudTranscriptionMode,
transcriptionMode,
} = useSettingsStore(useShallow(selectResolvedUploadTranscription));
- const uploadAllowedByPolicy = usePolicyStore((policyState) =>
- isTranscriptionContextAllowed(policyState, getSettings(), "upload")
- );
+ const uploadAllowedByPolicy = useTranscriptionContextAllowed("upload");
const remoteTranscriptionUrl = useSettingsStore((s) => s.remoteTranscriptionUrl);
const remoteTranscriptionModel = useSettingsStore((s) => s.remoteTranscriptionModel);
diff --git a/src/components/settings/DictationAgentSettings.tsx b/src/components/settings/DictationAgentSettings.tsx
index 0bbd69055..734ea1cd0 100644
--- a/src/components/settings/DictationAgentSettings.tsx
+++ b/src/components/settings/DictationAgentSettings.tsx
@@ -1,7 +1,8 @@
import { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import { useSettingsStore } from "../../stores/settingsStore";
-import { usePolicyStore, isAgentAllowed } from "../../stores/policyStore";
+import { isAgentAllowed } from "../../stores/policyRules";
+import { usePolicyStore } from "../../stores/policyStore";
import { useAgentName } from "../../utils/agentName";
import { useDialogs } from "../../hooks/useDialogs";
import { Toggle } from "../ui/toggle";
diff --git a/src/components/settings/InferenceConfigEditor.tsx b/src/components/settings/InferenceConfigEditor.tsx
index c1c7daa44..4539d095d 100644
--- a/src/components/settings/InferenceConfigEditor.tsx
+++ b/src/components/settings/InferenceConfigEditor.tsx
@@ -7,7 +7,7 @@ import {
selectResolvedLLMConfig,
setResolvedLLMConfig,
} from "../../stores/settingsStore";
-import { usePolicyStore, enforceModeOptions, isModeAllowed } from "../../stores/policyStore";
+import { usePolicyModeOptions } from "../../hooks/usePolicy";
import { InferenceModeSelector } from "../ui/SettingsSection";
import type { InferenceModeOption } from "../ui/SettingsSection";
import ReasoningModelSelector from "../ReasoningModelSelector";
@@ -42,13 +42,9 @@ 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 policyStatus = usePolicyStore((s) => s.status);
- const policyDoc = usePolicyStore((s) => s.policy);
- const appVersion = usePolicyStore((s) => s.appVersion);
- const policyState = { status: policyStatus, policy: policyDoc, appVersion };
const prefix = MODE_LABEL_PREFIX[scope];
- const modes: InferenceModeOption[] = enforceModeOptions(
+ const { modes, isModeAllowed } = usePolicyModeOptions<InferenceModeOption>(
[
{
id: "openwhispr",
@@ -83,9 +79,7 @@ export default function InferenceConfigEditor({ scope, onModeChange }: Inference
icon: <Building2 className="w-4 h-4" />,
},
],
- "llm",
- policyState,
- t("common.managedByOrg")
+ "llm"
);
const setField = useCallback(
@@ -98,11 +92,7 @@ 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({ status: policyStatus, policy: policyDoc, appVersion }, "llm", mode)) {
- return;
- }
+ if (!isModeAllowed(mode)) return;
if (mode === "openwhispr" && !isSignedIn) {
startCloudOnboarding();
return;
@@ -125,16 +115,7 @@ export default function InferenceConfigEditor({ scope, onModeChange }: Inference
onModeChange?.(mode);
},
- [
- scope,
- config.mode,
- config.provider,
- isSignedIn,
- onModeChange,
- policyStatus,
- policyDoc,
- appVersion,
- ]
+ [scope, config.mode, config.provider, isSignedIn, onModeChange, isModeAllowed]
);
const setMode = setField("mode");
diff --git a/src/components/settings/MeetingSettings.tsx b/src/components/settings/MeetingSettings.tsx
index b3f218222..dc36dd3be 100644
--- a/src/components/settings/MeetingSettings.tsx
+++ b/src/components/settings/MeetingSettings.tsx
@@ -2,7 +2,7 @@ import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { Cloud, Key, Cpu, Network } from "lucide-react";
import { useSettingsStore } from "../../stores/settingsStore";
-import { usePolicyStore, enforceModeOptions, isModeAllowed } from "../../stores/policyStore";
+import { usePolicyModeOptions } from "../../hooks/usePolicy";
import { InferenceModeSelector, SettingsRow } from "../ui/SettingsSection";
import type { InferenceModeOption } from "../ui/SettingsSection";
import { Toggle } from "../ui/toggle";
@@ -53,12 +53,7 @@ export function MeetingTranscriptionPanel() {
meetingRemoteTranscriptionUrl,
setMeetingRemoteTranscriptionUrl,
} = useSettingsStore();
- const policyStatus = usePolicyStore((state) => state.status);
- const policy = usePolicyStore((state) => state.policy);
- const appVersion = usePolicyStore((state) => state.appVersion);
- const policyState = { status: policyStatus, policy, appVersion };
-
- const transcriptionModes: InferenceModeOption[] = enforceModeOptions(
+ const { modes: transcriptionModes, isModeAllowed } = usePolicyModeOptions<InferenceModeOption>(
[
{
id: "openwhispr",
@@ -87,13 +82,11 @@ export function MeetingTranscriptionPanel() {
icon: <Network className="w-4 h-4" />,
},
],
- "transcription",
- policyState,
- t("common.managedByOrg")
+ "transcription"
);
const handleTranscriptionModeSelect = (mode: InferenceMode) => {
- if (!isModeAllowed(policyState, "transcription", mode)) return;
+ if (!isModeAllowed(mode)) return;
if (mode === "openwhispr" && !isSignedIn) {
startOnboarding();
return;
diff --git a/src/components/settings/UploadSettings.tsx b/src/components/settings/UploadSettings.tsx
index fa80ebcfe..a1c2772ad 100644
--- a/src/components/settings/UploadSettings.tsx
+++ b/src/components/settings/UploadSettings.tsx
@@ -2,7 +2,7 @@ import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { Cloud, Key, Cpu } from "lucide-react";
import { useSettingsStore } from "../../stores/settingsStore";
-import { usePolicyStore, enforceModeOptions, isModeAllowed } from "../../stores/policyStore";
+import { usePolicyModeOptions } from "../../hooks/usePolicy";
import { InferenceModeSelector } from "../ui/SettingsSection";
import type { InferenceModeOption } from "../ui/SettingsSection";
import TranscriptionModelPicker from "../TranscriptionModelPicker";
@@ -32,12 +32,7 @@ export function UploadTranscriptionPanel() {
setUploadCloudTranscriptionBaseUrl,
setUploadCloudTranscriptionMode,
} = useSettingsStore();
- const policyStatus = usePolicyStore((state) => state.status);
- const policy = usePolicyStore((state) => state.policy);
- const appVersion = usePolicyStore((state) => state.appVersion);
- const policyState = { status: policyStatus, policy, appVersion };
-
- const transcriptionModes: InferenceModeOption[] = enforceModeOptions(
+ const { modes: transcriptionModes, isModeAllowed } = usePolicyModeOptions<InferenceModeOption>(
[
{
id: "openwhispr",
@@ -60,13 +55,11 @@ export function UploadTranscriptionPanel() {
icon: <Cpu className="w-4 h-4" />,
},
],
- "transcription",
- policyState,
- t("common.managedByOrg")
+ "transcription"
);
const handleTranscriptionModeSelect = (mode: InferenceMode) => {
- if (!isModeAllowed(policyState, "transcription", mode)) return;
+ if (!isModeAllowed(mode)) return;
if (mode === "openwhispr" && !isSignedIn) {
startOnboarding();
return;
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index 35a4e24d1..6936f4044 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -37,9 +37,9 @@ import {
effectiveLocalHistoryEnabled,
isAgentAllowed,
isTranscriptionContextAllowed,
- usePolicyStore,
-} from "../stores/policyStore";
-import { isTranscriptionSelectionAllowed } from "../stores/policyRules";
+ isTranscriptionSelectionAllowed,
+} from "../stores/policyRules";
+import { usePolicyStore } from "../stores/policyStore";
import { recordCleanupFailure } from "../stores/cleanupFailureStore";
import {
getBatchTranscriptionModel,
@@ -601,6 +601,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
if (isTranscriptionSelectionAllowed(usePolicyStore.getState(), selection)) return;
const error = new Error("Transcription is restricted by your organization.");
error.code = "POLICY_RESTRICTED";
+ error.messageKey = "common.policyTranscriptionRestricted";
throw error;
}
@@ -608,6 +609,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
if (isAgentAllowed(usePolicyStore.getState())) return;
const error = new Error("AI agent use is restricted by your organization.");
error.code = "POLICY_RESTRICTED";
+ error.messageKey = "common.policyAgentRestricted";
throw error;
}
@@ -1522,11 +1524,18 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
throw error;
}
- const { allowOpenAIFallback, useLocalWhisper: isLocalMode } = getSettings();
+ const {
+ allowOpenAIFallback,
+ useLocalWhisper: isLocalMode,
+ cloudTranscriptionProvider,
+ } = getSettings();
+ // A policy-blocked fallback surfaces the local failure, not a policy error.
+ const fallbackAllowedByPolicy = isTranscriptionSelectionAllowed(usePolicyStore.getState(), {
+ mode: "providers",
+ provider: cloudTranscriptionProvider || "openai",
+ });
- if (allowOpenAIFallback && isLocalMode) {
- const fallbackProvider = getSettings().cloudTranscriptionProvider || "openai";
- this.assertTranscriptionSelectionAllowed({ mode: "providers", provider: fallbackProvider });
+ if (allowOpenAIFallback && isLocalMode && fallbackAllowedByPolicy) {
try {
const fallbackResult = await this.processWithOpenAIAPI(audioBlob, metadata);
return { ...fallbackResult, source: "openai-fallback" };
@@ -1616,11 +1625,18 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
throw error;
}
- const { allowOpenAIFallback, useLocalWhisper: isLocalMode } = getSettings();
+ const {
+ allowOpenAIFallback,
+ useLocalWhisper: isLocalMode,
+ cloudTranscriptionProvider,
+ } = getSettings();
+ // A policy-blocked fallback surfaces the local failure, not a policy error.
+ const fallbackAllowedByPolicy = isTranscriptionSelectionAllowed(usePolicyStore.getState(), {
+ mode: "providers",
+ provider: cloudTranscriptionProvider || "openai",
+ });
- if (allowOpenAIFallback && isLocalMode) {
- const fallbackProvider = getSettings().cloudTranscriptionProvider || "openai";
- this.assertTranscriptionSelectionAllowed({ mode: "providers", provider: fallbackProvider });
+ if (allowOpenAIFallback && isLocalMode && fallbackAllowedByPolicy) {
try {
const fallbackResult = await this.processWithOpenAIAPI(audioBlob, metadata);
return { ...fallbackResult, source: "openai-fallback" };
diff --git a/src/helpers/sttConfigRequest.js b/src/helpers/cloudConfigRequest.js
similarity index 79%
rename from src/helpers/sttConfigRequest.js
rename to src/helpers/cloudConfigRequest.js
index 4052ca8c0..104a421a0 100644
--- a/src/helpers/sttConfigRequest.js
+++ b/src/helpers/cloudConfigRequest.js
@@ -1,13 +1,14 @@
const { readPolicyResponseError, toPolicyFailure } = require("./policyResponseError");
-function createSttConfigRequestHandler({
+function createCloudConfigRequestHandler({
getApiUrl,
getAuthHeader,
proxyFetch,
withPolicyHeaders,
logger,
+ configPath,
}) {
- return async function handleSttConfigRequest(event) {
+ return async function handleCloudConfigRequest(event) {
try {
const apiUrl = getApiUrl();
if (!apiUrl) throw new Error("OpenWhispr API URL not configured");
@@ -15,7 +16,7 @@ function createSttConfigRequestHandler({
const authHeader = await getAuthHeader(event);
if (!Object.keys(authHeader).length) throw new Error("Not authenticated");
- const response = await proxyFetch(`${apiUrl}/api/stt-config`, {
+ const response = await proxyFetch(`${apiUrl}/api/${configPath}`, {
headers: withPolicyHeaders(authHeader),
});
if (!response.ok) {
@@ -41,10 +42,10 @@ function createSttConfigRequestHandler({
const data = await response.json();
return { success: true, ...data };
} catch (error) {
- logger?.error?.("STT config fetch error:", error);
+ logger?.error?.(`${configPath} fetch error:`, error);
return toPolicyFailure(error);
}
};
}
-module.exports = { createSttConfigRequestHandler };
+module.exports = { createCloudConfigRequestHandler };
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 932402a62..d44809de6 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -10,7 +10,7 @@ const tokenStore = require("./tokenStore");
const { createCloudApiRequestHandler } = require("./cloudApiRequest");
const { withPolicyRequestHeaders } = require("./policyRequestHeaders");
const { createWorkspacePolicyManager } = require("./workspacePolicyManager");
-const { createSttConfigRequestHandler } = require("./sttConfigRequest");
+const { createCloudConfigRequestHandler } = require("./cloudConfigRequest");
const {
createPolicyResponseError,
readPolicyResponseError,
@@ -4652,12 +4652,21 @@ class IPCHandlers {
broadcast: (snapshot) => broadcastToWindows("workspace-policy-changed", snapshot),
logger: debugLogger,
});
- const handleSttConfigRequest = createSttConfigRequestHandler({
+ const handleSttConfigRequest = createCloudConfigRequestHandler({
getApiUrl,
getAuthHeader,
proxyFetch,
withPolicyHeaders,
logger: debugLogger,
+ configPath: "stt-config",
+ });
+ const handleNoteRecordingConfigRequest = createCloudConfigRequestHandler({
+ getApiUrl,
+ getAuthHeader,
+ proxyFetch,
+ withPolicyHeaders,
+ logger: debugLogger,
+ configPath: "note-recording-config",
});
ipcMain.handle("cloud-transcribe", async (event, audioBuffer, opts = {}) => {
@@ -7657,46 +7666,13 @@ class IPCHandlers {
ipcMain.handle("get-stt-config", handleSttConfigRequest);
- ipcMain.handle(
- "get-workspace-policy",
- async (event, accountId, expectedAuthGeneration, reason) => {
- const authHeaders = await getAuthHeader(event);
- return workspacePolicyManager.getPolicy({
- accountId,
- expectedAuthGeneration,
- authHeaders,
- reason: reason === "recovery" ? "recovery" : "default",
- });
- }
- );
-
- ipcMain.handle("get-note-recording-config", async (event) => {
- try {
- const apiUrl = getApiUrl();
- if (!apiUrl) throw new Error("OpenWhispr API URL not configured");
-
- const authHeader = await getAuthHeader(event);
- if (!Object.keys(authHeader).length) throw new Error("Not authenticated");
-
- const response = await proxyFetch(`${apiUrl}/api/note-recording-config`, {
- headers: authHeader,
- });
-
- if (!response.ok) {
- if (response.status === 401) {
- return { success: false, error: "Session expired", code: "AUTH_EXPIRED" };
- }
- throw new Error(`API error: ${response.status}`);
- }
-
- const data = await response.json();
- return { success: true, ...data };
- } catch (error) {
- debugLogger.error("Note recording config fetch error:", error);
- return null;
- }
+ ipcMain.handle("get-workspace-policy", async (event, accountId, expectedAuthGeneration) => {
+ const authHeaders = await getAuthHeader(event);
+ return workspacePolicyManager.getPolicy({ accountId, expectedAuthGeneration, authHeaders });
});
+ ipcMain.handle("get-note-recording-config", handleNoteRecordingConfigRequest);
+
ipcMain.handle("transcribe-audio-file-cloud", async (event, filePath, opts = {}) => {
const requestId = typeof opts?.requestId === "string" ? opts.requestId : null;
const controller = new AbortController();
diff --git a/src/helpers/meetingRecordingRequest.ts b/src/helpers/meetingRecordingRequest.ts
index 1cda8be96..0edc58407 100644
--- a/src/helpers/meetingRecordingRequest.ts
+++ b/src/helpers/meetingRecordingRequest.ts
@@ -13,7 +13,10 @@ export async function handleMeetingRecordingRequest({
restoreFromMeetingMode,
onHandled,
}: MeetingRecordingRequestOptions): Promise<void> {
- const accepted = await startRecording(args);
- if (!accepted) await restoreFromMeetingMode();
- onHandled();
+ try {
+ const accepted = await startRecording(args);
+ if (!accepted) await restoreFromMeetingMode();
+ } finally {
+ onHandled();
+ }
}
diff --git a/src/helpers/workspacePolicyManager.js b/src/helpers/workspacePolicyManager.js
index 65addd26b..d3369bd73 100644
--- a/src/helpers/workspacePolicyManager.js
+++ b/src/helpers/workspacePolicyManager.js
@@ -62,18 +62,21 @@ function createWorkspacePolicyManager({
const inFlight = new Map();
const successfulRefreshes = new Map();
const lastAttempts = new Map();
- const lastRecoveryAttempts = new Map();
const managedPolicyRequired = new Set();
let revision = 0;
function captureIdentity(request = {}) {
const tokenState = tokenStore.getState();
if (
- request.expectedAuthGeneration !== undefined &&
- (!Number.isSafeInteger(request.expectedAuthGeneration) ||
- request.expectedAuthGeneration < 0 ||
- request.expectedAuthGeneration !== tokenState.generation)
+ !Number.isSafeInteger(request.expectedAuthGeneration) ||
+ request.expectedAuthGeneration < 0
) {
+ throw authError(
+ "Authenticated policy request has no validated credential generation",
+ "AUTH_CONTEXT_UNVALIDATED"
+ );
+ }
+ if (request.expectedAuthGeneration !== tokenState.generation) {
throw authError("Authentication context changed before policy request");
}
const apiUrl = getApiUrl();
@@ -222,9 +225,10 @@ function createWorkspacePolicyManager({
function acceptSuccessfulResponse(identity, data, status) {
managedPolicyRequired.delete(identityKey(identity));
- const result = accept(identity, data, status);
- if (result.status !== "current") successfulRefreshes.set(identityKey(identity), now());
- return result;
+ // A stale (anti-downgraded) response is still a successful server round
+ // trip; recording it keeps the refresh TTL engaged behind lagging replicas.
+ successfulRefreshes.set(identityKey(identity), now());
+ return accept(identity, data, status);
}
async function fetchPolicy(identity) {
@@ -288,21 +292,19 @@ function createWorkspacePolicyManager({
try {
assertIdentityCurrent(identity);
} catch (authContextError) {
- return {
- success: false,
- status: "error",
- code: authContextError.code,
- error: authContextError.message,
- };
+ return errorSnapshot(identity, authContextError.code, authContextError.message);
}
const requiresManagedFallback = error?.code === "POLICY_UNRESOLVABLE";
if (requiresManagedFallback) markManagedPolicyRequired(identity, error.message);
+ // Prefer the in-memory verdict; the disk cache only backs it up, so an
+ // unreadable cache file must not discard a valid session snapshot.
+ const current = snapshots.get(identityKey(identity));
+ if (current && (!requiresManagedFallback || current.data.managed)) {
+ return publicSnapshot(identity, current.data, "cached", current.revision);
+ }
const cached = cachedData(identity);
if (cached && (!requiresManagedFallback || cached.managed)) {
- const key = identityKey(identity);
- const current = snapshots.get(key);
- if (current) return publicSnapshot(identity, current.data, "cached", current.revision);
return accept(identity, cached, "cached");
}
logger?.warn?.("Workspace policy unavailable", { error: error?.message });
@@ -321,6 +323,9 @@ function createWorkspacePolicyManager({
return {
success: false,
status: "error",
+ revision,
+ accountId: normalizeAccountId(request?.accountId),
+ authGeneration: tokenStore.getState()?.generation ?? null,
code: error.code || "POLICY_UNAVAILABLE",
error: error.message,
};
@@ -352,15 +357,8 @@ function createWorkspacePolicyManager({
}
const lastAttempt = lastAttempts.get(key);
const attemptAge = lastAttempt === undefined ? null : now() - lastAttempt;
- const lastRecoveryAttempt = lastRecoveryAttempts.get(key);
- const recoveryAttemptAge =
- lastRecoveryAttempt === undefined ? null : now() - lastRecoveryAttempt;
const attemptIsThrottled =
- request?.reason === "recovery"
- ? recoveryAttemptAge !== null &&
- recoveryAttemptAge >= 0 &&
- recoveryAttemptAge < minimumAttemptIntervalMs
- : attemptAge !== null && attemptAge >= 0 && attemptAge < minimumAttemptIntervalMs;
+ attemptAge !== null && attemptAge >= 0 && attemptAge < minimumAttemptIntervalMs;
if (attemptIsThrottled) {
if (requiresManagedPolicy(identity)) {
return errorSnapshot(
@@ -372,16 +370,13 @@ function createWorkspacePolicyManager({
if (current) return publicSnapshot(identity, current.data, "cached", current.revision);
const cached = cachedData(identity);
if (cached) return accept(identity, cached, "cached");
- return {
- success: false,
- status: "error",
- code: "POLICY_RETRY_THROTTLED",
- error: "Workspace policy refresh is rate limited",
- };
+ return errorSnapshot(
+ identity,
+ "POLICY_RETRY_THROTTLED",
+ "Workspace policy refresh is rate limited"
+ );
}
- const attemptStartedAt = now();
- lastAttempts.set(key, attemptStartedAt);
- if (request?.reason === "recovery") lastRecoveryAttempts.set(key, attemptStartedAt);
+ lastAttempts.set(key, now());
const pending = fetchPolicy(identity).finally(() => {
if (inFlight.get(key) === pending) inFlight.delete(key);
});
diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.js
index 37fd23ec4..5449562e7 100644
--- a/src/hooks/useAudioRecording.js
+++ b/src/hooks/useAudioRecording.js
@@ -7,11 +7,8 @@ import { getSettings } from "../stores/settingsStore";
import { expandSnippets } from "../utils/snippets";
import { getRecordingErrorTitle, getRecordingErrorDescription } from "../utils/recordingErrors";
import { isAccessibilitySkipped } from "../utils/permissions";
-import {
- isAgentAllowed,
- isTranscriptionContextAllowed,
- usePolicyStore,
-} from "../stores/policyStore";
+import { isAgentAllowed, isTranscriptionContextAllowed } from "../stores/policyRules";
+import { usePolicyStore } from "../stores/policyStore";
// Maps a failed selection-replacement code to its `selectionEditing.*` toast
// detail key; unlisted codes fall back to the generic "unavailable" message.
diff --git a/src/hooks/usePolicy.ts b/src/hooks/usePolicy.ts
new file mode 100644
index 000000000..e71b849f7
--- /dev/null
+++ b/src/hooks/usePolicy.ts
@@ -0,0 +1,52 @@
+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 {
+ enforceModeOptions,
+ getTranscriptionSelection,
+ isModeAllowedByPolicy,
+ isTranscriptionSelectionAllowed,
+ type PolicyDecisionSnapshot,
+ type TranscriptionPolicyContext,
+} from "../stores/policyRules";
+import type { InferenceMode } from "../types/electron";
+import type { PolicyScope } from "../types/policy";
+
+/** The minimal reactive snapshot consumed by the pure policy rules. */
+export function usePolicySnapshot(): PolicyDecisionSnapshot {
+ const status = usePolicyStore((state) => state.status);
+ const policy = usePolicyStore((state) => state.policy);
+ const appVersion = usePolicyStore((state) => state.appVersion);
+ return useMemo(() => ({ status, policy, appVersion }), [status, policy, appVersion]);
+}
+
+/** 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)));
+ return isTranscriptionSelectionAllowed(snapshot, selection);
+}
+
+interface PolicyModeOptions<T> {
+ modes: T[];
+ /**
+ * "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.
+ */
+ 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();
+ const snapshot = usePolicySnapshot();
+ return {
+ modes: enforceModeOptions(options, scope, snapshot, t("common.managedByOrg")),
+ isModeAllowed: (mode: InferenceMode) => isModeAllowedByPolicy(snapshot, scope, mode),
+ };
+}
diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.ts
index ae15ffba2..e5d0d24ef 100644
--- a/src/hooks/useSettings.ts
+++ b/src/hooks/useSettings.ts
@@ -9,7 +9,8 @@ import type {
SelfHostedType,
} from "../types/electron";
import type { Snippet } from "../utils/snippets";
-import { effectiveAudioRetentionDays, usePolicyStore } from "../stores/policyStore";
+import { effectiveAudioRetentionDays } from "../stores/policyRules";
+import { usePolicyStore } from "../stores/policyStore";
export interface TranscriptionSettings {
uiLanguage: string;
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 0d200c2be..9c7755260 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -169,7 +169,10 @@
"copy": "Kopieren",
"copied": "Kopiert",
"done": "Fertig",
- "skip": "Überspringen"
+ "skip": "Überspringen",
+ "policyAiProcessingRestricted": "Die KI-Verarbeitung ist durch Ihre Organisation eingeschränkt.",
+ "policyAgentRestricted": "Die Nutzung des KI-Agenten ist durch Ihre Organisation eingeschränkt.",
+ "policyTranscriptionRestricted": "Die Transkription ist durch Ihre Organisation eingeschränkt."
},
"onboarding": {
"steps": {
@@ -2763,7 +2766,8 @@
"title": "Besprechungsnotizen",
"description": "Transkriptionen und strukturierte Zusammenfassungen",
"comingSoon": "Demnächst verfügbar",
- "back": "Zurück"
+ "back": "Zurück",
+ "restrictedByOrg": "Die Transkription von Besprechungen ist durch Ihre Organisation eingeschränkt."
},
"meetingPill": {
"returnToNote": "Zurück zur Aufnahme",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index aabc731c7..5b231c3e6 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -169,7 +169,10 @@
"copy": "Copy",
"copied": "Copied",
"done": "Done",
- "skip": "Skip"
+ "skip": "Skip",
+ "policyAiProcessingRestricted": "AI processing is restricted by your organization.",
+ "policyAgentRestricted": "AI agent use is restricted by your organization.",
+ "policyTranscriptionRestricted": "Transcription is restricted by your organization."
},
"onboarding": {
"steps": {
@@ -2763,7 +2766,8 @@
"title": "Meeting Notes",
"description": "Transcriptions & structured summaries",
"comingSoon": "Coming Soon",
- "back": "Back"
+ "back": "Back",
+ "restrictedByOrg": "Meeting transcription is restricted by your organization."
},
"meetingPill": {
"returnToNote": "Return to recording",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index bca62e9ed..31949f2c4 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -169,7 +169,10 @@
"copy": "Copiar",
"copied": "Copiado",
"done": "Listo",
- "skip": "Omitir"
+ "skip": "Omitir",
+ "policyAiProcessingRestricted": "El procesamiento con IA está restringido por tu organización.",
+ "policyAgentRestricted": "El uso del agente de IA está restringido por tu organización.",
+ "policyTranscriptionRestricted": "La transcripción está restringida por tu organización."
},
"onboarding": {
"steps": {
@@ -2620,7 +2623,8 @@
"title": "Notas de reunión",
"description": "Transcripciones y resúmenes estructurados",
"comingSoon": "Próximamente",
- "back": "Atrás"
+ "back": "Atrás",
+ "restrictedByOrg": "La transcripción de reuniones está restringida por tu organización."
},
"meetingPill": {
"returnToNote": "Volver a la grabación",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index de01738c7..040449398 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -169,7 +169,10 @@
"copy": "Copier",
"copied": "Copié",
"done": "Terminé",
- "skip": "Passer"
+ "skip": "Passer",
+ "policyAiProcessingRestricted": "Le traitement par IA est restreint par votre organisation.",
+ "policyAgentRestricted": "L’utilisation de l’agent IA est restreinte par votre organisation.",
+ "policyTranscriptionRestricted": "La transcription est restreinte par votre organisation."
},
"onboarding": {
"steps": {
@@ -2763,7 +2766,8 @@
"title": "Notes de réunion",
"description": "Transcriptions et résumés structurés",
"comingSoon": "Bientôt disponible",
- "back": "Retour"
+ "back": "Retour",
+ "restrictedByOrg": "La transcription des réunions est restreinte par votre organisation."
},
"meetingPill": {
"returnToNote": "Revenir à l'enregistrement",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 10eab2b84..b74d41d29 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -169,7 +169,10 @@
"copy": "Copia",
"copied": "Copiato",
"done": "Fatto",
- "skip": "Salta"
+ "skip": "Salta",
+ "policyAiProcessingRestricted": "L’elaborazione con IA è limitata dalla tua organizzazione.",
+ "policyAgentRestricted": "L’uso dell’agente IA è limitato dalla tua organizzazione.",
+ "policyTranscriptionRestricted": "La trascrizione è limitata dalla tua organizzazione."
},
"onboarding": {
"steps": {
@@ -2572,7 +2575,8 @@
"title": "Note delle riunioni",
"description": "Trascrizioni e riassunti strutturati",
"comingSoon": "Prossimamente",
- "back": "Indietro"
+ "back": "Indietro",
+ "restrictedByOrg": "La trascrizione delle riunioni è limitata dalla tua organizzazione."
},
"meetingPill": {
"returnToNote": "Torna alla registrazione",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index c6005e1fd..4a8b91256 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -169,7 +169,10 @@
"copy": "コピー",
"copied": "コピーしました",
"done": "完了",
- "skip": "スキップ"
+ "skip": "スキップ",
+ "policyAiProcessingRestricted": "AI処理は組織によって制限されています。",
+ "policyAgentRestricted": "AIエージェントの使用は組織によって制限されています。",
+ "policyTranscriptionRestricted": "文字起こしは組織によって制限されています。"
},
"onboarding": {
"steps": {
@@ -2556,7 +2559,8 @@
"title": "議事録",
"description": "文字起こしと構造化されたサマリー",
"comingSoon": "近日公開",
- "back": "戻る"
+ "back": "戻る",
+ "restrictedByOrg": "会議の文字起こしは組織によって制限されています。"
},
"meetingPill": {
"returnToNote": "録音に戻る",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 83f4453a5..c206d007d 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -148,7 +148,10 @@
"copy": "Copiar",
"copied": "Copiado",
"done": "Listo",
- "skip": "Pular"
+ "skip": "Pular",
+ "policyAiProcessingRestricted": "O processamento de IA está restrito pela sua organização.",
+ "policyAgentRestricted": "O uso do agente de IA está restrito pela sua organização.",
+ "policyTranscriptionRestricted": "A transcrição está restrita pela sua organização."
},
"onboarding": {
"steps": {
@@ -2572,7 +2575,8 @@
"title": "Notas de reunião",
"description": "Transcrições e resumos estruturados",
"comingSoon": "Em breve",
- "back": "Voltar"
+ "back": "Voltar",
+ "restrictedByOrg": "A transcrição de reuniões está restrita pela sua organização."
},
"meetingPill": {
"returnToNote": "Voltar à gravação",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 9296b24b7..a9e48d122 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -169,7 +169,10 @@
"copy": "Kopieren",
"copied": "Kopiert",
"done": "Fertig",
- "skip": "Пропустить"
+ "skip": "Пропустить",
+ "policyAiProcessingRestricted": "Обработка ИИ ограничена вашей организацией.",
+ "policyAgentRestricted": "Использование ИИ-агента ограничено вашей организацией.",
+ "policyTranscriptionRestricted": "Транскрипция ограничена вашей организацией."
},
"onboarding": {
"steps": {
@@ -2594,7 +2597,8 @@
"title": "Заметки со встреч",
"description": "Транскрипции и структурированные резюме",
"comingSoon": "Скоро",
- "back": "Назад"
+ "back": "Назад",
+ "restrictedByOrg": "Транскрипция встреч ограничена вашей организацией."
},
"meetingPill": {
"returnToNote": "Вернуться к записи",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index faf403b29..4cbffd7ab 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -169,7 +169,10 @@
"copy": "复制",
"copied": "已复制",
"done": "完成",
- "skip": "跳过"
+ "skip": "跳过",
+ "policyAiProcessingRestricted": "AI 处理已被您的组织限制。",
+ "policyAgentRestricted": "AI 智能体的使用已被您的组织限制。",
+ "policyTranscriptionRestricted": "转录已被您的组织限制。"
},
"onboarding": {
"steps": {
@@ -2572,7 +2575,8 @@
"title": "会议笔记",
"description": "转录与结构化摘要",
"comingSoon": "即将推出",
- "back": "返回"
+ "back": "返回",
+ "restrictedByOrg": "会议转录已被您的组织限制。"
},
"meetingPill": {
"returnToNote": "返回到录音",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 339d7117e..54a234a78 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -169,7 +169,10 @@
"copy": "複製",
"copied": "已複製",
"done": "完成",
- "skip": "略過"
+ "skip": "略過",
+ "policyAiProcessingRestricted": "AI 處理已被您的組織限制。",
+ "policyAgentRestricted": "AI 代理的使用已被您的組織限制。",
+ "policyTranscriptionRestricted": "轉錄已被您的組織限制。"
},
"onboarding": {
"steps": {
@@ -2572,7 +2575,8 @@
"title": "會議筆記",
"description": "轉錄與結構化摘要",
"comingSoon": "即將推出",
- "back": "返回"
+ "back": "返回",
+ "restrictedByOrg": "會議轉錄已被您的組織限制。"
},
"meetingPill": {
"returnToNote": "返回到錄音",
diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.ts
index fa73feb34..8f1124516 100644
--- a/src/services/ReasoningService.ts
+++ b/src/services/ReasoningService.ts
@@ -24,7 +24,7 @@ import { detectEndpointDialect } from "./ai/thinkingSuppressionDialects";
import { extractApiErrorMessage } from "./ai/apiErrorMessage";
import { clearTinfoilClientCache } from "./ai/tinfoilClient";
import { resolveChatRoute } from "../helpers/chatRouting";
-import { isAgentAllowed, isLlmSelectionAllowed, usePolicyStore } from "../stores/policyStore";
+import { assertAgentAllowedByPolicy, assertReasoningAllowedByPolicy } from "./reasoningPolicy";
import type { InferenceMode } from "../types/electron";
export type ToolMetadata = Record<string, unknown> | Array<Record<string, unknown>>;
@@ -58,17 +58,8 @@ function resolveLlmDispatchMode(
return "providers";
}
-function assertReasoningAllowedByPolicy(provider: string, mode: InferenceMode): void {
- if (!isLlmSelectionAllowed(usePolicyStore.getState(), mode, provider)) {
- throw new Error("AI processing is restricted by your organization.");
- }
-}
-
function assertAgentSessionAllowedByPolicy(provider: string, mode: InferenceMode): void {
- const policyState = usePolicyStore.getState();
- if (!isAgentAllowed(policyState)) {
- throw new Error("AI agent use is restricted by your organization.");
- }
+ assertAgentAllowedByPolicy();
assertReasoningAllowedByPolicy(provider, mode);
}
@@ -377,9 +368,7 @@ class ReasoningService extends BaseReasoningService {
const providerId = isLanCleanup
? "lan"
: resolveInferenceProvider(config.provider, trimmedModel);
- if (config.requiresAgent && !isAgentAllowed(usePolicyStore.getState())) {
- throw new Error("AI agent use is restricted by your organization.");
- }
+ if (config.requiresAgent) assertAgentAllowedByPolicy();
assertReasoningAllowedByPolicy(providerId, resolveLlmDispatchMode(providerId, config));
if (!trimmedModel && providerId !== "openwhispr" && providerId !== "lan") {
diff --git a/src/services/SyncService.ts b/src/services/SyncService.ts
index 26365ac8f..ecdcbee97 100644
--- a/src/services/SyncService.ts
+++ b/src/services/SyncService.ts
@@ -26,7 +26,8 @@ import {
} from "../lib/teamSpacesCapability";
import { readIsSubscribed, subscribeIsSubscribed } from "../lib/subscriptionFlag";
import { readNoteConflictIds } from "../lib/noteConflictRegistry";
-import { isCloudBackupAllowed, usePolicyStore } from "../stores/policyStore";
+import { isCloudBackupAllowed } from "../stores/policyRules";
+import { usePolicyStore } from "../stores/policyStore";
import {
buildNoteCreatePayload,
buildNoteUpdatePayload,
diff --git a/src/services/reasoningPolicy.ts b/src/services/reasoningPolicy.ts
new file mode 100644
index 000000000..5ef06cff4
--- /dev/null
+++ b/src/services/reasoningPolicy.ts
@@ -0,0 +1,16 @@
+import i18n from "../i18n";
+import { isAgentAllowed, isLlmSelectionAllowed } from "../stores/policyRules";
+import { usePolicyStore } from "../stores/policyStore";
+import type { InferenceMode } from "../types/electron";
+
+export function assertReasoningAllowedByPolicy(provider: string, mode: InferenceMode): void {
+ if (!isLlmSelectionAllowed(usePolicyStore.getState(), { mode, provider })) {
+ throw new Error(i18n.t("common.policyAiProcessingRestricted"));
+ }
+}
+
+export function assertAgentAllowedByPolicy(): void {
+ if (!isAgentAllowed(usePolicyStore.getState())) {
+ throw new Error(i18n.t("common.policyAgentRestricted"));
+ }
+}
diff --git a/src/stores/batchQueueStore.ts b/src/stores/batchQueueStore.ts
index 24946d73e..ca2466ab8 100644
--- a/src/stores/batchQueueStore.ts
+++ b/src/stores/batchQueueStore.ts
@@ -3,7 +3,8 @@ import { transcribeFileWithSpeakers } from "../services/fileTranscription";
import type { FileTranscriptionConfig, DiarizationSettings } from "../services/fileTranscription";
import { DOWNLOAD_ERROR_KEYS } from "../components/notes/shared";
import { getSettings } from "./settingsStore";
-import { isTranscriptionContextAllowed, usePolicyStore } from "./policyStore";
+import { isTranscriptionContextAllowed } from "./policyRules";
+import { usePolicyStore } from "./policyStore";
export type QueueItemStatus = "queued" | "downloading" | "transcribing" | "done" | "error";
diff --git a/src/stores/meetingRecordingStore.ts b/src/stores/meetingRecordingStore.ts
index cbad13624..6f6407ab3 100644
--- a/src/stores/meetingRecordingStore.ts
+++ b/src/stores/meetingRecordingStore.ts
@@ -20,7 +20,8 @@ import {
MAX_SPEAKER_COUNT,
} from "../constants/speakerDetection.json";
import logger from "../utils/logger";
-import { isTranscriptionContextAllowed, usePolicyStore } from "./policyStore";
+import { isTranscriptionContextAllowed } from "./policyRules";
+import { usePolicyStore } from "./policyStore";
import {
lockTranscriptSpeaker,
normalizeTranscriptSegment,
@@ -725,7 +726,7 @@ export async function startRecording(args: StartRecordingArgs): Promise<boolean>
if (!isTranscriptionContextAllowed(usePolicyStore.getState(), getSettings(), "meeting")) {
logger.warn("Meeting recording blocked by workspace policy", {}, "meeting");
useMeetingRecordingStore.setState({
- error: "Meeting transcription is restricted by your organization.",
+ error: "policyRestricted",
});
return false;
}
diff --git a/src/stores/policyRules.ts b/src/stores/policyRules.ts
index 3fd9ca9a5..53c9ac26d 100644
--- a/src/stores/policyRules.ts
+++ b/src/stores/policyRules.ts
@@ -1,5 +1,6 @@
import type { InferenceMode, ShareVisibility } from "../types/electron";
import type { OrgPolicy, PolicyScope } from "../types/policy";
+import type { SettingsState } from "./settingsStore";
import { compareAppVersions } from "../utils/version.ts";
export type PolicyStatus = "idle" | "loading" | "managed" | "unmanaged" | "error";
@@ -10,6 +11,10 @@ export interface PolicyDecisionSnapshot {
appVersion: string | null;
}
+function managedPolicy(state: PolicyDecisionSnapshot): OrgPolicy | null {
+ return state.status === "managed" && state.policy ? state.policy : null;
+}
+
export function isPolicyActionAllowed(state: PolicyDecisionSnapshot): boolean {
if (state.status === "idle" || state.status === "unmanaged") return true;
if (state.status !== "managed" || !state.policy) return false;
@@ -18,77 +23,95 @@ export function isPolicyActionAllowed(state: PolicyDecisionSnapshot): boolean {
return compareAppVersions(state.appVersion, state.policy.minAppVersion) >= 0;
}
-export type DesktopPolicyAction =
- | "capture"
- | "inference"
- | "agent"
- | "sharing"
- | "cloud-backup"
- | "history"
- | "retention-settings"
- | "updater"
- | "diagnostics"
- | "permissions"
- | "account"
- | "sign-out";
-
-const RECOVERY_ACTIONS = new Set<DesktopPolicyAction>([
- "history",
- "retention-settings",
- "updater",
- "diagnostics",
- "permissions",
- "account",
- "sign-out",
-]);
-
-export function isDesktopActionAllowed(
+/** Whether the org's minimum app version blocks this build (drives the update banner). */
+export function isUpdateRequiredByOrg(state: PolicyDecisionSnapshot): boolean {
+ const minAppVersion = managedPolicy(state)?.minAppVersion;
+ if (!minAppVersion || !state.appVersion) return false;
+ return compareAppVersions(state.appVersion, minAppVersion) < 0;
+}
+
+/** Fail closed while unresolved, allow unmanaged users, else ask the policy. */
+function managedPolicyDecision(
state: PolicyDecisionSnapshot,
- action: DesktopPolicyAction
+ decide: (policy: OrgPolicy) => boolean
): boolean {
- return RECOVERY_ACTIONS.has(action) || isPolicyActionAllowed(state);
+ if (!isPolicyActionAllowed(state)) return false;
+ const policy = managedPolicy(state);
+ return policy ? decide(policy) : true;
}
export function effectiveLocalHistoryEnabled(
state: PolicyDecisionSnapshot,
personalPreference: boolean
): boolean {
- if (state.status !== "managed" || !state.policy) return personalPreference;
- const mode = state.policy.dataRetention.localHistoryMode;
+ return lockedLocalHistoryValue(state) ?? personalPreference;
+}
+
+/** The org-forced local history value, or null when the user may choose. */
+export function lockedLocalHistoryValue(state: PolicyDecisionSnapshot): boolean | null {
+ const mode = managedPolicy(state)?.dataRetention.localHistoryMode;
if (mode === "always_on") return true;
if (mode === "always_off") return false;
- return personalPreference;
+ return null;
}
export function effectiveAudioRetentionDays(
state: PolicyDecisionSnapshot,
personalPreference: number
): number {
- if (personalPreference === 0 || state.status !== "managed" || !state.policy) {
- return personalPreference;
- }
- const maximumDays = state.policy.dataRetention.audioRetentionMaxDays;
+ if (personalPreference === 0) return personalPreference;
+ const maximumDays = maxAudioRetentionDays(state);
return maximumDays === null ? personalPreference : Math.min(personalPreference, maximumDays);
}
+/** The org cap on audio retention days, or null when uncapped. */
+export function maxAudioRetentionDays(state: PolicyDecisionSnapshot): number | null {
+ return managedPolicy(state)?.dataRetention.audioRetentionMaxDays ?? null;
+}
+
+/** Whether a transcription/LLM mode is allowed. Unmanaged users allow everything. */
export function isModeAllowedByPolicy(
state: PolicyDecisionSnapshot,
scope: PolicyScope,
mode: InferenceMode
): boolean {
- if (!isPolicyActionAllowed(state)) return false;
- if (state.status !== "managed" || !state.policy) return true;
- return state.policy[scope].allowedModes.includes(mode);
+ return managedPolicyDecision(state, (policy) => policy[scope].allowedModes.includes(mode));
}
+/** Whether a BYOK provider id is allowed for a scope. Unmanaged users allow everything. */
export function isProviderAllowedByPolicy(
state: PolicyDecisionSnapshot,
scope: PolicyScope,
providerId: string
): boolean {
- if (!isPolicyActionAllowed(state)) return false;
- if (state.status !== "managed" || !state.policy) return true;
- return state.policy[scope].allowedByokProviders.includes(providerId);
+ return managedPolicyDecision(state, (policy) =>
+ policy[scope].allowedByokProviders.includes(providerId)
+ );
+}
+
+/** Whether an enterprise-cloud provider id is allowed. Unmanaged users allow everything. */
+export function isEnterpriseProviderAllowed(
+ state: PolicyDecisionSnapshot,
+ providerId: string
+): boolean {
+ return managedPolicyDecision(state, (policy) =>
+ policy.llm.allowedEnterpriseProviders.includes(providerId)
+ );
+}
+
+/** Whether the AI agent (dictation, voice, and chat) is allowed. */
+export function isAgentAllowed(state: PolicyDecisionSnapshot): boolean {
+ return managedPolicyDecision(state, (policy) => policy.features.agentEnabled);
+}
+
+/** Whether the agent's web_search tool is allowed. */
+export function isWebSearchAllowed(state: PolicyDecisionSnapshot): boolean {
+ return managedPolicyDecision(state, (policy) => policy.features.webSearchEnabled);
+}
+
+/** Whether cloud backup/sync is allowed. */
+export function isCloudBackupAllowed(state: PolicyDecisionSnapshot): boolean {
+ return managedPolicyDecision(state, (policy) => policy.dataRetention.cloudBackupAllowed);
}
export interface LlmSelection {
@@ -105,8 +128,7 @@ export function isLlmSelectionAllowed(
return isProviderAllowedByPolicy(state, "llm", selection.provider);
}
if (selection.mode === "enterprise") {
- if (state.status !== "managed" || !state.policy) return true;
- return state.policy.llm.allowedEnterpriseProviders.includes(selection.provider);
+ return isEnterpriseProviderAllowed(state, selection.provider);
}
return true;
}
@@ -125,16 +147,49 @@ export function isTranscriptionSelectionAllowed(
return isProviderAllowedByPolicy(state, "transcription", selection.provider);
}
+export type TranscriptionPolicyContext = "dictation" | "meeting" | "upload";
+
+export function getTranscriptionSelection(
+ settings: SettingsState,
+ context: TranscriptionPolicyContext
+): TranscriptionSelection {
+ if (context === "meeting") {
+ return {
+ mode: settings.meetingTranscriptionMode,
+ provider: settings.meetingCloudTranscriptionProvider || settings.cloudTranscriptionProvider,
+ };
+ }
+ if (context === "upload") {
+ return {
+ mode: settings.uploadTranscriptionMode,
+ provider: settings.uploadCloudTranscriptionProvider || settings.cloudTranscriptionProvider,
+ };
+ }
+ return {
+ mode: settings.transcriptionMode,
+ provider: settings.cloudTranscriptionProvider,
+ };
+}
+
+export function isTranscriptionContextAllowed(
+ state: PolicyDecisionSnapshot,
+ settings: SettingsState,
+ context: TranscriptionPolicyContext
+): boolean {
+ return isTranscriptionSelectionAllowed(state, getTranscriptionSelection(settings, context));
+}
+
+/** Whether a note share visibility is allowed under the org's external-sharing mode. */
export function isShareVisibilityAllowed(
state: PolicyDecisionSnapshot,
visibility: ShareVisibility
): boolean {
- if (!isPolicyActionAllowed(state)) return false;
- if (state.status !== "managed" || !state.policy) return true;
- const mode = state.policy.sharing.externalLinkSharing;
- if (mode === "allowed") return true;
- if (mode === "domain_only") return visibility === "private" || visibility === "domain";
- return visibility === "private";
+ return managedPolicyDecision(state, (policy) => {
+ const mode = policy.sharing.externalLinkSharing;
+ if (mode === "allowed") return true;
+ if (mode === "domain_only") return visibility === "private" || visibility === "domain";
+ return visibility === "private";
+ });
}
export type SharePolicyAction =
@@ -183,6 +238,18 @@ 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[] {
+ if (state.status === "idle" || state.status === "unmanaged") return options;
+ return options.map((option) =>
+ isModeAllowedByPolicy(state, scope, option.id)
+ ? option
+ : { ...option, disabled: true, badge: managedBadge }
+ );
+}
+
interface CloudProviderOption {
id: string;
models?: ReadonlyArray<{ id: string }>;
diff --git a/src/stores/policyStore.ts b/src/stores/policyStore.ts
index f34a75dd2..ee7ac8069 100644
--- a/src/stores/policyStore.ts
+++ b/src/stores/policyStore.ts
@@ -1,46 +1,22 @@
import { create } from "zustand";
import logger from "../utils/logger";
-import type { SettingsState } from "./settingsStore";
-import type { InferenceMode, ShareVisibility } from "../types/electron";
-import type { OrgPolicy, PolicyScope } from "../types/policy";
+import type { OrgPolicy } from "../types/policy";
import {
POLICY_SUCCESS_REFRESH_MS,
resolvedPolicyRefreshIdentity,
shouldAcceptPolicySnapshot,
shouldPreserveResolvedPolicyOnFailure,
} from "./policyLifecycle";
-import {
- effectiveAudioRetentionDays as effectiveAudioRetentionDaysRule,
- effectiveLocalHistoryEnabled as effectiveLocalHistoryEnabledRule,
- isModeAllowedByPolicy,
- isDesktopActionAllowed as isDesktopActionAllowedRule,
- isLlmSelectionAllowed as isLlmSelectionAllowedRule,
- isPolicyActionAllowed as isPolicyActionAllowedRule,
- isProviderAllowedByPolicy,
- isShareActionAllowed as isShareActionAllowedRule,
- isShareVisibilityAllowed as isShareVisibilityAllowedRule,
- isTranscriptionSelectionAllowed,
- type PolicyDecisionSnapshot,
- type DesktopPolicyAction,
- type SharePolicyAction,
-} from "./policyRules";
+import type { PolicyDecisionSnapshot } from "./policyRules";
export interface PolicyState extends PolicyDecisionSnapshot {
/** Account whose policy is represented by this renderer state. */
accountId: string | null;
authGeneration: number | null;
revision: number;
- policyUpdatedAt: string | null;
- endpointSupported: boolean | null;
/** True once the org enforces a policy on this user. */
managed: boolean;
- /** True after the first fetch resolves from the network, cache, or an error. */
- loaded: boolean;
- fetchPolicy: (
- accountId: string,
- authGeneration: number,
- reason?: "default" | "recovery"
- ) => Promise<void>;
+ fetchPolicy: (accountId: string, authGeneration: number) => Promise<void>;
clearPolicy: () => void;
}
@@ -87,16 +63,7 @@ function normalizeSnapshot(
result: PolicyIpcSnapshot,
current: PolicyState
): Required<
- Pick<
- PolicyIpcSnapshot,
- | "revision"
- | "accountId"
- | "authGeneration"
- | "managed"
- | "policy"
- | "policyUpdatedAt"
- | "endpointSupported"
- >
+ Pick<PolicyIpcSnapshot, "revision" | "accountId" | "authGeneration" | "managed" | "policy">
> {
return {
revision: result.revision ?? current.revision + 1,
@@ -107,8 +74,6 @@ function normalizeSnapshot(
authGeneration: result.authGeneration ?? null,
managed: Boolean(result.managed),
policy: result.policy ?? null,
- policyUpdatedAt: result.policyUpdatedAt ?? null,
- endpointSupported: result.endpointSupported !== false,
};
}
@@ -141,13 +106,10 @@ function applyPolicySnapshot(result: PolicyIpcSnapshot, appVersion: string | nul
accountId: snapshot.accountId,
authGeneration: snapshot.authGeneration,
revision: snapshot.revision,
- policyUpdatedAt: snapshot.policyUpdatedAt,
- endpointSupported: snapshot.endpointSupported,
status: snapshot.managed ? "managed" : "unmanaged",
managed: snapshot.managed,
policy: snapshot.policy,
appVersion,
- loaded: true,
});
return true;
}
@@ -168,7 +130,6 @@ function applyPolicyFailure(result: PolicyIpcSnapshot): boolean {
status: "error",
managed: false,
policy: null,
- loaded: true,
});
return true;
}
@@ -198,18 +159,11 @@ export const usePolicyStore = create<PolicyState>()((set, get) => ({
accountId: null,
authGeneration: null,
revision: 0,
- policyUpdatedAt: null,
- endpointSupported: null,
status: "idle",
managed: false,
policy: null,
appVersion: null,
- loaded: false,
- fetchPolicy: (
- accountId: string,
- authGeneration: number,
- reason: "default" | "recovery" = "default"
- ): Promise<void> => {
+ fetchPolicy: (accountId: string, authGeneration: number): Promise<void> => {
ensurePolicyLifecycleListeners();
if (fetchInFlight?.accountId === accountId && fetchInFlight.authGeneration === authGeneration) {
return fetchInFlight.promise;
@@ -226,24 +180,17 @@ export const usePolicyStore = create<PolicyState>()((set, get) => ({
accountId,
authGeneration,
revision: sameIdentity ? previous.revision : 0,
- policyUpdatedAt: null,
- endpointSupported: null,
status: "loading",
managed: false,
policy: null,
appVersion: null,
- loaded: false,
});
}
const promise = (async () => {
const versionPromise = readAppVersion();
try {
- const result = await window.electronAPI.getWorkspacePolicy?.(
- accountId,
- authGeneration,
- reason
- );
+ const result = await window.electronAPI.getWorkspacePolicy?.(accountId, authGeneration);
const appVersion = await versionPromise;
if (sequence !== fetchSequence) return;
if (result?.success) {
@@ -261,19 +208,16 @@ export const usePolicyStore = create<PolicyState>()((set, get) => ({
error && typeof error === "object" && "code" in error && typeof error.code === "string"
? error.code
: undefined;
- if (
+ if (!(
current.accountId === accountId &&
shouldPreserveResolvedPolicyOnFailure(current.status, failureCode)
- ) {
- set({ loaded: true });
- } else {
+ )) {
set({
accountId,
status: "error",
managed: false,
policy: null,
appVersion: await versionPromise,
- loaded: true,
});
}
} finally {
@@ -296,174 +240,10 @@ export const usePolicyStore = create<PolicyState>()((set, get) => ({
accountId: null,
authGeneration: null,
revision: 0,
- policyUpdatedAt: null,
- endpointSupported: null,
status: "idle",
managed: false,
policy: null,
appVersion: null,
- loaded: false,
});
},
}));
-
-type PolicySelectorState = Pick<PolicyState, "status" | "policy" | "appVersion">;
-
-export type TranscriptionPolicyContext = "dictation" | "meeting" | "upload";
-
-function getTranscriptionSelection(
- settings: SettingsState,
- context: TranscriptionPolicyContext
-): { mode: InferenceMode; provider: string } {
- if (context === "meeting") {
- return {
- mode: settings.meetingTranscriptionMode,
- provider: settings.meetingCloudTranscriptionProvider || settings.cloudTranscriptionProvider,
- };
- }
- if (context === "upload") {
- return {
- mode: settings.uploadTranscriptionMode,
- provider: settings.uploadCloudTranscriptionProvider || settings.cloudTranscriptionProvider,
- };
- }
- return {
- mode: settings.transcriptionMode,
- provider: settings.cloudTranscriptionProvider,
- };
-}
-
-export function isTranscriptionContextAllowed(
- state: PolicySelectorState,
- settings: SettingsState,
- context: TranscriptionPolicyContext
-): boolean {
- return isTranscriptionSelectionAllowed(state, getTranscriptionSelection(settings, context));
-}
-
-export function isPolicyActionAllowed(state: PolicySelectorState): boolean {
- return isPolicyActionAllowedRule(state);
-}
-
-export function isDesktopActionAllowed(
- state: PolicySelectorState,
- action: DesktopPolicyAction
-): boolean {
- return isDesktopActionAllowedRule(state, action);
-}
-
-export function isLlmSelectionAllowed(
- state: PolicySelectorState,
- mode: InferenceMode,
- provider: string
-): boolean {
- return isLlmSelectionAllowedRule(state, { mode, provider });
-}
-
-/** Whether a transcription/LLM mode is allowed. Unmanaged users allow everything. */
-export function isModeAllowed(
- state: PolicySelectorState,
- scope: PolicyScope,
- mode: InferenceMode
-): boolean {
- return isModeAllowedByPolicy(state, scope, mode);
-}
-
-/** Whether a BYOK provider id is allowed for a scope. Unmanaged users allow everything. */
-export function isProviderAllowed(
- state: PolicySelectorState,
- scope: PolicyScope,
- providerId: string
-): boolean {
- return isProviderAllowedByPolicy(state, scope, providerId);
-}
-
-/** Whether an enterprise-cloud provider id is allowed. Unmanaged users allow everything. */
-export function isEnterpriseProviderAllowed(
- state: PolicySelectorState,
- providerId: string
-): boolean {
- if (!isPolicyActionAllowed(state)) return false;
- if (state.status !== "managed" || !state.policy) return true;
- return state.policy.llm.allowedEnterpriseProviders.includes(providerId);
-}
-
-/** Whether the AI agent (dictation, voice, and chat) is allowed. */
-export function isAgentAllowed(state: PolicySelectorState): boolean {
- if (!isPolicyActionAllowed(state)) return false;
- if (state.status !== "managed" || !state.policy) return true;
- return state.policy.features.agentEnabled;
-}
-
-/** Whether the agent's web_search tool is allowed. */
-export function isWebSearchAllowed(state: PolicySelectorState): boolean {
- if (!isPolicyActionAllowed(state)) return false;
- if (state.status !== "managed" || !state.policy) return true;
- return state.policy.features.webSearchEnabled;
-}
-
-/** Whether a note share visibility is allowed under the org's external-sharing mode. */
-export function isShareVisibilityAllowed(
- state: PolicySelectorState,
- visibility: ShareVisibility
-): boolean {
- return isShareVisibilityAllowedRule(state, visibility);
-}
-
-export function isShareActionAllowed(
- state: PolicySelectorState,
- action: SharePolicyAction,
- currentVisibility: ShareVisibility
-): boolean {
- return isShareActionAllowedRule(state, action, currentVisibility);
-}
-
-/** The org-forced local history value, or null when the user may choose. */
-export function lockedLocalHistoryValue(state: PolicySelectorState): boolean | null {
- if (state.status !== "managed" || !state.policy) return null;
- const mode = state.policy.dataRetention.localHistoryMode;
- if (mode === "always_on") return true;
- if (mode === "always_off") return false;
- return null;
-}
-
-/** The history setting used at runtime without overwriting the user's preference. */
-export function effectiveLocalHistoryEnabled(
- state: PolicySelectorState,
- personalPreference: boolean
-): boolean {
- return effectiveLocalHistoryEnabledRule(state, personalPreference);
-}
-
-/** Whether cloud backup/sync is allowed. */
-export function isCloudBackupAllowed(state: PolicySelectorState): boolean {
- if (!isPolicyActionAllowed(state)) return false;
- if (state.status !== "managed" || !state.policy) return true;
- return state.policy.dataRetention.cloudBackupAllowed;
-}
-
-/** The org cap on audio retention days, or null when uncapped. */
-export function maxAudioRetentionDays(state: PolicySelectorState): number | null {
- if (state.status !== "managed" || !state.policy) return null;
- return state.policy.dataRetention.audioRetentionMaxDays;
-}
-
-/** The audio retention period used at runtime without overwriting the user's preference. */
-export function effectiveAudioRetentionDays(
- state: PolicySelectorState,
- personalPreference: number
-): number {
- return effectiveAudioRetentionDaysRule(state, personalPreference);
-}
-
-/** 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: PolicySelectorState, managedBadge: string): T[] {
- if (state.status === "idle" || state.status === "unmanaged") return options;
- return options.map((option) =>
- isModeAllowed(state, scope, option.id)
- ? option
- : { ...option, disabled: true, badge: managedBadge }
- );
-}
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 7cea63dbf..ce6098c34 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -785,8 +785,7 @@ declare global {
// Org policy (see src/types/policy.ts)
getWorkspacePolicy?: (
accountId?: string,
- expectedAuthGeneration?: number,
- reason?: "default" | "recovery"
+ expectedAuthGeneration?: number
) => Promise<{
success: boolean;
status?: "network" | "cached" | "current" | "unsupported" | "restricted" | "error";
diff --git a/test/helpers/cloudConfigRequest.test.js b/test/helpers/cloudConfigRequest.test.js
new file mode 100644
index 000000000..3a4f80e81
--- /dev/null
+++ b/test/helpers/cloudConfigRequest.test.js
@@ -0,0 +1,100 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const { createCloudConfigRequestHandler } = require("../../src/helpers/cloudConfigRequest");
+
+test("the config handler preserves policy and upgrade response metadata", async () => {
+ const handler = createCloudConfigRequestHandler({
+ getApiUrl: () => "https://api.openwhispr.test",
+ getAuthHeader: async () => ({ Authorization: "Bearer token-a" }),
+ proxyFetch: async (_url, options) => {
+ assert.equal(options.headers["x-openwhispr-policy-version"], "1");
+ return new Response(
+ JSON.stringify({
+ error: "Update required",
+ code: "UPGRADE_REQUIRED",
+ data: { minAppVersion: "2.0.0" },
+ }),
+ { status: 426 }
+ );
+ },
+ withPolicyHeaders: (headers) => ({ ...headers, "x-openwhispr-policy-version": "1" }),
+ logger: { error() {} },
+ configPath: "stt-config",
+ });
+
+ assert.deepEqual(await handler({ sender: {} }), {
+ success: false,
+ error: "Update required",
+ code: "UPGRADE_REQUIRED",
+ status: 426,
+ minAppVersion: "2.0.0",
+ details: { minAppVersion: "2.0.0" },
+ });
+});
+
+test("the config handler keeps successful and legacy auth results compatible", async () => {
+ const responses = [
+ new Response(JSON.stringify({ dictation: { mode: "streaming" } }), { status: 200 }),
+ new Response("{}", { status: 401 }),
+ ];
+ const handler = createCloudConfigRequestHandler({
+ getApiUrl: () => "https://api.openwhispr.test",
+ getAuthHeader: async () => ({ Authorization: "Bearer token-a" }),
+ proxyFetch: async () => responses.shift(),
+ withPolicyHeaders: (headers) => headers,
+ logger: { error() {} },
+ configPath: "stt-config",
+ });
+
+ assert.deepEqual(await handler({ sender: {} }), {
+ success: true,
+ dictation: { mode: "streaming" },
+ });
+ assert.deepEqual(await handler({ sender: {} }), {
+ success: false,
+ error: "Session expired",
+ code: "AUTH_EXPIRED",
+ status: 401,
+ });
+});
+
+test("the note-recording-config handler applies policy headers to its route", async () => {
+ let requestedUrl = null;
+ const handler = createCloudConfigRequestHandler({
+ getApiUrl: () => "https://api.openwhispr.test",
+ getAuthHeader: async () => ({ Authorization: "Bearer token-a" }),
+ proxyFetch: async (url, options) => {
+ requestedUrl = url;
+ assert.equal(options.headers["x-openwhispr-policy-version"], "1");
+ return new Response(JSON.stringify({ providers: [] }), { status: 200 });
+ },
+ withPolicyHeaders: (headers) => ({ ...headers, "x-openwhispr-policy-version": "1" }),
+ logger: { error() {} },
+ configPath: "note-recording-config",
+ });
+
+ assert.deepEqual(await handler({ sender: {} }), { success: true, providers: [] });
+ assert.equal(requestedUrl, "https://api.openwhispr.test/api/note-recording-config");
+});
+
+test("the note-recording-config handler returns a structured policy failure instead of null", async () => {
+ const handler = createCloudConfigRequestHandler({
+ getApiUrl: () => "https://api.openwhispr.test",
+ getAuthHeader: async () => ({ Authorization: "Bearer token-a" }),
+ proxyFetch: async () =>
+ new Response(
+ JSON.stringify({ error: "Blocked by workspace policy", code: "POLICY_RESTRICTED" }),
+ { status: 403 }
+ ),
+ withPolicyHeaders: (headers) => headers,
+ logger: { error() {} },
+ configPath: "note-recording-config",
+ });
+
+ const result = await handler({ sender: {} });
+ assert.equal(result.success, false);
+ assert.equal(result.code, "POLICY_RESTRICTED");
+ assert.equal(result.status, 403);
+ assert.equal(result.error, "Blocked by workspace policy");
+});
diff --git a/test/helpers/ipcPolicyHeaderCoverage.test.js b/test/helpers/ipcPolicyHeaderCoverage.test.js
index 96dfebbce..57b4b43db 100644
--- a/test/helpers/ipcPolicyHeaderCoverage.test.js
+++ b/test/helpers/ipcPolicyHeaderCoverage.test.js
@@ -44,17 +44,9 @@ test("direct policy-aware JSON and token routes apply the shared headers", () =>
});
test("policy headers are not injected into BYOK or self-hosted transports", () => {
- const thirdPartySections = [
- source.slice(
- source.indexOf('provider === "tinfoil"'),
- source.indexOf('provider === "tinfoil"') + 1200
- ),
- source.slice(
- source.indexOf('kind === "self-hosted"'),
- source.indexOf('kind === "self-hosted"') + 1200
- ),
- ];
- for (const section of thirdPartySections) {
- assert.doesNotMatch(section, /withPolicyHeaders/);
+ for (const anchor of ['provider === "tinfoil"', 'kind === "self-hosted"']) {
+ const anchorIndex = source.indexOf(anchor);
+ assert.notEqual(anchorIndex, -1, `anchor ${anchor} must exist in ipcHandlers.js`);
+ assert.doesNotMatch(source.slice(anchorIndex, anchorIndex + 1200), /withPolicyHeaders/);
}
});
diff --git a/test/helpers/meetingPolicyStartRecovery.test.js b/test/helpers/meetingPolicyStartRecovery.test.js
index 34871ecb4..b7a9f7c1a 100644
--- a/test/helpers/meetingPolicyStartRecovery.test.js
+++ b/test/helpers/meetingPolicyStartRecovery.test.js
@@ -166,6 +166,26 @@ test("a policy-rejected automatic meeting start restores manager mode before cle
assert.deepEqual(lifecycle, ["restored", "handled"]);
assert.equal(
useMeetingRecordingStore.getState().error,
- "Meeting transcription is restricted by your organization."
+ "policyRestricted",
+ "the store must hold the sentinel key so the mount can localize it"
+ );
+
+ const rejectionLifecycle = [];
+ await assert.rejects(
+ handleMeetingRecordingRequest({
+ args: { noteId: 42, noteTitle: "New note", folderId: null },
+ startRecording: async () => {
+ throw new Error("start failed");
+ },
+ restoreFromMeetingMode: () => rejectionLifecycle.push("restored"),
+ onHandled: () => rejectionLifecycle.push("handled"),
+ }),
+ /start failed/,
+ "a failed start must still propagate its error"
+ );
+ assert.deepEqual(
+ rejectionLifecycle,
+ ["handled"],
+ "a failed start must still clear the pending request so it is not re-attempted"
);
});
diff --git a/test/helpers/policyFailClosedTransition.test.js b/test/helpers/policyFailClosedTransition.test.js
index 0b8511fcf..7d0fe49d2 100644
--- a/test/helpers/policyFailClosedTransition.test.js
+++ b/test/helpers/policyFailClosedTransition.test.js
@@ -105,5 +105,4 @@ test("renderer fails closed when a managed-unresolvable refresh supersedes unman
await usePolicyStore.getState().fetchPolicy("account-a", 1);
assert.equal(usePolicyStore.getState().status, "error");
- assert.equal(usePolicyStore.getState().loaded, true);
});
diff --git a/test/helpers/policyPreferencePreservation.test.js b/test/helpers/policyPreferencePreservation.test.js
index f6f5c0f7b..555be0b70 100644
--- a/test/helpers/policyPreferencePreservation.test.js
+++ b/test/helpers/policyPreferencePreservation.test.js
@@ -101,8 +101,9 @@ test("managed policy gates preserve the user's raw preferences", async (t) => {
else globalThis.localStorage = originalLocalStorage;
});
- const { usePolicyStore, isCloudBackupAllowed, lockedLocalHistoryValue } =
- await vite.ssrLoadModule("/stores/policyStore.ts");
+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");
+ const { isCloudBackupAllowed, lockedLocalHistoryValue } =
+ await vite.ssrLoadModule("/stores/policyRules.ts");
const { useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");
const before = useSettingsStore.getState();
assert.equal(before.transcriptionMode, "local");
diff --git a/test/helpers/policyRules.test.js b/test/helpers/policyRules.test.js
index a31c18cda..0ed6a0d22 100644
--- a/test/helpers/policyRules.test.js
+++ b/test/helpers/policyRules.test.js
@@ -24,6 +24,24 @@ const policy = {
minAppVersion: null,
};
+test("update-required derives from the org minimum and known app version", async () => {
+ const { isUpdateRequiredByOrg } = await load();
+ const managedWithMin = (minAppVersion, appVersion) => ({
+ status: "managed",
+ policy: { ...policy, minAppVersion },
+ appVersion,
+ });
+
+ assert.equal(isUpdateRequiredByOrg(managedWithMin("2.0.0", "1.8.1")), true);
+ assert.equal(isUpdateRequiredByOrg(managedWithMin("1.0.0", "1.8.1")), false);
+ assert.equal(isUpdateRequiredByOrg(managedWithMin(null, "1.8.1")), false);
+ assert.equal(isUpdateRequiredByOrg(managedWithMin("2.0.0", null)), false);
+ assert.equal(
+ isUpdateRequiredByOrg({ status: "unmanaged", policy: null, appVersion: "1.8.1" }),
+ false
+ );
+});
+
test("allows guests and resolved unmanaged accounts", async () => {
const { isPolicyActionAllowed } = await load();
@@ -195,30 +213,6 @@ test("sharing recovery remains available when exposure-increasing actions are bl
}
});
-test("minimum-version enforcement preserves recovery and maintenance surfaces", async () => {
- const { isDesktopActionAllowed } = await load();
- const snapshot = {
- status: "managed",
- policy: { ...policy, minAppVersion: "2.0.0" },
- appVersion: "1.8.1",
- };
-
- for (const action of [
- "history",
- "retention-settings",
- "updater",
- "diagnostics",
- "permissions",
- "account",
- "sign-out",
- ]) {
- assert.equal(isDesktopActionAllowed(snapshot, action), true, action);
- }
- for (const action of ["capture", "inference", "agent", "sharing", "cloud-backup"]) {
- assert.equal(isDesktopActionAllowed(snapshot, action), false, action);
- }
-});
-
test("derives local history from policy without changing the personal preference", async () => {
const { effectiveLocalHistoryEnabled } = await load();
const unmanaged = { status: "unmanaged", policy: null, appVersion: "1.8.1" };
diff --git a/test/helpers/sttConfigRequest.test.js b/test/helpers/sttConfigRequest.test.js
deleted file mode 100644
index 3ac3ce167..000000000
--- a/test/helpers/sttConfigRequest.test.js
+++ /dev/null
@@ -1,58 +0,0 @@
-const test = require("node:test");
-const assert = require("node:assert/strict");
-
-const { createSttConfigRequestHandler } = require("../../src/helpers/sttConfigRequest");
-
-test("the STT config handler preserves policy and upgrade response metadata", async () => {
- const handler = createSttConfigRequestHandler({
- getApiUrl: () => "https://api.openwhispr.test",
- getAuthHeader: async () => ({ Authorization: "Bearer token-a" }),
- proxyFetch: async (_url, options) => {
- assert.equal(options.headers["x-openwhispr-policy-version"], "1");
- return new Response(
- JSON.stringify({
- error: "Update required",
- code: "UPGRADE_REQUIRED",
- data: { minAppVersion: "2.0.0" },
- }),
- { status: 426 }
- );
- },
- withPolicyHeaders: (headers) => ({ ...headers, "x-openwhispr-policy-version": "1" }),
- logger: { error() {} },
- });
-
- assert.deepEqual(await handler({ sender: {} }), {
- success: false,
- error: "Update required",
- code: "UPGRADE_REQUIRED",
- status: 426,
- minAppVersion: "2.0.0",
- details: { minAppVersion: "2.0.0" },
- });
-});
-
-test("the STT config handler keeps successful and legacy auth results compatible", async () => {
- const responses = [
- new Response(JSON.stringify({ dictation: { mode: "streaming" } }), { status: 200 }),
- new Response("{}", { status: 401 }),
- ];
- const handler = createSttConfigRequestHandler({
- getApiUrl: () => "https://api.openwhispr.test",
- getAuthHeader: async () => ({ Authorization: "Bearer token-a" }),
- proxyFetch: async () => responses.shift(),
- withPolicyHeaders: (headers) => headers,
- logger: { error() {} },
- });
-
- assert.deepEqual(await handler({ sender: {} }), {
- success: true,
- dictation: { mode: "streaming" },
- });
- assert.deepEqual(await handler({ sender: {} }), {
- success: false,
- error: "Session expired",
- code: "AUTH_EXPIRED",
- status: 401,
- });
-});
diff --git a/test/helpers/workspacePolicyManager.test.js b/test/helpers/workspacePolicyManager.test.js
index e6c421d33..d0c97b07d 100644
--- a/test/helpers/workspacePolicyManager.test.js
+++ b/test/helpers/workspacePolicyManager.test.js
@@ -361,7 +361,7 @@ test("known-managed unsupported fallbacks do not extend successful freshness", a
assert.equal(requestCount, 3);
});
-test("throttles sequential focus refreshes after a fallback but lets recovery retry", async (t) => {
+test("throttles sequential focus refreshes after a fallback", async (t) => {
let currentTime = 0;
let requestCount = 0;
const updated = validPolicy("2026-08-05T00:05:00.000Z");
@@ -370,7 +370,7 @@ test("throttles sequential focus refreshes after a fallback but lets recovery re
async () => {
requestCount += 1;
if (requestCount === 1) return response(200, validPolicy());
- if (requestCount <= 3) throw new Error("offline");
+ if (requestCount <= 2) throw new Error("offline");
return response(200, updated);
},
{
@@ -389,20 +389,10 @@ test("throttles sequential focus refreshes after a fallback but lets recovery re
assert.equal((await context.manager.getPolicy(request)).status, "cached");
assert.equal(requestCount, 2);
- const firstRecovery = await context.manager.getPolicy({ ...request, reason: "recovery" });
- currentTime = 300_002;
- const secondWindowRecovery = await context.manager.getPolicy({
- ...request,
- reason: "recovery",
- });
- assert.equal(firstRecovery.status, "cached");
- assert.equal(secondWindowRecovery.status, "cached");
- assert.equal(requestCount, 3);
-
- currentTime = 305_001;
- const recovered = await context.manager.getPolicy({ ...request, reason: "recovery" });
+ currentTime = 305_002;
+ const recovered = await context.manager.getPolicy(request);
assert.equal(recovered.policy.features.agentEnabled, true);
- assert.equal(requestCount, 4);
+ assert.equal(requestCount, 3);
});
test("a stale managed HTTP response cannot replace a newer disk policy after restart", async (t) => {
@@ -718,3 +708,79 @@ test("an unmanaged verdict cannot be rebound to a new credential or API origin",
assert.equal(reboundOrigin.success, false);
assert.equal(reboundOrigin.code, "POLICY_UNAVAILABLE");
});
+
+test("serves the in-memory verdict when the disk cache is unreadable during an outage", async (t) => {
+ let online = true;
+ const context = setup(async () => {
+ if (!online) throw new Error("offline");
+ return response(200, { data: validPolicy().data });
+ });
+ t.after(context.cleanup);
+ const request = { accountId: "account-a", expectedAuthGeneration: 1 };
+
+ const first = await context.manager.getPolicy(request);
+ assert.equal(first.status, "network");
+
+ fs.writeFileSync(context.cachePath, "not json");
+ online = false;
+ const fallback = await context.manager.getPolicy(request);
+ assert.equal(fallback.success, true);
+ assert.equal(fallback.status, "cached");
+ assert.equal(fallback.managed, true);
+});
+
+test("a stale-but-successful refresh still counts toward the refresh TTL", async (t) => {
+ let currentTime = 0;
+ let fetches = 0;
+ const context = setup(
+ async () => {
+ fetches += 1;
+ return response(200, {
+ data: validPolicy(fetches === 1 ? "2026-08-05T00:00:00.000Z" : "2026-08-01T00:00:00.000Z")
+ .data,
+ });
+ },
+ { successfulRefreshMs: 5 * 60 * 1000, now: () => currentTime }
+ );
+ t.after(context.cleanup);
+ const request = { accountId: "account-a", expectedAuthGeneration: 1 };
+
+ await context.manager.getPolicy(request);
+ currentTime += 6 * 60 * 1000;
+ const stale = await context.manager.getPolicy(request);
+ assert.equal(stale.status, "current");
+ assert.equal(fetches, 2);
+
+ currentTime += 60 * 1000;
+ const held = await context.manager.getPolicy(request);
+ assert.equal(held.status, "current");
+ assert.equal(fetches, 2, "a lagging server must not defeat the refresh TTL");
+});
+
+test("a policy request without a validated auth generation fails closed", async (t) => {
+ const context = setup(async () => response(200, { data: validPolicy().data }));
+ t.after(context.cleanup);
+
+ const result = await context.manager.getPolicy({ accountId: "account-a" });
+ assert.equal(result.success, false);
+ assert.equal(result.code, "AUTH_CONTEXT_UNVALIDATED");
+ assert.equal(result.accountId, "account-a");
+ assert.equal(result.authGeneration, 1);
+});
+
+test("throttled errors carry the snapshot identity fields", async (t) => {
+ const context = setup(
+ async () => {
+ throw new Error("offline");
+ },
+ { minimumAttemptIntervalMs: 60_000, now: () => 1_000_000 }
+ );
+ t.after(context.cleanup);
+ const request = { accountId: "account-a", expectedAuthGeneration: 1 };
+
+ await context.manager.getPolicy(request);
+ const throttled = await context.manager.getPolicy(request);
+ assert.equal(throttled.code, "POLICY_RETRY_THROTTLED");
+ assert.equal(throttled.accountId, "account-a");
+ assert.equal(throttled.authGeneration, 1);
+});
diff --git a/test/services/reasoningPolicyRestriction.test.js b/test/services/reasoningPolicyRestriction.test.js
new file mode 100644
index 000000000..5cc1edbbc
--- /dev/null
+++ b/test/services/reasoningPolicyRestriction.test.js
@@ -0,0 +1,111 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+
+const esTranslations = require("../../src/locales/es/translation.json");
+const enTranslations = require("../../src/locales/en/translation.json");
+
+test("reasoning policy asserts throw messages localized to the active UI language", async (t) => {
+ const originalWindow = globalThis.window;
+ const originalLocalStorage = globalThis.localStorage;
+ const values = new Map();
+ const storage = {
+ getItem: (key) => values.get(key) ?? null,
+ setItem: (key, value) => values.set(key, String(value)),
+ removeItem: (key) => values.delete(key),
+ };
+ globalThis.localStorage = storage;
+ globalThis.window = {
+ innerWidth: 1200,
+ localStorage: storage,
+ addEventListener() {},
+ electronAPI: {},
+ };
+
+ const { createServer } = await import("vite");
+ const cacheDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-reasoning-policy-test-"));
+ const vite = await createServer({
+ root: path.resolve(__dirname, "../../src"),
+ cacheDir,
+ configFile: false,
+ appType: "custom",
+ logLevel: "silent",
+ optimizeDeps: { noDiscovery: true },
+ plugins: [
+ {
+ name: "reasoning-policy-test-app-version",
+ enforce: "pre",
+ resolveId(source) {
+ return source.endsWith("/helpers/appVersion.js")
+ ? "\0reasoning-policy-app-version"
+ : null;
+ },
+ load(id) {
+ if (id !== "\0reasoning-policy-app-version") return null;
+ return `
+ export function parseCanonicalAppVersion(value) {
+ const match = typeof value === "string" ? /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)$/.exec(value) : null;
+ return match ? match.slice(1).map(Number) : null;
+ }
+ export function isCanonicalAppVersion(value) {
+ return parseCanonicalAppVersion(value) !== null;
+ }
+ `;
+ },
+ },
+ ],
+ });
+ t.after(async () => {
+ await vite.close();
+ fs.rmSync(cacheDir, { recursive: true, force: true });
+ if (originalWindow === undefined) delete globalThis.window;
+ else globalThis.window = originalWindow;
+ if (originalLocalStorage === undefined) delete globalThis.localStorage;
+ else globalThis.localStorage = originalLocalStorage;
+ });
+
+ const { assertAgentAllowedByPolicy, assertReasoningAllowedByPolicy } = await vite.ssrLoadModule(
+ "/services/reasoningPolicy.ts"
+ );
+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");
+ const { default: i18n } = await vite.ssrLoadModule("/i18n.ts");
+
+ usePolicyStore.setState({
+ status: "managed",
+ appVersion: "1.8.1",
+ policy: {
+ version: 1,
+ transcription: { allowedModes: [], allowedByokProviders: [] },
+ llm: { allowedModes: [], allowedByokProviders: [], allowedEnterpriseProviders: [] },
+ features: { agentEnabled: false, webSearchEnabled: false },
+ sharing: { externalLinkSharing: "disabled" },
+ dataRetention: {
+ audioRetentionMaxDays: null,
+ localHistoryMode: "user_choice",
+ cloudBackupAllowed: false,
+ },
+ minAppVersion: null,
+ },
+ });
+
+ await i18n.changeLanguage("es");
+ assert.notEqual(
+ esTranslations.common.policyAgentRestricted,
+ enTranslations.common.policyAgentRestricted,
+ "the localized strings must differ so this test can prove translation happened"
+ );
+
+ assert.throws(() => assertAgentAllowedByPolicy(), {
+ message: esTranslations.common.policyAgentRestricted,
+ });
+ assert.throws(() => assertReasoningAllowedByPolicy("openai", "providers"), {
+ message: esTranslations.common.policyAiProcessingRestricted,
+ });
+
+ await i18n.changeLanguage("en");
+ assert.throws(() => assertAgentAllowedByPolicy(), {
+ message: enTranslations.common.policyAgentRestricted,
+ });
+});