Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(policy): Harden desktop enforcement and compatibility
Chadpihaa53cdfb183f1
diff --git a/preload.js b/preload.jsindex dd9e48cec..c22850f40 100644--- a/preload.js+++ b/preload.js@@ -605,7 +605,13 @@ 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: () => ipcRenderer.invoke("get-workspace-policy"),+ getWorkspacePolicy: (accountId, expectedAuthGeneration, reason) =>+ ipcRenderer.invoke("get-workspace-policy", accountId, expectedAuthGeneration, reason),+ onWorkspacePolicyChanged: (callback) => {+ const listener = (_event, snapshot) => callback(snapshot);+ ipcRenderer.on("workspace-policy-changed", listener);+ return () => ipcRenderer.removeListener("workspace-policy-changed", listener);+ },getNoteRecordingConfig: () => ipcRenderer.invoke("get-note-recording-config"),// Cloud audio file transcriptiondiff --git a/src/AppRouter.jsx b/src/AppRouter.jsxindex e27f78728..7a0fbca95 100644--- a/src/AppRouter.jsx+++ b/src/AppRouter.jsx@@ -9,6 +9,7 @@ import WindowControls from "./components/WindowControls.tsx";import { Card, CardContent } from "./components/ui/card.tsx";import { useAuth } from "./hooks/useAuth";import { useTheme } from "./hooks/useTheme";+import { usePolicyStore } from "./stores/policyStore";const ControlPanel = React.lazy(() => import("./components/ControlPanel.tsx"));const OnboardingFlow = React.lazy(() => import("./components/OnboardingFlow.tsx"));@@ -35,6 +36,14 @@ export default function AppRouter() {function MainApp() {const { isSignedIn, isGracePeriodOnly, isLoaded: authLoaded } = useAuth();+ const policyStatus = usePolicyStore((state) => state.status);+ const policyResolved =+ !isSignedIn ||+ policyStatus === "managed" ||+ policyStatus === "unmanaged" ||+ policyStatus === "error";+ const isWaitingForPolicyStart = isSignedIn && !policyResolved;+ const autoSyncReady = authLoaded && policyResolved;const [showOnboarding, setShowOnboarding] = useState(false);const [needsReauth, setNeedsReauth] = useState(false);@@ -62,12 +71,12 @@ function MainApp() {// the previous account's rows while validation is still running. A failed// (guest/offline) resolution also counts as settled: canSync() then no-ops// because no validated auth context exists.- if (!isAgentPanel && authLoaded) {+ if (!isAgentPanel && autoSyncReady) {import("./services/SyncService.js").then(({ syncService }) => syncService.startAutoSync()).catch(() => {});}- }, [authLoaded, isAgentPanel, isControlPanel]);+ }, [autoSyncReady, isAgentPanel, isControlPanel]);useEffect(() => {if (!authLoaded) return;@@ -111,9 +120,10 @@ function MainApp() {localStorage.setItem("onboardingCompleted", "true");};- // The agent overlay never touches account-scoped data, so it renders- // without waiting for auth resolution (guests can use it offline).+ // The agent waits for auth resolution so account policy can fail closed;+ // guests still render once the signed-out state resolves.if (isAgentPanel) {+ if (!authLoaded || isWaitingForPolicyStart) return <LoadingFallback />;return (<Suspense fallback={<LoadingFallback />}><AgentOverlay />@@ -124,7 +134,7 @@ function MainApp() {// isLoading clears once the onboarding effect has run, which itself waits// for authLoaded — and authLoaded terminates even when the session cannot// resolve (guest/offline presents as signed out).- if (isLoading) {+ if (isLoading || isWaitingForPolicyStart) {return <LoadingFallback />;}diff --git a/src/components/AgentOverlay.tsx b/src/components/AgentOverlay.tsxindex 7eb3ee47c..793287e9f 100644--- a/src/components/AgentOverlay.tsx+++ b/src/components/AgentOverlay.tsx@@ -194,15 +194,9 @@ export default function AgentOverlay() {window.electronAPI?.hideAgentOverlay?.();}, []);- // The overlay is its own BrowserWindow, so this renderer has to fetch the- // policy itself — the control panel's fetch lives in a different context.- const policyManaged = usePolicyStore((s) => s.managed);- const policyDoc = usePolicyStore((s) => s.policy);- const agentAllowed = isAgentAllowed({ managed: policyManaged, policy: policyDoc });-- useEffect(() => {- void usePolicyStore.getState().fetchPolicy();- }, []);+ // The overlay is its own BrowserWindow; MainApp's useAuth populates this+ // renderer's independent policy store before the overlay is shown.+ const agentAllowed = usePolicyStore(isAgentAllowed);useEffect(() => {if (!agentAllowed) window.electronAPI?.hideAgentOverlay?.();diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsxindex 43392ea65..94e93f97e 100644--- a/src/components/ControlPanel.tsx+++ b/src/components/ControlPanel.tsx@@ -32,7 +32,13 @@ import {clearTranscriptions as clearStore,} from "../stores/transcriptionStore";import { useSettingsStore } from "../stores/settingsStore";-import { usePolicyStore, isAgentAllowed } from "../stores/policyStore";+import {+ isAgentAllowed,+ isDesktopActionAllowed,+ isTranscriptionContextAllowed,+ usePolicyStore,+} from "../stores/policyStore";+import { isControlPanelViewAllowed } from "../stores/policyRules";import { compareAppVersions } from "../utils/version";import {useIsMeetingMode,@@ -182,14 +188,13 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelProconst policyMinAppVersion = usePolicyStore((s) =>s.managed ? (s.policy?.minAppVersion ?? null) : null);- const agentAllowedByPolicy = usePolicyStore((s) =>- isAgentAllowed({ managed: s.managed, policy: s.policy })- );- // The sidebar hides the chat item when the policy disallows the agent, but- // the user may already be on the chat view when the policy arrives.+ const agentAllowedByPolicy = usePolicyStore(isAgentAllowed);+ const policyActionsAllowed = usePolicyStore((state) => isDesktopActionAllowed(state, "capture"));useEffect(() => {- if (!agentAllowedByPolicy && activeView === "chat") setActiveView("home");- }, [agentAllowedByPolicy, activeView]);+ if (!isControlPanelViewAllowed(activeView, agentAllowedByPolicy, policyActionsAllowed)) {+ setActiveView("home");+ }+ }, [activeView, agentAllowedByPolicy, policyActionsAllowed]);const [appVersion, setAppVersion] = useState<string | null>(null);useEffect(() => {if (!policyMinAppVersion) return;@@ -598,6 +603,10 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelProasync (id: number, options?: { isRecover?: boolean }) => {try {const s = useSettingsStore.getState();+ if (!isTranscriptionContextAllowed(usePolicyStore.getState(), s, "dictation")) {+ toast({ title: t("common.managedByOrg"), variant: "default" });+ return;+ }const result = await window.electronAPI.retryTranscription(id, {useLocalWhisper: s.useLocalWhisper,localTranscriptionProvider: s.localTranscriptionProvider,@@ -1180,7 +1189,7 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro<DictionaryView /></Suspense>)}- {activeView === "upload" && (+ {activeView === "upload" && policyActionsAllowed && (<Suspense fallback={null}><UploadAudioViewonNoteCreated={(noteId, folderId) => {diff --git a/src/components/ControlPanelSidebar.tsx b/src/components/ControlPanelSidebar.tsxindex 661e6a81d..8e1853a6b 100644--- a/src/components/ControlPanelSidebar.tsx+++ b/src/components/ControlPanelSidebar.tsx@@ -19,7 +19,7 @@ import { cn } from "./lib/utils";import SupportDropdown from "./ui/SupportDropdown";import { getCachedPlatform } from "../utils/platform";import type { UpsellDecision } from "../lib/upsell";-import { usePolicyStore, isAgentAllowed } from "../stores/policyStore";+import { isAgentAllowed, isDesktopActionAllowed, usePolicyStore } from "../stores/policyStore";const platform = getCachedPlatform();@@ -74,9 +74,8 @@ export default function ControlPanelSidebar({const showLimitBanner = upsell === "show" && Boolean(isSignedIn) && Boolean(isOverLimit);const showUpgradeBanner = upsell === "show" && !showLimitBanner && !upgradeDismissed;- const policyManaged = usePolicyStore((s) => s.managed);- const policyDoc = usePolicyStore((s) => s.policy);- const agentAllowed = isAgentAllowed({ managed: policyManaged, policy: policyDoc });+ const agentAllowed = usePolicyStore(isAgentAllowed);+ const policyActionsAllowed = usePolicyStore((state) => isDesktopActionAllowed(state, "capture"));const navItems: {id: ControlPanelView;@@ -88,7 +87,9 @@ export default function ControlPanelSidebar({? [{ id: "chat" as const, label: t("sidebar.chat"), icon: MessageSquare }]: []),{ id: "personal-notes", label: t("sidebar.notes"), icon: NotebookPen },- { id: "upload", label: t("sidebar.upload"), icon: Upload },+ ...(policyActionsAllowed+ ? [{ id: "upload" as const, label: t("sidebar.upload"), icon: Upload }]+ : []),{ id: "dictionary", label: t("sidebar.dictionary"), icon: BookOpen },{ id: "integrations", label: t("sidebar.integrations"), icon: Blocks },];diff --git a/src/components/EnterpriseSection.tsx b/src/components/EnterpriseSection.tsxindex ec29fdc52..ad5c8bfb1 100644--- a/src/components/EnterpriseSection.tsx+++ b/src/components/EnterpriseSection.tsx@@ -28,10 +28,14 @@ export default function EnterpriseSection({const { t } = useTranslation();const azureDeploymentName = useSettingsStore((s) => s.azureDeploymentName);const bedrockRegion = useSettingsStore((s) => s.bedrockRegion);- const policyManaged = usePolicyStore((s) => s.managed);+ const policyStatus = usePolicyStore((s) => s.status);const policyDoc = usePolicyStore((s) => s.policy);+ const appVersion = usePolicyStore((s) => s.appVersion);const providerAllowed = (providerId: string) =>- isEnterpriseProviderAllowed({ managed: policyManaged, policy: policyDoc }, providerId);+ isEnterpriseProviderAllowed(+ { status: policyStatus, policy: policyDoc, appVersion },+ providerId+ );const providerTabs = ENTERPRISE_PROVIDER_TABS.map((tab) =>providerAllowed(tab.id)diff --git a/src/components/HistoryView.tsx b/src/components/HistoryView.tsxindex 31dfbf273..a892a9686 100644--- a/src/components/HistoryView.tsx+++ b/src/components/HistoryView.tsx@@ -10,6 +10,7 @@ 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";interface HistoryViewProps {history: TranscriptionItemType[];@@ -49,7 +50,10 @@ export default function HistoryView({onToggleDiscarded,}: HistoryViewProps) {const { t } = useTranslation();- const dataRetentionEnabled = useSettingsStore((s) => s.dataRetentionEnabled);+ const personalDataRetentionEnabled = useSettingsStore((s) => s.dataRetentionEnabled);+ const dataRetentionEnabled = usePolicyStore((policyState) =>+ effectiveLocalHistoryEnabled(policyState, personalDataRetentionEnabled)+ );const { events, isLoading: eventsLoading, isConnected } = useUpcomingEvents();const groupedHistory = useMemo(() => {diff --git a/src/components/ReasoningModelSelector.tsx b/src/components/ReasoningModelSelector.tsxindex e09ccef56..d247695b7 100644--- a/src/components/ReasoningModelSelector.tsx+++ b/src/components/ReasoningModelSelector.tsx@@ -349,12 +349,13 @@ export default function ReasoningModelSelector({loading: tinfoilModelsLoading,error: tinfoilModelsError,} = useTinfoilModels(selectedCloudProvider === "tinfoil");- const policyManaged = usePolicyStore((s) => s.managed);+ const policyStatus = usePolicyStore((s) => s.status);const policyDoc = usePolicyStore((s) => s.policy);+ const appVersion = usePolicyStore((s) => s.appVersion);const providerAllowed = useCallback((providerId: string) =>- isProviderAllowed({ managed: policyManaged, policy: policyDoc }, "llm", providerId),- [policyManaged, policyDoc]+ isProviderAllowed({ status: policyStatus, policy: policyDoc, appVersion }, "llm", providerId),+ [policyStatus, policyDoc, appVersion]);const effectiveMode = mode || selectedMode;diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 61953eaeb..cc4524f67 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -110,12 +110,15 @@ import { clearMissingLocalModelSelections, useSettingsStore } from "../stores/seimport { useWorkspaceStore } from "../stores/workspaceStore";import {usePolicyStore,+ effectiveAudioRetentionDays,+ effectiveLocalHistoryEnabled,enforceModeOptions,isModeAllowed,lockedLocalHistoryValue,isCloudBackupAllowed,maxAudioRetentionDays,} from "../stores/policyStore";+import { canChangeCloudBackupPreference } from "../stores/policyRules";import { canManageSystemAudioInApp } from "../utils/systemAudioAccess";import WorkspaceSection from "./settings/WorkspaceSection";import WorkspaceBillingOverview from "./settings/WorkspaceBillingOverview";@@ -277,8 +280,10 @@ function TranscriptionSection({toast,}: TranscriptionSectionProps) {const { t } = useTranslation();- const policyManaged = usePolicyStore((s) => s.managed);+ 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([@@ -310,14 +315,14 @@ function TranscriptionSection({},],"transcription",- { managed: policyManaged, policy: policyDoc },+ policyState,t("common.managedByOrg"));const handleTranscriptionModeSelect = (mode: InferenceMode) => {// "Disabled" mode options still fire onSelect (the sign-in gate relies on// that to start onboarding), so policy must be enforced here, not in the UI.- if (!isModeAllowed({ managed: policyManaged, policy: policyDoc }, "transcription", mode)) {+ if (!isModeAllowed(policyState, "transcription", mode)) {return;}if (mode === "openwhispr" && !isSignedIn) {@@ -871,12 +876,25 @@ export default function SettingsPage({const translationKey = useSettingsStore((s) => s.translationKey);const setTranslationKey = useSettingsStore((s) => s.setTranslationKey);- const settingsPolicyManaged = usePolicyStore((s) => s.managed);+ const settingsPolicyStatus = usePolicyStore((s) => s.status);const settingsPolicyDoc = usePolicyStore((s) => s.policy);- const settingsPolicyState = { managed: settingsPolicyManaged, policy: settingsPolicyDoc };+ const settingsPolicyAppVersion = usePolicyStore((s) => s.appVersion);+ const settingsPolicyState = {+ status: settingsPolicyStatus,+ policy: settingsPolicyDoc,+ appVersion: settingsPolicyAppVersion,+ };const historyLockedByPolicy = lockedLocalHistoryValue(settingsPolicyState) !== null;+ const effectiveDataRetentionEnabled = effectiveLocalHistoryEnabled(+ settingsPolicyState,+ dataRetentionEnabled+ );const cloudBackupPolicyAllowed = isCloudBackupAllowed(settingsPolicyState);const audioRetentionCap = maxAudioRetentionDays(settingsPolicyState);+ const enforcedAudioRetentionDays = effectiveAudioRetentionDays(+ settingsPolicyState,+ audioRetentionDays+ );const { t, i18n } = useTranslation();const { toast } = useToast();@@ -3536,7 +3554,12 @@ EOF`,><Togglechecked={cloudBackupEnabled}- disabled={!cloudBackupPolicyAllowed}+ disabled={+ !canChangeCloudBackupPreference(+ cloudBackupPolicyAllowed,+ cloudBackupEnabled+ )+ }onChange={(v) => {setCloudBackupEnabled(v);if (v) {@@ -3634,7 +3657,7 @@ EOF`,description={t("settingsPage.privacy.audioRetentionDescription")}><select- value={audioRetentionDays}+ value={enforcedAudioRetentionDays}onChange={(e) => {const days = parseInt(e.target.value, 10);if (audioRetentionCap !== null && days > audioRetentionCap) return;@@ -3643,6 +3666,14 @@ EOF`,className={RETENTION_SELECT_CLASS}><option value={0}>{t("settingsPage.privacy.audioRetentionDisabled")}</option>+ {enforcedAudioRetentionDays > 0 &&+ !RETENTION_DAY_OPTIONS.includes(enforcedAudioRetentionDays) && (+ <option value={enforcedAudioRetentionDays}>+ {t("settingsPage.privacy.retentionDays", {+ count: enforcedAudioRetentionDays,+ })}+ </option>+ )}{RETENTION_DAY_OPTIONS.map((days) => (<optionkey={days}@@ -3694,7 +3725,7 @@ EOF`,}><Toggle- checked={dataRetentionEnabled}+ checked={effectiveDataRetentionEnabled}disabled={historyLockedByPolicy}onChange={setDataRetentionEnabled}/>@@ -3707,7 +3738,7 @@ EOF`,><selectvalue={transcriptRetentionDays}- disabled={!dataRetentionEnabled}+ disabled={!effectiveDataRetentionEnabled}onChange={(e) => setTranscriptRetentionDays(parseInt(e.target.value, 10))}className={RETENTION_SELECT_CLASS}>@@ -3729,7 +3760,7 @@ EOF`,><Togglechecked={saveDiscardedTranscriptions}- disabled={!dataRetentionEnabled || audioRetentionDays === 0}+ disabled={!effectiveDataRetentionEnabled || enforcedAudioRetentionDays === 0}onChange={setSaveDiscardedTranscriptions}/></SettingsRow>diff --git a/src/components/TranscriptionModelPicker.tsx b/src/components/TranscriptionModelPicker.tsxindex 21e863e6a..7750de704 100644--- a/src/components/TranscriptionModelPicker.tsx+++ b/src/components/TranscriptionModelPicker.tsx@@ -26,6 +26,7 @@ import {} from "../utils/modelPickerStyles";import { useSettingsStore } from "../stores/settingsStore";import { usePolicyStore, isProviderAllowed } from "../stores/policyStore";+import { reconcileCloudProviderSelection } from "../stores/policyRules";import { getRemoteProviderIcon } from "../utils/providerIcons";import { createExternalLinkHandler } from "../utils/externalLinks";import { API_ENDPOINTS, normalizeBaseUrl } from "../config/constants";@@ -277,8 +278,6 @@ const PROVIDER_CREDENTIALS: Record<},};-const VALID_CLOUD_PROVIDER_IDS = CLOUD_PROVIDER_TABS.map((p) => p.id);-const TINFOIL_AUDIO_DOCS_URL = "https://docs.tinfoil.sh/models/audio";const LOCAL_PROVIDER_TABS: Array<{ id: string; name: string; disabled?: boolean }> = [@@ -394,12 +393,17 @@ 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 policyManaged = usePolicyStore((s) => s.managed);+ const policyStatus = usePolicyStore((s) => s.status);const policyDoc = usePolicyStore((s) => s.policy);+ const appVersion = usePolicyStore((s) => s.appVersion);const providerAllowed = useCallback((providerId: string) =>- isProviderAllowed({ managed: policyManaged, policy: policyDoc }, "transcription", providerId),- [policyManaged, policyDoc]+ isProviderAllowed(+ { status: policyStatus, policy: policyDoc, appVersion },+ "transcription",+ providerId+ ),+ [policyStatus, policyDoc, appVersion]);const cloudProviders = useMemo(() =>@@ -475,33 +479,23 @@ export default function TranscriptionModelPicker({}, []);const ensureValidCloudSelection = useCallback(() => {- const isValidProvider = VALID_CLOUD_PROVIDER_IDS.includes(selectedCloudProvider);-- if (!isValidProvider) {- const knownProviderUrls = cloudProviders.map((p) => p.baseUrl);- const hasCustomUrl =- cloudTranscriptionBaseUrl &&- cloudTranscriptionBaseUrl.trim() !== "" &&- cloudTranscriptionBaseUrl !== API_ENDPOINTS.TRANSCRIPTION_BASE &&- !knownProviderUrls.includes(cloudTranscriptionBaseUrl);-- if (hasCustomUrl && providerAllowed("custom")) {- onCloudProviderSelect("custom");- } else {- const firstProvider = cloudProviders[0];- if (firstProvider) {- onCloudProviderSelect(firstProvider.id);- if (firstProvider.models?.length) {- onCloudModelSelect(firstProvider.models[0].id);- }- }- }- } else if (selectedCloudProvider !== "custom" && !selectedCloudModel) {- const provider = cloudProviders.find((p) => p.id === selectedCloudProvider);- if (provider?.models?.length) {- onCloudModelSelect(provider.models[0].id);- }- }+ const knownProviderUrls = cloudProviders.map((provider) => provider.baseUrl);+ const hasCustomUrl = Boolean(+ cloudTranscriptionBaseUrl &&+ cloudTranscriptionBaseUrl.trim() !== "" &&+ cloudTranscriptionBaseUrl !== API_ENDPOINTS.TRANSCRIPTION_BASE &&+ !knownProviderUrls.includes(cloudTranscriptionBaseUrl)+ );+ const selection = reconcileCloudProviderSelection({+ selectedProvider: selectedCloudProvider,+ selectedModel: selectedCloudModel,+ allowedProviders: cloudProviders,+ customAllowed: providerAllowed("custom"),+ hasCustomUrl,+ });+ if (!selection) return;+ if (selection.provider !== selectedCloudProvider) onCloudProviderSelect(selection.provider);+ if (selection.model !== selectedCloudModel) onCloudModelSelect(selection.model);}, [cloudProviders,cloudTranscriptionBaseUrl,diff --git a/src/components/chat/useChatStreaming.ts b/src/components/chat/useChatStreaming.tsindex a6405354c..f36038a1d 100644--- a/src/components/chat/useChatStreaming.ts+++ b/src/components/chat/useChatStreaming.ts@@ -3,7 +3,12 @@ import { useTranslation } from "react-i18next";import ReasoningService, { type AgentStreamChunk } from "../../services/ReasoningService";import { isEnterpriseProvider } from "../../models/ModelRegistry";import { getSettings } from "../../stores/settingsStore";-import { usePolicyStore, isWebSearchAllowed } from "../../stores/policyStore";+import {+ isAgentAllowed,+ isLlmSelectionAllowed,+ isWebSearchAllowed,+ usePolicyStore,+} from "../../stores/policyStore";import { getAgentSystemPrompt } from "../../config/prompts";import { createToolRegistry } from "../../services/tools";import type { ToolRegistry } from "../../services/tools/ToolRegistry";@@ -104,10 +109,23 @@ export function useChatStreaming({const sendToAI = useCallback(async (userText: string, allMessages: Message[]) => {- setAgentState("thinking");-const settings = getSettings();const chatAgentMode = settings.chatAgentMode || "openwhispr";+ const policyState = usePolicyStore.getState();+ const policyProvider =+ chatAgentMode === "openwhispr"+ ? "openwhispr"+ : chatAgentMode === "local"+ ? "local"+ : settings.chatAgentProvider;+ if (+ !isAgentAllowed(policyState) ||+ !isLlmSelectionAllowed(policyState, chatAgentMode, policyProvider)+ ) {+ return;+ }++ setAgentState("thinking");const isCloudAgent = chatAgentMode === "openwhispr" && settings.isSignedIn;const isLanAgent = chatAgentMode === "self-hosted" && !!settings.chatAgentRemoteUrl;const isCustomAgent =diff --git a/src/components/notes/NoteBottomBar.tsx b/src/components/notes/NoteBottomBar.tsxindex b1ba39c72..6fa812b78 100644--- a/src/components/notes/NoteBottomBar.tsx+++ b/src/components/notes/NoteBottomBar.tsx@@ -9,6 +9,7 @@ const BAR_COUNT = 5;interface NoteBottomBarProps {isRecording: boolean;isProcessing: boolean;+ recordingDisabled?: boolean;onStartRecording: () => void;onStopRecording: () => void;onAskSubmit: (text: string) => void;@@ -23,6 +24,7 @@ interface NoteBottomBarProps {export default function NoteBottomBar({isRecording,isProcessing,+ recordingDisabled = false,onStartRecording,onStopRecording,onAskSubmit,@@ -150,6 +152,7 @@ export default function NoteBottomBar({) : (<buttononClick={onStartRecording}+ disabled={recordingDisabled}className={cn("flex items-center justify-center w-10 h-10 rounded-xl","bg-foreground/3 dark:bg-white/4",@@ -159,9 +162,11 @@ export default function NoteBottomBar({"hover:bg-foreground/6 dark:hover:bg-white/8","hover:text-foreground/50 dark:hover:text-foreground/35","hover:border-border/30 dark:hover:border-white/10",- "active:scale-95"+ "active:scale-95",+ "disabled:pointer-events-none disabled:opacity-40")}aria-label={t("notes.editor.transcribe")}+ title={recordingDisabled ? t("common.managedByOrg") : undefined}><Mic size={15} /></button>diff --git a/src/components/notes/NoteEditor.tsx b/src/components/notes/NoteEditor.tsxindex 68ae5785e..9f53bfbba 100644--- a/src/components/notes/NoteEditor.tsx+++ b/src/components/notes/NoteEditor.tsx@@ -178,6 +178,7 @@ interface NoteEditorProps {isSaving: boolean;isRecording: boolean;isProcessing: boolean;+ recordingAllowed?: boolean;onStartRecording: () => void;onStopRecording: () => void;onExportNote?: (format: "md" | "txt") => void;@@ -209,6 +210,7 @@ export default function NoteEditor({isSaving,isRecording,isProcessing,+ recordingAllowed = true,onStartRecording,onStopRecording,onExportNote,@@ -1252,6 +1254,7 @@ export default function NoteEditor({<NoteBottomBarisRecording={isRecording}isProcessing={isProcessing}+ recordingDisabled={!recordingAllowed}onStartRecording={onStartRecording}onStopRecording={onStopRecording}onAskSubmit={handleAskSubmit}diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsxindex 4c6aec269..cddbfef2a 100644--- a/src/components/notes/PersonalNotesView.tsx+++ b/src/components/notes/PersonalNotesView.tsx@@ -54,8 +54,10 @@ 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 NotesOnboarding from "./NotesOnboarding";import { isRegenerableNoteTitle } from "../../helpers/regenerableNoteTitle";+import { handleMeetingRecordingRequest } from "../../helpers/meetingRecordingRequest";import { markIntroSeen, NOTES_STRUCTURE_INTRO, shouldShowIntro } from "../../lib/versionedIntro";import {applyNoteDraftMutation,@@ -213,6 +215,9 @@ 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 spaces = useSpaces();const folders = useFolders();@@ -615,15 +620,28 @@ export default function PersonalNotesView({if (!meetingRecordingRequest || activeNoteId !== meetingRecordingRequest.noteId) return;const note = activeNote?.id === meetingRecordingRequest.noteId ? activeNote : null;const seedSegments = note?.transcript ? parseTranscriptSegments(note.transcript) : [];- storeStartRecording({- noteId: meetingRecordingRequest.noteId,- noteTitle: note?.title ?? null,- folderId: note?.folder_id ?? meetingRecordingRequest.folderId ?? null,- seedSegments,- diarizationEnabled: note?.diarization_enabled == null ? null : note.diarization_enabled === 1,- expectedCount: resolveExpectedSpeakerCount(note),+ void handleMeetingRecordingRequest({+ args: {+ noteId: meetingRecordingRequest.noteId,+ noteTitle: note?.title ?? null,+ folderId: note?.folder_id ?? meetingRecordingRequest.folderId ?? null,+ seedSegments,+ diarizationEnabled:+ note?.diarization_enabled == null ? null : note.diarization_enabled === 1,+ expectedCount: resolveExpectedSpeakerCount(note),+ },+ startRecording: storeStartRecording,+ restoreFromMeetingMode: async () => {+ await window.electronAPI?.restoreFromMeetingMode?.();+ },+ onHandled: () => onMeetingRecordingRequestHandled?.(),+ }).catch((error) => {+ logger.warn(+ "Failed to handle automatic meeting recording request",+ { error: (error as Error).message },+ "meeting"+ );});- onMeetingRecordingRequestHandled?.();}, [meetingRecordingRequest, activeNoteId, activeNote, onMeetingRecordingRequestHandled]);const prevTranscribingRef = useRef(false);@@ -749,6 +767,7 @@ export default function PersonalNotesView({isSaving={isSaving}isRecording={isActiveNoteRecording}isProcessing={false}+ recordingAllowed={meetingRecordingAllowed}onStartRecording={startRecording}onStopRecording={stopRecording}onExportNote={handleExportNote}diff --git a/src/components/notes/ShareNoteDialog.tsx b/src/components/notes/ShareNoteDialog.tsxindex 030104e4b..7c65d3565 100644--- a/src/components/notes/ShareNoteDialog.tsx+++ b/src/components/notes/ShareNoteDialog.tsx@@ -30,7 +30,12 @@ import {} from "../../stores/noteStore";import { useToast } from "../ui/useToast";import MemberAvatar from "../MemberAvatar";-import { usePolicyStore, isShareVisibilityAllowed } from "../../stores/policyStore";+import {+ isShareActionAllowed,+ isShareVisibilityAllowed,+ usePolicyStore,+} from "../../stores/policyStore";+import type { SharePolicyAction } from "../../stores/policyRules";import { emailDomain, isPersonalEmailDomain } from "../../utils/personalEmailDomains";import { EMAIL_REGEX } from "../../utils/validation";import type {@@ -91,12 +96,16 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDlocalIsSharedRef.current = Boolean(note.is_shared);}, [note.is_shared]);- const policyManaged = usePolicyStore((s) => s.managed);+ 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 visibilityAllowed = useCallback(- (visibility: ShareVisibility) =>- isShareVisibilityAllowed({ managed: policyManaged, policy: policyDoc }, visibility),- [policyManaged, policyDoc]+ (visibility: ShareVisibility) => isShareVisibilityAllowed(policyState, visibility),+ [policyState]);const ownerDomain = useMemo(() => emailDomain(ownerEmail), [ownerEmail]);@@ -106,9 +115,22 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDconst share = cached?.share ?? null;const access = cached?.access;- const canManageSharing = access?.can_manage_access ?? true;+ const currentVisibility = share?.visibility ?? "private";+ const shareActionAllowed = useCallback(+ (action: SharePolicyAction, visibility: ShareVisibility = currentVisibility) =>+ isShareActionAllowed(policyState, action, visibility),+ [currentVisibility, policyState]+ );+ const canManageAccess = access?.can_manage_access ?? true;+ const canInvite = canManageAccess && shareActionAllowed("invite");+ const canBeginSharing =+ canManageAccess &&+ (visibilityAllowed("link") || visibilityAllowed("domain") || visibilityAllowed("invited"));+ const canUseLink =+ canManageAccess &&+ shareActionAllowed(currentVisibility === "private" ? "create-link" : "copy-link");// Principal search needs the ACL API; legacy servers only take raw emails.- const canSearchPrincipals = Boolean(access?.can_manage_access);+ const canSearchPrincipals = canInvite && Boolean(access?.can_manage_access);const invitations = useMemo(() => cached?.invitations ?? [], [cached?.invitations]);const accessInvitationEmails = useMemo(() =>@@ -240,10 +262,18 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDconst applyVisibility = useCallback(async (next: ShareVisibility): Promise<ShareMutationResponse | null> => {- if (!cloudId || !canManageSharing) return null;- if (!visibilityAllowed(next)) return null;+ if (!cloudId || !canManageAccess) return null;const previous = getShareCacheEntry(cloudId);if (!previous || previous.share.visibility === next) return null;+ const action: SharePolicyAction =+ next === "private"+ ? "make-private"+ : next === "link"+ ? "create-link"+ : next === "domain"+ ? "set-domain"+ : "invite";+ if (!shareActionAllowed(action, previous.share.visibility)) return null;setSavingVisibility(true);// Optimistic update so the dropdown feels instant.updateShareCache(cloudId, (entry) => ({@@ -309,7 +339,7 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDsetSavingVisibility(false);}},- [cloudId, canManageSharing, ownerDomain, note.id, t, toast, visibilityAllowed]+ [cloudId, canManageAccess, ownerDomain, note.id, t, toast, shareActionAllowed]);const copyLink = useCallback(@@ -332,7 +362,7 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD// Legacy shares can predate local token persistence; rotating is the only// way to recover a copyable link (the old one stops working by design).const rotateAndCopy = useCallback(async () => {- if (!cloudId) return;+ if (!cloudId || !canManageAccess || !shareActionAllowed("rotate-link")) return;try {const res = await NoteSharingService.rotateToken(cloudId);updateShareCache(cloudId, (entry) => ({@@ -348,10 +378,10 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDconsole.error("Share link recovery failed:", err);toast({ title: t("noteEditor.share.dialog.error.copyFailed"), variant: "destructive" });}- }, [cloudId, note.id, copyLink, t, toast]);+ }, [cloudId, canManageAccess, note.id, copyLink, t, toast, shareActionAllowed]);const handleLinkButton = useCallback(async () => {- if (!cloudId || !share || !canManageSharing) return;+ if (!cloudId || !share || !canUseLink) return;setLinkBusy(true);try {if (share.visibility === "private") {@@ -369,18 +399,10 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD} finally {setLinkBusy(false);}- }, [- cloudId,- share,- canManageSharing,- note.share_token,- applyVisibility,- copyLink,- rotateAndCopy,- ]);+ }, [cloudId, share, canUseLink, note.share_token, applyVisibility, copyLink, rotateAndCopy]);const handleInvite = useCallback(async () => {- if (!cloudId || !canManageSharing) return;+ if (!cloudId || !canInvite) return;const trimmed = emailInput.trim();if (!trimmed) return;if (!EMAIL_REGEX.test(trimmed)) {@@ -416,11 +438,11 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD} finally {setSubmitting(false);}- }, [cloudId, canManageSharing, emailInput, applyVisibility, refreshShareCache, t]);+ }, [cloudId, canInvite, emailInput, applyVisibility, refreshShareCache, t]);const handlePrincipalGrant = useCallback(async (principal: AccessPrincipalSuggestion) => {- if (!cloudId || !cached?.access?.can_manage_access) return;+ if (!cloudId || !canInvite || !cached?.access?.can_manage_access) return;setSubmitting(true);setInputError(null);try {@@ -450,12 +472,12 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDsetSubmitting(false);}},- [cloudId, cached, note.id, refreshShareCache, t]+ [cloudId, canInvite, cached, note.id, refreshShareCache, t]);const handleShareInput = useCallback(async () => {const trimmed = emailInput.trim();- if (!trimmed || !canManageSharing) return;+ if (!trimmed || !canInvite) return;if (access) {const matchingSuggestion = suggestions.find(@@ -482,11 +504,11 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD}await handleInvite();- }, [access, canManageSharing, emailInput, suggestions, handlePrincipalGrant, handleInvite]);+ }, [access, canInvite, emailInput, suggestions, handlePrincipalGrant, handleInvite]);const handleRevoke = useCallback(async (invitation: NoteShareInvitation) => {- if (!cloudId || !canManageSharing) return;+ if (!cloudId || !canManageAccess || !shareActionAllowed("revoke-invitation")) return;const previous = getShareCacheEntry(cloudId);if (!previous) return;updateShareCache(cloudId, (entry) => ({@@ -508,12 +530,12 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDtoast({ title: t("noteEditor.share.dialog.error.revokeFailed"), variant: "destructive" });}},- [cloudId, canManageSharing, t, toast]+ [cloudId, canManageAccess, shareActionAllowed, t, toast]);const handleResend = useCallback(async (invitation: NoteShareInvitation) => {- if (!cloudId || !canManageSharing) return;+ if (!cloudId || !canManageAccess || !shareActionAllowed("resend-invitation")) return;setResendingId(invitation.id);try {const res = await NoteSharingService.resendInvite(cloudId, invitation.id);@@ -529,7 +551,7 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDsetResendingId(null);}},- [cloudId, canManageSharing, t, toast]+ [cloudId, canManageAccess, shareActionAllowed, t, toast]);const replaceAccessGrant = useCallback(@@ -554,7 +576,14 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDconst handleGrantPermission = useCallback(async (grant: NoteAccessGrant, permission: NoteAccessGrant["permission"]) => {- if (!cloudId || grant.permission === permission) return;+ if (+ !cloudId ||+ !canManageAccess ||+ !shareActionAllowed("change-grant") ||+ grant.permission === permission+ ) {+ return;+ }setBusyGrantId(grant.id);replaceAccessGrant(grant.id, { ...grant, permission });try {@@ -573,12 +602,12 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDsetBusyGrantId(null);}},- [cloudId, replaceAccessGrant, t, toast]+ [cloudId, canManageAccess, shareActionAllowed, replaceAccessGrant, t, toast]);const handleRemoveGrant = useCallback(async (grant: NoteAccessGrant) => {- if (!cloudId) return;+ if (!cloudId || !canManageAccess || !shareActionAllowed("remove-grant")) return;setBusyGrantId(grant.id);replaceAccessGrant(grant.id, null);try {@@ -592,10 +621,11 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDsetBusyGrantId(null);}},- [cloudId, refreshShareCache, replaceAccessGrant, t, toast]+ [cloudId, canManageAccess, shareActionAllowed, refreshShareCache, replaceAccessGrant, t, toast]);const handleSyncAndShare = useCallback(async () => {+ if (!canBeginSharing) return;setSyncing(true);try {const assignedCloudId = await syncService.ensureNoteSynced(note.id);@@ -607,7 +637,7 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD} finally {setSyncing(false);}- }, [note.id, t, toast]);+ }, [canBeginSharing, note.id, t, toast]);const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {if (e.key === "Enter" || (e.metaKey && e.key === "Enter")) {@@ -629,7 +659,7 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD<Buttonsize="sm"onClick={() => void handleSyncAndShare()}- disabled={syncing}+ disabled={syncing || !canBeginSharing}className="h-8 px-3 text-xs gap-1.5 justify-self-start">{syncing && <Loader2 size={12} className="animate-spin" />}@@ -668,7 +698,7 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD}}onKeyDown={onKeyDown}placeholder={t("noteEditor.share.dialog.searchPlaceholder")}- disabled={loading || submitting || !canManageSharing}+ disabled={loading || submitting || !canInvite}className={cn(notesInputClass,"flex-1 disabled:opacity-50 disabled:cursor-not-allowed"@@ -680,7 +710,7 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD<Buttonsize="sm"onClick={() => void handleShareInput()}- disabled={loading || submitting || !canManageSharing || !emailInput.trim()}+ disabled={loading || submitting || !canInvite || !emailInput.trim()}className="h-8 px-3 text-xs gap-1.5">{submitting && <Loader2 size={12} className="animate-spin" />}@@ -764,9 +794,15 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD<AccessGrantRowkey={grant.id}grant={grant}- canManage={Boolean(+ canChangePermission={Boolean(access?.can_manage_access &&- (!grant.inherited || access.can_manage_inherited_access)+ (!grant.inherited || access.can_manage_inherited_access) &&+ shareActionAllowed("change-grant")+ )}+ canRemove={Boolean(+ access?.can_manage_access &&+ (!grant.inherited || access.can_manage_inherited_access) &&+ shareActionAllowed("remove-grant"))}busy={busyGrantId === grant.id}onPermissionChange={(permission) => void handleGrantPermission(grant, permission)}@@ -804,7 +840,7 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD: t("noteEditor.share.dialog.pending")}trailing={- canManageSharing ? (+ canManageAccess ? (<DropdownMenu><DropdownMenuTrigger asChild><button@@ -823,7 +859,10 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD<DropdownMenuContent align="end" sideOffset={4}><DropdownMenuItemclassName="text-xs"- disabled={resendingId === invitation.id}+ disabled={+ resendingId === invitation.id ||+ !shareActionAllowed("resend-invitation")+ }onClick={() => void handleResend(invitation)}>{t("noteEditor.share.dialog.resend")}@@ -852,7 +891,7 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDownerDomain={ownerDomain}showDomainOption={showDomainOption}showLinkOption={visibilityAllowed("link")}- disabled={loading || !share || !canManageSharing || savingVisibility || linkBusy}+ disabled={loading || !share || !canManageAccess || savingVisibility || linkBusy}onChange={(v) => void applyVisibility(v)}/><div className="flex-1" />@@ -860,7 +899,7 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDvariant={isPrivate ? "default" : "outline"}size="sm"className="h-8 px-3 text-xs gap-1.5"- disabled={loading || !share || !canManageSharing || savingVisibility || linkBusy}+ disabled={loading || !share || !canUseLink || savingVisibility || linkBusy}onClick={() => void handleLinkButton()}>{linkBusy ? (@@ -925,13 +964,15 @@ function AudienceIcon() {function AccessGrantRow({grant,- canManage,+ canChangePermission,+ canRemove,busy,onPermissionChange,onRemove,}: {grant: NoteAccessGrant;- canManage: boolean;+ canChangePermission: boolean;+ canRemove: boolean;busy: boolean;onPermissionChange: (permission: NoteAccessGrant["permission"]) => void;onRemove: () => void;@@ -971,7 +1012,7 @@ function AccessGrantRow({primary={primary}secondary={secondary}trailing={- canManage ? (+ canChangePermission || canRemove ? (<DropdownMenu><DropdownMenuTrigger asChild><button@@ -992,6 +1033,7 @@ function AccessGrantRow({<DropdownMenuContent align="end" sideOffset={4}><DropdownMenuItemclassName="text-xs gap-2"+ disabled={!canChangePermission}onClick={() => onPermissionChange("viewer")}>{grant.permission === "viewer" && <Check size={11} />}@@ -999,12 +1041,17 @@ function AccessGrantRow({</DropdownMenuItem><DropdownMenuItemclassName="text-xs gap-2"+ disabled={!canChangePermission}onClick={() => onPermissionChange("editor")}>{grant.permission === "editor" && <Check size={11} />}{t("noteEditor.share.dialog.editor")}</DropdownMenuItem>- <DropdownMenuItem className="text-xs text-red-500" onClick={onRemove}>+ <DropdownMenuItem+ className="text-xs text-red-500"+ disabled={!canRemove}+ onClick={onRemove}+ >{t("noteEditor.share.dialog.revoke")}</DropdownMenuItem></DropdownMenuContent>diff --git a/src/components/notes/UploadAudioView.tsx b/src/components/notes/UploadAudioView.tsxindex 3d017fc24..7792ee5ed 100644--- a/src/components/notes/UploadAudioView.tsx+++ b/src/components/notes/UploadAudioView.tsx@@ -54,6 +54,7 @@ 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";type UploadState = "idle" | "selected" | "downloading" | "transcribing" | "complete" | "error";@@ -250,6 +251,9 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: UploacloudTranscriptionMode,transcriptionMode,} = useSettingsStore(useShallow(selectResolvedUploadTranscription));+ const uploadAllowedByPolicy = usePolicyStore((policyState) =>+ isTranscriptionContextAllowed(policyState, getSettings(), "upload")+ );const remoteTranscriptionUrl = useSettingsStore((s) => s.remoteTranscriptionUrl);const remoteTranscriptionModel = useSettingsStore((s) => s.remoteTranscriptionModel);@@ -589,9 +593,12 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: UploarunIdRef.current++;reset();};-const handleTranscribe = async () => {if (!file || batch.isProcessing) return;+ if (!isTranscriptionContextAllowed(usePolicyStore.getState(), getSettings(), "upload")) {+ setError(t("common.managedByOrg"));+ return;+ }const currentFile = file;const currentTempPath = downloadedTempPath;const runId = ++runIdRef.current;@@ -820,6 +827,10 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploaconst startBatchProcessing = () => {if (state === "downloading" || state === "transcribing") return;+ if (!isTranscriptionContextAllowed(usePolicyStore.getState(), getSettings(), "upload")) {+ setBatchUrlNotice(t("common.managedByOrg"));+ return;+ }setBatchUrlNotice(null);const transcribeOpts: TranscribeOptions = {@@ -1049,7 +1060,11 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploavariant="default"size="sm"onClick={startBatchProcessing}- disabled={state === "downloading" || state === "transcribing"}+ disabled={+ !uploadAllowedByPolicy ||+ state === "downloading" ||+ state === "transcribing"+ }className="h-8 text-xs px-5">{t("notes.upload.transcribe")}@@ -1067,7 +1082,7 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: UploagetActiveModelLabel={getActiveModelLabel}reset={reset}handleTranscribe={handleTranscribe}- transcribeDisabled={batch.isProcessing}+ transcribeDisabled={batch.isProcessing || !uploadAllowedByPolicy}requiresUpgrade={!!requiresUpgrade}fileTooLarge={fileTooLarge}isLargeFile={isLargeFile}diff --git a/src/components/settings/DictationAgentSettings.tsx b/src/components/settings/DictationAgentSettings.tsxindex 6765afcfc..0bbd69055 100644--- a/src/components/settings/DictationAgentSettings.tsx+++ b/src/components/settings/DictationAgentSettings.tsx@@ -15,9 +15,7 @@ export default function DictationAgentSettings() {const { t } = useTranslation();const useDictationAgent = useSettingsStore((s) => s.useDictationAgent);const setUseDictationAgent = useSettingsStore((s) => s.setUseDictationAgent);- const policyManaged = usePolicyStore((s) => s.managed);- const policyDoc = usePolicyStore((s) => s.policy);- const agentAllowed = isAgentAllowed({ managed: policyManaged, policy: policyDoc });+ const agentAllowed = usePolicyStore(isAgentAllowed);const { agentName, setAgentName } = useAgentName();const [agentNameInput, setAgentNameInput] = useState(agentName);diff --git a/src/components/settings/InferenceConfigEditor.tsx b/src/components/settings/InferenceConfigEditor.tsxindex 889692d70..c1c7daa44 100644--- a/src/components/settings/InferenceConfigEditor.tsx+++ b/src/components/settings/InferenceConfigEditor.tsx@@ -42,8 +42,10 @@ export default function InferenceConfigEditor({ scope, onModeChange }: Inferenceconst { t } = useTranslation();const config = useSettingsStore(useShallow((s) => selectResolvedLLMConfig(s, scope)));const isSignedIn = useSettingsStore((s) => s.isSignedIn);- const policyManaged = usePolicyStore((s) => s.managed);+ 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(@@ -82,7 +84,7 @@ export default function InferenceConfigEditor({ scope, onModeChange }: Inference},],"llm",- { managed: policyManaged, policy: policyDoc },+ policyState,t("common.managedByOrg"));@@ -98,7 +100,7 @@ export default function InferenceConfigEditor({ scope, onModeChange }: Inference(mode: InferenceMode) => {// "Disabled" mode options still fire onSelect (the sign-in gate relies on// that to start onboarding), so policy must be enforced here, not in the UI.- if (!isModeAllowed({ managed: policyManaged, policy: policyDoc }, "llm", mode)) {+ if (!isModeAllowed({ status: policyStatus, policy: policyDoc, appVersion }, "llm", mode)) {return;}if (mode === "openwhispr" && !isSignedIn) {@@ -123,7 +125,16 @@ export default function InferenceConfigEditor({ scope, onModeChange }: InferenceonModeChange?.(mode);},- [scope, config.mode, config.provider, isSignedIn, onModeChange, policyManaged, policyDoc]+ [+ scope,+ config.mode,+ config.provider,+ isSignedIn,+ onModeChange,+ policyStatus,+ policyDoc,+ appVersion,+ ]);const setMode = setField("mode");diff --git a/src/components/settings/MeetingSettings.tsx b/src/components/settings/MeetingSettings.tsxindex 3f3bc2da9..b3f218222 100644--- a/src/components/settings/MeetingSettings.tsx+++ b/src/components/settings/MeetingSettings.tsx@@ -2,6 +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 { InferenceModeSelector, SettingsRow } from "../ui/SettingsSection";import type { InferenceModeOption } from "../ui/SettingsSection";import { Toggle } from "../ui/toggle";@@ -52,37 +53,47 @@ 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[] = [- {- id: "openwhispr",- label: t("settingsPage.transcription.modes.openwhispr"),- description: t("settingsPage.transcription.modes.openwhisprDesc"),- icon: <Cloud className="w-4 h-4" />,- disabled: !isSignedIn,- badge: !isSignedIn ? t("common.freeAccountRequired") : undefined,- },- {- id: "providers",- label: t("settingsPage.transcription.modes.providers"),- description: t("settingsPage.transcription.modes.providersDesc"),- icon: <Key className="w-4 h-4" />,- },- {- id: "local",- label: t("settingsPage.transcription.modes.local"),- description: t("settingsPage.transcription.modes.localDesc"),- icon: <Cpu className="w-4 h-4" />,- },- {- id: "self-hosted",- label: t("settingsPage.transcription.modes.selfHosted"),- description: t("settingsPage.transcription.modes.selfHostedDesc"),- icon: <Network className="w-4 h-4" />,- },- ];+ const transcriptionModes: InferenceModeOption[] = enforceModeOptions(+ [+ {+ id: "openwhispr",+ label: t("settingsPage.transcription.modes.openwhispr"),+ description: t("settingsPage.transcription.modes.openwhisprDesc"),+ icon: <Cloud className="w-4 h-4" />,+ disabled: !isSignedIn,+ badge: !isSignedIn ? t("common.freeAccountRequired") : undefined,+ },+ {+ id: "providers",+ label: t("settingsPage.transcription.modes.providers"),+ description: t("settingsPage.transcription.modes.providersDesc"),+ icon: <Key className="w-4 h-4" />,+ },+ {+ id: "local",+ label: t("settingsPage.transcription.modes.local"),+ description: t("settingsPage.transcription.modes.localDesc"),+ icon: <Cpu className="w-4 h-4" />,+ },+ {+ id: "self-hosted",+ label: t("settingsPage.transcription.modes.selfHosted"),+ description: t("settingsPage.transcription.modes.selfHostedDesc"),+ icon: <Network className="w-4 h-4" />,+ },+ ],+ "transcription",+ policyState,+ t("common.managedByOrg")+ );const handleTranscriptionModeSelect = (mode: InferenceMode) => {+ if (!isModeAllowed(policyState, "transcription", mode)) return;if (mode === "openwhispr" && !isSignedIn) {startOnboarding();return;diff --git a/src/components/settings/UploadSettings.tsx b/src/components/settings/UploadSettings.tsxindex 8fe3702cf..fa80ebcfe 100644--- a/src/components/settings/UploadSettings.tsx+++ b/src/components/settings/UploadSettings.tsx@@ -2,6 +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 { InferenceModeSelector } from "../ui/SettingsSection";import type { InferenceModeOption } from "../ui/SettingsSection";import TranscriptionModelPicker from "../TranscriptionModelPicker";@@ -31,31 +32,41 @@ 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[] = [- {- id: "openwhispr",- label: t("settingsPage.transcription.modes.openwhispr"),- description: t("settingsPage.transcription.modes.openwhisprDesc"),- icon: <Cloud className="w-4 h-4" />,- disabled: !isSignedIn,- badge: !isSignedIn ? t("common.freeAccountRequired") : undefined,- },- {- id: "providers",- label: t("settingsPage.transcription.modes.providers"),- description: t("settingsPage.transcription.modes.providersDesc"),- icon: <Key className="w-4 h-4" />,- },- {- id: "local",- label: t("settingsPage.transcription.modes.local"),- description: t("settingsPage.transcription.modes.localDesc"),- icon: <Cpu className="w-4 h-4" />,- },- ];+ const transcriptionModes: InferenceModeOption[] = enforceModeOptions(+ [+ {+ id: "openwhispr",+ label: t("settingsPage.transcription.modes.openwhispr"),+ description: t("settingsPage.transcription.modes.openwhisprDesc"),+ icon: <Cloud className="w-4 h-4" />,+ disabled: !isSignedIn,+ badge: !isSignedIn ? t("common.freeAccountRequired") : undefined,+ },+ {+ id: "providers",+ label: t("settingsPage.transcription.modes.providers"),+ description: t("settingsPage.transcription.modes.providersDesc"),+ icon: <Key className="w-4 h-4" />,+ },+ {+ id: "local",+ label: t("settingsPage.transcription.modes.local"),+ description: t("settingsPage.transcription.modes.localDesc"),+ icon: <Cpu className="w-4 h-4" />,+ },+ ],+ "transcription",+ policyState,+ t("common.managedByOrg")+ );const handleTranscriptionModeSelect = (mode: InferenceMode) => {+ if (!isModeAllowed(policyState, "transcription", mode)) return;if (mode === "openwhispr" && !isSignedIn) {startOnboarding();return;diff --git a/src/helpers/appVersion.js b/src/helpers/appVersion.jsnew file mode 100644index 000000000..5e9c1dd5d--- /dev/null+++ b/src/helpers/appVersion.js@@ -0,0 +1,15 @@+const CANONICAL_APP_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;++function parseCanonicalAppVersion(value) {+ if (typeof value !== "string") return null;+ const match = CANONICAL_APP_VERSION.exec(value);+ if (!match) return null;+ const parts = match.slice(1).map(Number);+ return parts.every(Number.isSafeInteger) ? parts : null;+}++function isCanonicalAppVersion(value) {+ return parseCanonicalAppVersion(value) !== null;+}++module.exports = { isCanonicalAppVersion, parseCanonicalAppVersion };diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex 68bca8034..3a42b9e92 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -32,6 +32,14 @@ import {isCloudDictationAgentMode,isCloudTranslationMode,} from "../stores/settingsStore";+import {+ effectiveAudioRetentionDays,+ effectiveLocalHistoryEnabled,+ isAgentAllowed,+ isTranscriptionContextAllowed,+ usePolicyStore,+} from "../stores/policyStore";+import { isTranscriptionSelectionAllowed } from "../stores/policyRules";import { recordCleanupFailure } from "../stores/cleanupFailureStore";import {getBatchTranscriptionModel,@@ -75,6 +83,15 @@ const RECORDING_TIMESLICE_MS = 250; // flush chunks periodically so short recordconst PREVIEW_FLUSH_WATCHDOG_MS = 1000;const REALTIME_MODELS = new Set(["gpt-4o-mini-transcribe", "gpt-4o-transcribe"]);+function getEffectiveRetentionPreferences() {+ const settings = getSettings();+ const policyState = usePolicyStore.getState();+ return {+ dataRetentionEnabled: effectiveLocalHistoryEnabled(policyState, settings.dataRetentionEnabled),+ audioRetentionDays: effectiveAudioRetentionDays(policyState, settings.audioRetentionDays),+ };+}+function dictationAgentReachable(settings) {return resolveDictationAgentInference(settings, { isCloudAgent: isCloudDictationAgentMode() }).reachable;@@ -571,6 +588,29 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);this.context = context;}+ isRecordingAllowedByPolicy() {+ const policyState = usePolicyStore.getState();+ return (+ isTranscriptionContextAllowed(policyState, getSettings(), "dictation") &&+ (this.context !== "agent" || isAgentAllowed(policyState)) &&+ (!this.voiceAgentRequested || isAgentAllowed(policyState))+ );+ }++ assertTranscriptionSelectionAllowed(selection) {+ if (isTranscriptionSelectionAllowed(usePolicyStore.getState(), selection)) return;+ const error = new Error("Transcription is restricted by your organization.");+ error.code = "POLICY_RESTRICTED";+ throw error;+ }++ assertAgentAllowedByPolicy() {+ if (isAgentAllowed(usePolicyStore.getState())) return;+ const error = new Error("AI agent use is restricted by your organization.");+ error.code = "POLICY_RESTRICTED";+ throw error;+ }+setSttConfig(config) {this.sttConfig = config;}@@ -795,6 +835,10 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);async startRecording(forceDefaultMic = false) {try {+ if (!this.isRecordingAllowedByPolicy()) {+ logger.warn("Recording blocked by workspace policy", { context: this.context }, "audio");+ return false;+ }if (this.isRecording || this.isProcessing || this.mediaRecorder?.state === "recording") {return false;}@@ -1210,7 +1254,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);// whether to retain the discarded audio from the snapshot rather than live// manager state (which may already belong to a new recording).const shouldSave =- shouldSaveDiscardedRecording(getSettings(), durationSeconds) &&+ shouldSaveDiscardedRecording(getSettings(), durationSeconds, usePolicyStore.getState()) &&(chunks.length > 0 || segments.length > 0);if (shouldSave) {// Assemble and save in the background — the merge crosses IPC into FFmpeg@@ -1481,6 +1525,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);const { allowOpenAIFallback, useLocalWhisper: isLocalMode } = getSettings();if (allowOpenAIFallback && isLocalMode) {+ const fallbackProvider = getSettings().cloudTranscriptionProvider || "openai";+ this.assertTranscriptionSelectionAllowed({ mode: "providers", provider: fallbackProvider });try {const fallbackResult = await this.processWithOpenAIAPI(audioBlob, metadata);return { ...fallbackResult, source: "openai-fallback" };@@ -1573,6 +1619,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);const { allowOpenAIFallback, useLocalWhisper: isLocalMode } = getSettings();if (allowOpenAIFallback && isLocalMode) {+ const fallbackProvider = getSettings().cloudTranscriptionProvider || "openai";+ this.assertTranscriptionSelectionAllowed({ mode: "providers", provider: fallbackProvider });try {const fallbackResult = await this.processWithOpenAIAPI(audioBlob, metadata);return { ...fallbackResult, source: "openai-fallback" };@@ -1727,6 +1775,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}async processWithReasoningModel(text, model, agentName, config) {+ if (config?.requiresAgent) this.assertAgentAllowedByPolicy();logger.logReasoning("CALLING_REASONING_SERVICE", {model,agentName,@@ -2100,6 +2149,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);const targetModel = route.kind === "agent" ? route.model : cleanupModel;const reasoningConfig = route.config;+ if (route.kind === "agent") this.assertAgentAllowedByPolicy();logger.logReasoning("SENDING_TO_REASONING", {preparedTextLength: normalizedText.length,@@ -2115,7 +2165,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);normalizedText,targetModel,agentName,- reasoningConfig+ { ...reasoningConfig, requiresAgent: true }): await this.processWithReasoningModel(normalizedText,@@ -2371,11 +2421,12 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);try {if (route.kind === "agent") {+ this.assertAgentAllowedByPolicy();const reasoned = await this.processAgentCommand(processedText,route.model,agentName,- route.config+ { ...route.config, requiresAgent: true });if (reasoned) processedText = reasoned;} else if (route.kind === "cleanup" && cleanupCloudMode === "openwhispr") {@@ -2920,6 +2971,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);const isOpenAIMode = !getSettings().useLocalWhisper;if (allowLocalFallback && isOpenAIMode) {+ this.assertTranscriptionSelectionAllowed({ mode: "local", provider: "" });try {const arrayBuffer = await audioBlob.arrayBuffer();const options = { model: fallbackModel };@@ -3201,7 +3253,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}async saveTranscription(text, rawText = null, { clientTranscriptionId } = {}) {- if (!getSettings().dataRetentionEnabled) {+ const { dataRetentionEnabled, audioRetentionDays } = getEffectiveRetentionPreferences();+ if (!dataRetentionEnabled) {logger.debug("Skipping transcription save — data retention disabled", {}, "audio");this.lastAudioBlob = null;this.lastAudioMetadata = null;@@ -3217,16 +3270,18 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);// Save audio if we have a captured blob and the transcription was saved successfullyif (result?.id && this.lastAudioBlob) {- try {- const arrayBuffer = await this.lastAudioBlob.arrayBuffer();- await window.electronAPI.saveTranscriptionAudio(- result.id,- arrayBuffer,- this.lastAudioMetadata- );- } catch (audioErr) {- // Non-blocking: transcription is saved even if audio save fails- logger.warn("Failed to save transcription audio", { error: audioErr.message }, "audio");+ if (audioRetentionDays > 0) {+ try {+ const arrayBuffer = await this.lastAudioBlob.arrayBuffer();+ await window.electronAPI.saveTranscriptionAudio(+ result.id,+ arrayBuffer,+ this.lastAudioMetadata+ );+ } catch (audioErr) {+ // Non-blocking: transcription is saved even if audio save fails+ logger.warn("Failed to save transcription audio", { error: audioErr.message }, "audio");+ }}this.lastAudioBlob = null;this.lastAudioMetadata = null;@@ -3239,7 +3294,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}async saveFailedTranscription(errorMessage, errorCode = null, metadata = {}) {- if (!getSettings().dataRetentionEnabled) {+ const { dataRetentionEnabled, audioRetentionDays } = getEffectiveRetentionPreferences();+ if (!dataRetentionEnabled) {logger.debug("Skipping failed transcription save — data retention disabled", {}, "audio");this.lastAudioBlob = null;this.lastAudioMetadata = null;@@ -3256,24 +3312,26 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);if (result?.id) syncService.debouncedPush("transcription", result.id);if (result?.id && this.lastAudioBlob) {- try {- const durationMs = metadata?.durationSeconds- ? Math.round(metadata.durationSeconds * 1000)- : null;- const arrayBuffer = await this.lastAudioBlob.arrayBuffer();- await window.electronAPI.saveTranscriptionAudio(result.id, arrayBuffer, {- durationMs,- provider: null,- model: null,- });- } catch (audioErr) {- logger.warn(- "Failed to save audio for failed transcription",- {- error: audioErr.message,- },- "audio"- );+ if (audioRetentionDays > 0) {+ try {+ const durationMs = metadata?.durationSeconds+ ? Math.round(metadata.durationSeconds * 1000)+ : null;+ const arrayBuffer = await this.lastAudioBlob.arrayBuffer();+ await window.electronAPI.saveTranscriptionAudio(result.id, arrayBuffer, {+ durationMs,+ provider: null,+ model: null,+ });+ } catch (audioErr) {+ logger.warn(+ "Failed to save audio for failed transcription",+ {+ error: audioErr.message,+ },+ "audio"+ );+ }}this.lastAudioBlob = null;this.lastAudioMetadata = null;@@ -3386,6 +3444,10 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}async warmupStreamingConnection({ isSignedIn: isSignedInOverride } = {}) {+ if (!this.isRecordingAllowedByPolicy()) {+ logger.debug("Streaming warmup skipped by workspace policy", {}, "streaming");+ return false;+ }if (!this.shouldUseStreaming(isSignedInOverride)) {logger.debug("Streaming warmup skipped - not in streaming mode", {}, "streaming");return false;@@ -3558,6 +3620,14 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);async startStreamingRecording(forceDefaultMic = false) {try {+ if (!this.isRecordingAllowedByPolicy()) {+ logger.warn(+ "Streaming recording blocked by workspace policy",+ { context: this.context },+ "audio"+ );+ return false;+ }if (this.streamingStartInProgress) {return false;}@@ -3972,11 +4042,12 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);try {if (route.kind === "agent") {+ this.assertAgentAllowedByPolicy();const reasoned = await this.processAgentCommand(finalText,route.model,agentName,- route.config+ { ...route.config, requiresAgent: true });if (reasoned) finalText = reasoned;logger.info(diff --git a/src/helpers/cloudApiRequest.js b/src/helpers/cloudApiRequest.jsindex c1bbb012b..464845628 100644--- a/src/helpers/cloudApiRequest.js+++ b/src/helpers/cloudApiRequest.js@@ -1,3 +1,5 @@+const { withPolicyRequestHeaders } = require("./policyRequestHeaders");+class AuthContextError extends Error {constructor(message, code = "AUTH_CONTEXT_CHANGED") {super(message);@@ -90,10 +92,12 @@ function createCloudApiRequestHandler({// no account fence and remain usable while auth is unresolved.const fence = opts.public ? null : captureAuthFence(tokenStore, opts.expectedAuthGeneration);const method = (opts.method || "GET").toUpperCase();- const headers = {- "x-openwhispr-version": getAppVersion(),- ...(fence ? { Authorization: fence.authorization } : {}),- };+ // Public invitation previews are not policy-aware and intentionally stay+ // on the legacy API contract. Authenticated cloud calls opt into policy+ // v1 using the same exact headers as direct main-process request paths.+ const headers = fence+ ? withPolicyRequestHeaders({ Authorization: fence.authorization }, getAppVersion())+ : { "x-openwhispr-version": getAppVersion() };const fetchOptions = {method,headers,@@ -140,6 +144,7 @@ function createCloudApiRequestHandler({status: response.status,code: data?.code,details: data?.data,+ minAppVersion: data?.minAppVersion ?? data?.data?.minAppVersion,};}diff --git a/src/helpers/discardedRecording.js b/src/helpers/discardedRecording.jsindex 0d83c76a8..8651cb96f 100644--- a/src/helpers/discardedRecording.js+++ b/src/helpers/discardedRecording.js@@ -1,12 +1,23 @@+import {+ effectiveAudioRetentionDays,+ effectiveLocalHistoryEnabled,+} from "../stores/policyRules.ts";+// Minimum recording length (seconds) worth preserving as a discarded record.// Avoids saving accidental sub-second Escape taps. See #907.export const MIN_DISCARDED_DURATION_SECONDS = 1;-export function shouldSaveDiscardedRecording(settings, durationSeconds) {+export function shouldSaveDiscardedRecording(settings, durationSeconds, policyState = null) {if (!settings) return false;+ const dataRetentionEnabled = policyState+ ? effectiveLocalHistoryEnabled(policyState, settings.dataRetentionEnabled)+ : settings.dataRetentionEnabled;+ const audioRetentionDays = policyState+ ? effectiveAudioRetentionDays(policyState, settings.audioRetentionDays)+ : settings.audioRetentionDays;if (!settings.saveDiscardedTranscriptions) return false;- if (!settings.dataRetentionEnabled) return false;- if (!(settings.audioRetentionDays > 0)) return false;+ if (!dataRetentionEnabled) return false;+ if (!(audioRetentionDays > 0)) return false;if (!(durationSeconds >= MIN_DISCARDED_DURATION_SECONDS)) return false;return true;}diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 09ceee81e..8e18f051b 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -8,9 +8,16 @@ const { broadcastToWindows } = require("./windowBroadcast");const { BYOK_API_KEYS } = require("../config/secretKeys");const tokenStore = require("./tokenStore");const { createCloudApiRequestHandler } = require("./cloudApiRequest");+const { withPolicyRequestHeaders } = require("./policyRequestHeaders");+const { createWorkspacePolicyManager } = require("./workspacePolicyManager");+const { createSttConfigRequestHandler } = require("./sttConfigRequest");+const {+ createPolicyResponseError,+ readPolicyResponseError,+ toPolicyFailure,+} = require("./policyResponseError");const { classifyAndLog } = require("./networkErrors");const { resolveLocalServerNeeds } = require("./localServerPolicy");-const { isValidPolicyShape } = require("./policyValidation");const GnomeShortcutManager = require("./gnomeShortcut");const HyprlandShortcutManager = require("./hyprlandShortcut");const AssemblyAiStreaming = require("./assemblyAiStreaming");@@ -31,7 +38,10 @@ const MeetingEchoLeakDetector = require("./meetingEchoLeakDetector");const { partitionPendingMicFinals, isWithinRetractWindow } = require("./meetingMicHoldback");const { applySmartSpacing } = require("./smartSpacing");const { applyAutoLearnSetting } = require("./autoLearnSetting");-const { DEFAULT_RETENTION_SETTINGS, applyRetentionSettings } = require("./retentionSettings");+const {+ DEFAULT_RETENTION_SETTINGS,+ createRetentionSettingsHandler,+} = require("./retentionSettings");const {transcriptsOverlap,transcriptsLooselyOverlap,@@ -300,9 +310,7 @@ function interpretTranscribeResponse(data) {});}if (data.statusCode !== 200) {- throw Object.assign(new Error(data.data?.error || `API error: ${data.statusCode}`), {- statusCode: data.statusCode,- });+ throw createPolicyResponseError(data.statusCode, data.data, `API error: ${data.statusCode}`);}return data.data;}@@ -311,7 +319,7 @@ async function chunkedCloudTranscribe({buffer = null,filePath = null,apiUrl,- authHeader,+ policyHeaders,multipartFields = {},onProgress,signal,@@ -373,7 +381,7 @@ async function chunkedCloudTranscribe({"audio/mpeg",multipartFields);- const data = await postMultipart(url, body, boundary, authHeader, {+ const data = await postMultipart(url, body, boundary, policyHeaders, {signal: AbortSignal.any([jobSignal, timeoutSignal]),session: getCloudUploadSession(),});@@ -1162,12 +1170,17 @@ class IPCHandlers {return this.audioStorageManager.getStorageUsage();});- ipcMain.on("retention-settings-changed", (_event, incoming) => {- const { changed, settings } = applyRetentionSettings(this._retentionSettings, incoming);- if (!changed) return;- this._retentionSettings = settings;- this._runRetentionCleanup();- });+ ipcMain.on(+ "retention-settings-changed",+ createRetentionSettingsHandler({+ getCurrentSettings: () => this._retentionSettings,+ getOwner: () => this.windowManager.mainWindow?.webContents,+ onSettingsChanged: (settings) => {+ this._retentionSettings = settings;+ this._runRetentionCleanup();+ },+ })+ );ipcMain.handle("delete-all-audio", async () => {const result = this.audioStorageManager.deleteAllAudio();@@ -4622,6 +4635,7 @@ class IPCHandlers {// Honors system proxy via Electron's net stack. useSessionCookies:false so// Electron doesn't auto-attach jar cookies on top of our explicit headers.const proxyFetch = (url, init = {}) => net.fetch(url, { ...init, useSessionCookies: false });+ const withPolicyHeaders = (headers) => withPolicyRequestHeaders(headers, app.getVersion());const handleCloudApiRequest = createCloudApiRequestHandler({getApiUrl,getAppVersion: () => app.getVersion(),@@ -4629,6 +4643,22 @@ class IPCHandlers {tokenStore,logger: debugLogger,});+ const workspacePolicyManager = createWorkspacePolicyManager({+ cachePath: path.join(app.getPath("userData"), "workspace-policy.json"),+ getApiUrl,+ getAppVersion: () => app.getVersion(),+ proxyFetch,+ tokenStore,+ broadcast: (snapshot) => broadcastToWindows("workspace-policy-changed", snapshot),+ logger: debugLogger,+ });+ const handleSttConfigRequest = createSttConfigRequestHandler({+ getApiUrl,+ getAuthHeader,+ proxyFetch,+ withPolicyHeaders,+ logger: debugLogger,+ });ipcMain.handle("cloud-transcribe", async (event, audioBuffer, opts = {}) => {try {@@ -4659,7 +4689,7 @@ class IPCHandlers {const { text, responses, lastResponse, warning } = await chunkedCloudTranscribe({buffer: audioData,apiUrl,- authHeader,+ policyHeaders: withPolicyHeaders(authHeader),multipartFields,});const sum = (field) => responses.reduce((s, r) => s + (r?.[field] || 0), 0);@@ -4688,7 +4718,7 @@ class IPCHandlers {multipartFields);const url = new URL(`${apiUrl}/api/transcribe`);- const data = await postMultipart(url, body, boundary, authHeader, {+ const data = await postMultipart(url, body, boundary, withPolicyHeaders(authHeader), {signal: AbortSignal.timeout(CLOUD_UPLOAD_TIMEOUT_MS),session: getCloudUploadSession(),});@@ -4717,10 +4747,7 @@ class IPCHandlers {};} catch (error) {debugLogger.error("Cloud transcription error", { error: error.message }, "cloud-api");- if (error.code) {- return { success: false, error: error.message, code: error.code, ...error };- }- return { success: false, error: error.message };+ return toPolicyFailure(error);}});@@ -4826,7 +4853,7 @@ class IPCHandlers {const { text } = await chunkedCloudTranscribe({buffer,apiUrl,- authHeader,+ policyHeaders: withPolicyHeaders(authHeader),multipartFields,});result = { text, source: "openwhispr", model: "cloud" };@@ -4838,10 +4865,16 @@ class IPCHandlers {multipartFields);const url = new URL(`${apiUrl}/api/transcribe`);- const data = await postMultipart(url, body, boundary, authHeader, {- signal: AbortSignal.timeout(CLOUD_UPLOAD_TIMEOUT_MS),- session: getCloudUploadSession(),- });+ const data = await postMultipart(+ url,+ body,+ boundary,+ withPolicyHeaders(authHeader),+ {+ signal: AbortSignal.timeout(CLOUD_UPLOAD_TIMEOUT_MS),+ session: getCloudUploadSession(),+ }+ );const responseData = interpretTranscribeResponse(data);result = {text: responseData.text,@@ -5495,7 +5528,7 @@ class IPCHandlers {try {response = await proxyFetch(url, {method: "POST",- headers: { "Content-Type": "application/json", ...authHeader },+ headers: withPolicyHeaders({ "Content-Type": "application/json", ...authHeader }),body: JSON.stringify(body),});} catch (err) {@@ -5510,8 +5543,7 @@ class IPCHandlers {throw err;}if (!response.ok) {- const err = await response.json().catch(() => ({}));- throw new Error(err.error || `Token request failed: ${response.status}`);+ throw await readPolicyResponseError(response, `Token request failed: ${response.status}`);}return response.json();};@@ -6604,7 +6636,7 @@ class IPCHandlers {return { success: true };} catch (error) {debugLogger.error("Meeting transcription prepare error", { error: error.message });- return { success: false, error: error.message };+ return toPolicyFailure(error);} finally {if (timeoutHandle) clearTimeout(timeoutHandle);meetingTranscriptionPrepareInProgress = false;@@ -6747,7 +6779,7 @@ class IPCHandlers {await rollbackMeetingTranscriptionStart();this.meetingDetectionEngine?.setUserRecording(false);debugLogger.error("Meeting transcription start error", { error: error.message });- return { success: false, error: error.message };+ return toPolicyFailure(error);} finally {meetingTranscriptionStartInProgress = false;}@@ -6999,8 +7031,7 @@ class IPCHandlers {});const streamingStartFailure = (err) => {- const result = { success: false, error: err.message };- if (err.code) result.code = err.code;+ const result = toPolicyFailure(err);if (err.messageKey) result.messageKey = err.messageKey;if (err.networkCode) result.networkCode = err.networkCode;return result;@@ -7232,10 +7263,10 @@ class IPCHandlers {const response = await proxyFetch(`${apiUrl}/api/reason`, {method: "POST",- headers: {+ headers: withPolicyHeaders({"Content-Type": "application/json",...authHeader,- },+ }),body: JSON.stringify({text,model: opts.model,@@ -7269,8 +7300,7 @@ class IPCHandlers {if (response.status === 503) {return { success: false, error: "Request timed out", code: "SERVER_ERROR" };}- const errorData = await response.json().catch(() => ({}));- throw new Error(errorData.error || `API error: ${response.status}`);+ throw await readPolicyResponseError(response, `API error: ${response.status}`);}const data = await response.json();@@ -7295,7 +7325,7 @@ class IPCHandlers {};} catch (error) {debugLogger.error("Cloud reasoning error:", error);- return { success: false, error: error.message };+ return toPolicyFailure(error);}});@@ -7309,10 +7339,10 @@ class IPCHandlers {const response = await proxyFetch(`${apiUrl}/api/agent/stream`, {method: "POST",- headers: {+ headers: withPolicyHeaders({"Content-Type": "application/json",...authHeader,- },+ }),body: JSON.stringify({messages,systemPrompt: opts.systemPrompt,@@ -7324,16 +7354,10 @@ class IPCHandlers {});if (!response.ok) {- const errorData = await response.json().catch(() => ({}));- event.sender.send("cloud-agent-stream-error", {- error: errorData.error || `API error: ${response.status}`,- code:- response.status === 401- ? "AUTH_EXPIRED"- : response.status === 503- ? "SERVER_ERROR"- : undefined,- });+ const error = await readPolicyResponseError(response, `API error: ${response.status}`);+ if (response.status === 401 && !error.code) error.code = "AUTH_EXPIRED";+ if (response.status === 503 && !error.code) error.code = "SERVER_ERROR";+ event.sender.send("cloud-agent-stream-error", toPolicyFailure(error));return;}@@ -7373,7 +7397,7 @@ class IPCHandlers {event.sender.send("cloud-agent-stream-end");} catch (error) {debugLogger.error("Cloud agent stream error:", error);- event.sender.send("cloud-agent-stream-error", { error: error.message });+ event.sender.send("cloud-agent-stream-error", toPolicyFailure(error));}});@@ -7403,10 +7427,10 @@ class IPCHandlers {const response = await proxyFetch(`${apiUrl}/api/agent/web-search`, {method: "POST",- headers: {+ headers: withPolicyHeaders({"Content-Type": "application/json",...authHeader,- },+ }),body: JSON.stringify({ query, numResults }),});@@ -7417,18 +7441,15 @@ class IPCHandlers {if (response.status === 503) {return { success: false, error: "Request timed out", code: "SERVER_ERROR" };}- const errorData = await response.json().catch(() => ({}));- return {- success: false,- error: errorData.error || `API error: ${response.status}`,- };+ const error = await readPolicyResponseError(response, `API error: ${response.status}`);+ return toPolicyFailure(error);}const data = await response.json();return { success: true, ...data };} catch (error) {debugLogger.error("Agent web search error:", error);- return { success: false, error: error.message };+ return toPolicyFailure(error);}});@@ -7631,104 +7652,22 @@ class IPCHandlers {}});- const withAppVersion = (headers) => ({- ...headers,- "x-openwhispr-version": app.getVersion(),- });-ipcMain.handle("cloud-api-request", (_event, opts) => handleCloudApiRequest(opts));- ipcMain.handle("get-stt-config", async (event) => {- 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/stt-config`, {- headers: withAppVersion(authHeader),- });-- if (!response.ok) {- if (response.status === 401) {- return { success: false, error: "Session expired", code: "AUTH_EXPIRED" };- }- if (response.status === 503) {- return { success: false, error: "Request timed out", code: "SERVER_ERROR" };- }- throw new Error(`API error: ${response.status}`);- }-- const data = await response.json();- return { success: true, ...data };- } catch (error) {- debugLogger.error("STT config fetch error:", error);- return null;- }- });+ ipcMain.handle("get-stt-config", handleSttConfigRequest);- // Org policy delivered by the API and enforced by the app. Cached to disk so- // enforcement survives a network failure (fail-closed): on error we keep- // serving the last policy rather than falling back to unmanaged. An- // authoritative `managed: false` clears the cache so leaving a workspace- // unlocks settings.- ipcMain.handle("get-workspace-policy", async (event) => {- const cachePath = path.join(app.getPath("userData"), "workspace-policy.json");- 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/workspace-policy`, {- headers: withAppVersion(authHeader),+ 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",});- if (!response.ok) throw new Error(`API error: ${response.status}`);-- const json = await response.json();- const data = json?.data;- // Treat a malformed 200 body as a failure, not an authoritative- // "unmanaged" verdict, so the catch serves the cached policy (fail-closed)- // instead of deleting it and unlocking the user.- if (- !data ||- typeof data.managed !== "boolean" ||- (data.managed && !isValidPolicyShape(data.policy))- ) {- throw new Error("Malformed policy response");- }- if (data.managed) {- try {- fs.writeFileSync(cachePath, JSON.stringify(data), { mode: 0o600 });- } catch (err) {- debugLogger.error("Policy cache write failed:", err);- }- } else {- try {- if (fs.existsSync(cachePath)) fs.unlinkSync(cachePath);- } catch {- /* ignore */- }- }- return { success: true, status: "ok", ...data };- } catch (error) {- try {- if (fs.existsSync(cachePath)) {- const cached = JSON.parse(fs.readFileSync(cachePath, "utf8"));- // Re-validate: a cache written by a build that predates shape- // validation (or a corrupted file) must not reach the renderer.- if (cached?.managed === true && isValidPolicyShape(cached.policy)) {- return { success: true, status: "cached", ...cached };- }- }- } catch (err) {- debugLogger.error("Policy cache read failed:", err);- }- return { success: false, status: "error", error: error.message };}- });+ );ipcMain.handle("get-note-recording-config", async (event) => {try {@@ -7792,7 +7731,7 @@ class IPCHandlers {const { text, warning } = await chunkedCloudTranscribe({filePath: realCloud,apiUrl,- authHeader,+ policyHeaders: withPolicyHeaders(authHeader),multipartFields,onProgress: (payload) => event.sender.send("upload-transcription-progress", payload),signal: controller.signal,@@ -7812,7 +7751,7 @@ class IPCHandlers {multipartFields);const url = new URL(`${apiUrl}/api/transcribe`);- const data = await postMultipart(url, body, boundary, authHeader, {+ const data = await postMultipart(url, body, boundary, withPolicyHeaders(authHeader), {signal: AbortSignal.any([controller.signal,AbortSignal.timeout(CLOUD_UPLOAD_TIMEOUT_MS),@@ -7828,10 +7767,7 @@ class IPCHandlers {return { success: false, error: "Cancelled", code: "UPLOAD_CANCELLED" };}debugLogger.error("Cloud audio file transcription error", { error: error.message });- if (error.code) {- return { success: false, error: error.message, code: error.code, ...error };- }- return { success: false, error: error.message };+ return toPolicyFailure(error);} finally {if (requestId) this._uploadTranscriptionControllers.delete(requestId);}@@ -8340,9 +8276,9 @@ class IPCHandlers {const tokenResponse = await proxyFetch(`${apiUrl}/api/streaming-token`, {method: "POST",- headers: {+ headers: withPolicyHeaders({...authHeader,- },+ }),});if (!tokenResponse.ok) {@@ -8351,9 +8287,9 @@ class IPCHandlers {err.code = "AUTH_EXPIRED";throw err;}- const errorData = await tokenResponse.json().catch(() => ({}));- throw new Error(- errorData.error || `Failed to get streaming token: ${tokenResponse.status}`+ throw await readPolicyResponseError(+ tokenResponse,+ `Failed to get streaming token: ${tokenResponse.status}`);}@@ -8393,10 +8329,7 @@ class IPCHandlers {return { success: true };} catch (error) {debugLogger.error("AssemblyAI warmup error", { error: error.message });- if (error.code === "AUTH_EXPIRED") {- return { success: false, error: "Session expired", code: "AUTH_EXPIRED" };- }- return { success: false, error: error.message };+ return toPolicyFailure(error);}});@@ -8541,7 +8474,7 @@ class IPCHandlers {const tokenResponse = await proxyFetch(`${apiUrl}/api/deepgram-streaming-token`, {method: "POST",- headers: authHeader,+ headers: withPolicyHeaders(authHeader),});if (!tokenResponse.ok) {@@ -8550,7 +8483,10 @@ class IPCHandlers {err.code = "AUTH_EXPIRED";throw err;}- throw new Error(`Failed to get Deepgram streaming token: ${tokenResponse.status}`);+ throw await readPolicyResponseError(+ tokenResponse,+ `Failed to get Deepgram streaming token: ${tokenResponse.status}`+ );}const { token } = await tokenResponse.json();@@ -8571,9 +8507,9 @@ class IPCHandlers {const tokenResponse = await proxyFetch(`${apiUrl}/api/deepgram-streaming-token`, {method: "POST",- headers: {+ headers: withPolicyHeaders({...authHeader,- },+ }),});if (!tokenResponse.ok) {@@ -8582,9 +8518,9 @@ class IPCHandlers {err.code = "AUTH_EXPIRED";throw err;}- const errorData = await tokenResponse.json().catch(() => ({}));- throw new Error(- errorData.error || `Failed to get Deepgram streaming token: ${tokenResponse.status}`+ throw await readPolicyResponseError(+ tokenResponse,+ `Failed to get Deepgram streaming token: ${tokenResponse.status}`);}@@ -8634,10 +8570,7 @@ class IPCHandlers {return { success: true };} catch (error) {debugLogger.error("Deepgram warmup error", { error: error.message });- if (error.code === "AUTH_EXPIRED") {- return { success: false, error: "Session expired", code: "AUTH_EXPIRED" };- }- return { success: false, error: error.message };+ return toPolicyFailure(error);}});diff --git a/src/helpers/meetingRecordingRequest.ts b/src/helpers/meetingRecordingRequest.tsnew file mode 100644index 000000000..1cda8be96--- /dev/null+++ b/src/helpers/meetingRecordingRequest.ts@@ -0,0 +1,19 @@+import type { StartRecordingArgs } from "../stores/meetingRecordingStore";++interface MeetingRecordingRequestOptions {+ args: StartRecordingArgs;+ startRecording: (args: StartRecordingArgs) => Promise<boolean>;+ restoreFromMeetingMode: () => Promise<void> | void;+ onHandled: () => void;+}++export async function handleMeetingRecordingRequest({+ args,+ startRecording,+ restoreFromMeetingMode,+ onHandled,+}: MeetingRecordingRequestOptions): Promise<void> {+ const accepted = await startRecording(args);+ if (!accepted) await restoreFromMeetingMode();+ onHandled();+}diff --git a/src/helpers/policyRequestHeaders.js b/src/helpers/policyRequestHeaders.jsnew file mode 100644index 000000000..b5e8b9d61--- /dev/null+++ b/src/helpers/policyRequestHeaders.js@@ -0,0 +1,16 @@+const { isCanonicalAppVersion } = require("./appVersion");++const POLICY_CAPABILITY_VERSION = "1";++function withPolicyRequestHeaders(headers, appVersion) {+ if (!isCanonicalAppVersion(appVersion)) {+ throw new Error("Policy requests require a canonical app version");+ }+ return {+ ...headers,+ "x-openwhispr-policy-version": POLICY_CAPABILITY_VERSION,+ "x-openwhispr-version": appVersion,+ };+}++module.exports = { POLICY_CAPABILITY_VERSION, withPolicyRequestHeaders };diff --git a/src/helpers/policyResponseError.js b/src/helpers/policyResponseError.jsnew file mode 100644index 000000000..4107f9040--- /dev/null+++ b/src/helpers/policyResponseError.js@@ -0,0 +1,40 @@+function errorMessage(payload, fallback) {+ if (typeof payload?.error === "string" && payload.error) return payload.error;+ if (typeof payload?.error?.message === "string" && payload.error.message) {+ return payload.error.message;+ }+ if (typeof payload?.message === "string" && payload.message) return payload.message;+ return fallback;+}++function createPolicyResponseError(status, payload, fallback) {+ const code = payload?.code ?? payload?.error?.code;+ const details = payload?.data;+ const minAppVersion =+ payload?.minAppVersion ?? details?.minAppVersion ?? payload?.error?.minAppVersion;+ return Object.assign(new Error(errorMessage(payload, fallback)), {+ ...(code ? { code } : {}),+ status,+ statusCode: status,+ ...(minAppVersion ? { minAppVersion } : {}),+ ...(details !== undefined ? { details } : {}),+ });+}++async function readPolicyResponseError(response, fallback) {+ const payload = await response.json().catch(() => null);+ return createPolicyResponseError(response.status, payload, fallback);+}++function toPolicyFailure(error) {+ return {+ success: false,+ error: error?.message || String(error),+ ...(error?.code ? { code: error.code } : {}),+ ...(Number.isInteger(error?.status) ? { status: error.status } : {}),+ ...(error?.minAppVersion ? { minAppVersion: error.minAppVersion } : {}),+ ...(error?.details !== undefined ? { details: error.details } : {}),+ };+}++module.exports = { createPolicyResponseError, readPolicyResponseError, toPolicyFailure };diff --git a/src/helpers/policyValidation.js b/src/helpers/policyValidation.jsindex a2736856b..524f9063c 100644--- a/src/helpers/policyValidation.js+++ b/src/helpers/policyValidation.js@@ -3,32 +3,46 @@// policy.sharing.*, and policy.dataRetention.* unchecked, and treats a null// policy as "allow everything" — so a managed response must carry a// structurally valid policy or the whole response is malformed.+const { isCanonicalAppVersion } = require("./appVersion");+const modelRegistryData = require("../models/modelRegistryData.json");+const POLICY_SCOPES = ["transcription", "llm"];+const TRANSCRIPTION_MODES = new Set(["openwhispr", "providers", "local", "self-hosted"]);+const LLM_MODES = new Set([...TRANSCRIPTION_MODES, "enterprise"]);+const TRANSCRIPTION_PROVIDERS = new Set(+ modelRegistryData.transcriptionProviders.map((provider) => provider.id)+);+const LLM_PROVIDERS = new Set(modelRegistryData.cloudProviders.map((provider) => provider.id));+const ENTERPRISE_PROVIDERS = new Set(+ modelRegistryData.enterpriseProviders.map((provider) => provider.id)+);const SHARING_MODES = ["allowed", "domain_only", "disabled"];const LOCAL_HISTORY_MODES = ["user_choice", "always_on", "always_off"];+function isKnownList(value, known) {+ return Array.isArray(value) && value.every((item) => typeof item === "string" && known.has(item));+}+function isValidPolicyShape(policy) {return (Boolean(policy) &&typeof policy === "object" &&- POLICY_SCOPES.every(- (scope) =>- // The canonical schema enforces min-1 allowedModes ("enable at least- // one mode"), and reconciliation relies on allowedModes[0] existing to- // move users off a disallowed mode — an empty list is malformed.- Array.isArray(policy[scope]?.allowedModes) &&- policy[scope].allowedModes.length > 0 &&- Array.isArray(policy[scope]?.allowedByokProviders)- ) &&- Array.isArray(policy.llm?.allowedEnterpriseProviders) &&+ policy.version === 1 &&+ POLICY_SCOPES.every((scope) => Boolean(policy[scope])) &&+ isKnownList(policy.transcription.allowedModes, TRANSCRIPTION_MODES) &&+ isKnownList(policy.transcription.allowedByokProviders, TRANSCRIPTION_PROVIDERS) &&+ isKnownList(policy.llm.allowedModes, LLM_MODES) &&+ isKnownList(policy.llm.allowedByokProviders, LLM_PROVIDERS) &&+ isKnownList(policy.llm.allowedEnterpriseProviders, ENTERPRISE_PROVIDERS) &&typeof policy.features?.agentEnabled === "boolean" &&typeof policy.features?.webSearchEnabled === "boolean" &&SHARING_MODES.includes(policy.sharing?.externalLinkSharing) &&LOCAL_HISTORY_MODES.includes(policy.dataRetention?.localHistoryMode) &&typeof policy.dataRetention?.cloudBackupAllowed === "boolean" &&(policy.dataRetention?.audioRetentionMaxDays === null ||- typeof policy.dataRetention?.audioRetentionMaxDays === "number") &&- (policy.minAppVersion === null || typeof policy.minAppVersion === "string")+ (Number.isSafeInteger(policy.dataRetention?.audioRetentionMaxDays) &&+ policy.dataRetention.audioRetentionMaxDays > 0)) &&+ (policy.minAppVersion === null || isCanonicalAppVersion(policy.minAppVersion)));}diff --git a/src/helpers/retentionSettings.js b/src/helpers/retentionSettings.jsindex e4f151160..56fdbad79 100644--- a/src/helpers/retentionSettings.js+++ b/src/helpers/retentionSettings.js@@ -1,6 +1,6 @@-// Pure resolver for the "retention-settings-changed" IPC sync. Both renderer-// windows re-sync on mount, so the handler needs to know whether the incoming-// values actually differ before kicking off another cleanup sweep.+// Pure resolver for the "retention-settings-changed" IPC sync. The renderer+// re-syncs on mount, so the handler needs to know whether the incoming values+// actually differ before kicking off another cleanup sweep.const DEFAULT_RETENTION_SETTINGS = {audioRetentionDays: 30,transcriptRetentionDays: 0, // 0 = keep transcripts forever@@ -25,4 +25,18 @@ function applyRetentionSettings(current, incoming) {return { changed, settings };}-module.exports = { DEFAULT_RETENTION_SETTINGS, applyRetentionSettings };+function createRetentionSettingsHandler({ getCurrentSettings, getOwner, onSettingsChanged }) {+ return (event, incoming) => {+ const owner = getOwner();+ if (!owner || event.sender !== owner) return;++ const { changed, settings } = applyRetentionSettings(getCurrentSettings(), incoming);+ if (changed) onSettingsChanged(settings);+ };+}++module.exports = {+ DEFAULT_RETENTION_SETTINGS,+ applyRetentionSettings,+ createRetentionSettingsHandler,+};diff --git a/src/helpers/sttConfigRequest.js b/src/helpers/sttConfigRequest.jsnew file mode 100644index 000000000..4052ca8c0--- /dev/null+++ b/src/helpers/sttConfigRequest.js@@ -0,0 +1,50 @@+const { readPolicyResponseError, toPolicyFailure } = require("./policyResponseError");++function createSttConfigRequestHandler({+ getApiUrl,+ getAuthHeader,+ proxyFetch,+ withPolicyHeaders,+ logger,+}) {+ return async function handleSttConfigRequest(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/stt-config`, {+ headers: withPolicyHeaders(authHeader),+ });+ if (!response.ok) {+ if (response.status === 401) {+ return {+ success: false,+ error: "Session expired",+ code: "AUTH_EXPIRED",+ status: 401,+ };+ }+ if (response.status === 503) {+ return {+ success: false,+ error: "Request timed out",+ code: "SERVER_ERROR",+ status: 503,+ };+ }+ throw await readPolicyResponseError(response, `API error: ${response.status}`);+ }++ const data = await response.json();+ return { success: true, ...data };+ } catch (error) {+ logger?.error?.("STT config fetch error:", error);+ return toPolicyFailure(error);+ }+ };+}++module.exports = { createSttConfigRequestHandler };diff --git a/src/helpers/workspacePolicyCache.js b/src/helpers/workspacePolicyCache.jsnew file mode 100644index 000000000..e54ccd2c5--- /dev/null+++ b/src/helpers/workspacePolicyCache.js@@ -0,0 +1,51 @@+const fs = require("fs");++const CACHE_VERSION = 2;++function isIdentity(value) {+ return (+ value &&+ typeof value === "object" &&+ typeof value.apiOrigin === "string" &&+ typeof value.credentialHash === "string" &&+ (value.accountId === null || typeof value.accountId === "string")+ );+}++function readEnvelope(cachePath) {+ if (!fs.existsSync(cachePath)) return { version: CACHE_VERSION, entries: [] };+ try {+ const parsed = JSON.parse(fs.readFileSync(cachePath, "utf8"));+ if (parsed?.version !== CACHE_VERSION || !Array.isArray(parsed.entries)) {+ return { version: CACHE_VERSION, entries: [] };+ }+ return parsed;+ } catch {+ return { version: CACHE_VERSION, entries: [] };+ }+}++function sameIdentity(left, right) {+ return left.apiOrigin === right.apiOrigin && left.credentialHash === right.credentialHash;+}++function readWorkspacePolicyCache(cachePath, identity) {+ if (!isIdentity(identity)) return null;+ const entry = readEnvelope(cachePath).entries.find(+ (candidate) => isIdentity(candidate?.identity) && sameIdentity(candidate.identity, identity)+ );+ return entry?.data && typeof entry.data === "object" ? entry.data : null;+}++function writeWorkspacePolicyCache(cachePath, identity, data) {+ if (!isIdentity(identity)) throw new Error("Complete policy cache identity is required");+ if (!data || typeof data !== "object") throw new Error("Policy cache data is required");+ const envelope = readEnvelope(cachePath);+ const entries = envelope.entries.filter(+ (entry) => !isIdentity(entry?.identity) || !sameIdentity(entry.identity, identity)+ );+ entries.push({ identity, data });+ fs.writeFileSync(cachePath, JSON.stringify({ version: CACHE_VERSION, entries }), { mode: 0o600 });+}++module.exports = { readWorkspacePolicyCache, writeWorkspacePolicyCache };diff --git a/src/helpers/workspacePolicyManager.js b/src/helpers/workspacePolicyManager.jsnew file mode 100644index 000000000..3c7a294f8--- /dev/null+++ b/src/helpers/workspacePolicyManager.js@@ -0,0 +1,319 @@+const crypto = require("crypto");++const { isValidPolicyShape } = require("./policyValidation");+const { withPolicyRequestHeaders } = require("./policyRequestHeaders");+const { readWorkspacePolicyCache, writeWorkspacePolicyCache } = require("./workspacePolicyCache");++function authError(message, code = "AUTH_CONTEXT_CHANGED") {+ return Object.assign(new Error(message), { code });+}++function normalizeAccountId(value) {+ return typeof value === "string" && value.trim() ? value.trim() : null;+}++function normalizeAuthHeaders(value, token) {+ const headers = {};+ if (value && typeof value === "object") {+ if (typeof value.Authorization === "string" && value.Authorization) {+ headers.Authorization = value.Authorization;+ }+ if (typeof value.Cookie === "string" && value.Cookie) headers.Cookie = value.Cookie;+ }+ if (!headers.Authorization && !headers.Cookie && token) {+ headers.Authorization = `Bearer ${token}`;+ }+ return headers;+}++function validTimestamp(value) {+ return typeof value === "string" && Number.isFinite(Date.parse(value));+}++function validatePolicyData(value) {+ if (!value || typeof value !== "object" || typeof value.managed !== "boolean") return false;+ if (value.managed) {+ return isValidPolicyShape(value.policy) && validTimestamp(value.policyUpdatedAt);+ }+ return (+ (value.policy === null || value.policy === undefined || isValidPolicyShape(value.policy)) &&+ value.policyUpdatedAt == null+ );+}++function createWorkspacePolicyManager({+ cachePath,+ getApiUrl,+ getAppVersion,+ proxyFetch,+ tokenStore,+ broadcast,+ logger,+ requestTimeoutMs = 10_000,+ successfulRefreshMs = 5 * 60 * 1000,+ minimumAttemptIntervalMs = 5_000,+ now = Date.now,+}) {+ const snapshots = new Map();+ const inFlight = new Map();+ const successfulRefreshes = new Map();+ const lastAttempts = new Map();+ const lastRecoveryAttempts = new Map();+ 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)+ ) {+ throw authError("Authentication context changed before policy request");+ }+ const apiUrl = getApiUrl();+ if (!apiUrl) throw new Error("OpenWhispr API URL not configured");+ const authHeaders = normalizeAuthHeaders(request.authHeaders, tokenState?.token);+ if (!Object.keys(authHeaders).length) {+ throw authError("Authenticated policy request has no credential", "AUTH_CONTEXT_UNVALIDATED");+ }+ const apiOrigin = new URL(apiUrl).origin;+ const accountId = normalizeAccountId(request.accountId);+ const credentialMaterial = JSON.stringify(+ Object.entries(authHeaders).sort(([left], [right]) => left.localeCompare(right))+ );+ const credentialHash = crypto.createHash("sha256").update(credentialMaterial).digest("hex");+ return {+ accountId,+ apiUrl: apiUrl.replace(/\/+$/, ""),+ apiOrigin,+ credentialHash,+ authHeaders,+ token: tokenState?.token ?? null,+ authGeneration: tokenState.generation,+ };+ }++ function assertIdentityCurrent(identity) {+ const current = tokenStore.getState();+ if (+ current?.generation !== identity.authGeneration ||+ (identity.token ? current?.token !== identity.token : Boolean(current?.token))+ ) {+ throw authError("Authentication context changed during policy request");+ }+ }++ function identityKey(identity) {+ return `${identity.apiOrigin}\n${identity.credentialHash}`;+ }++ function cacheIdentity(identity) {+ return {+ apiOrigin: identity.apiOrigin,+ credentialHash: identity.credentialHash,+ accountId: identity.accountId,+ };+ }++ function cachedData(identity) {+ const cached = readWorkspacePolicyCache(cachePath, cacheIdentity(identity));+ return validatePolicyData(cached) ? cached : null;+ }++ function publicSnapshot(identity, data, status, snapshotRevision) {+ return {+ success: true,+ status,+ revision: snapshotRevision,+ accountId: identity.accountId,+ authGeneration: identity.authGeneration,+ managed: data.managed,+ policy: data.policy ?? null,+ policyUpdatedAt: data.policyUpdatedAt ?? null,+ endpointSupported: data.endpointSupported !== false,+ };+ }++ function accept(identity, data, status) {+ const key = identityKey(identity);+ let current = snapshots.get(key);+ if (!current) {+ const cached = cachedData(identity);+ if (cached) {+ current = { data: cached, revision };+ snapshots.set(key, current);+ }+ }+ if (+ current?.data.managed &&+ data.managed &&+ validTimestamp(current.data.policyUpdatedAt) &&+ validTimestamp(data.policyUpdatedAt) &&+ Date.parse(data.policyUpdatedAt) < Date.parse(current.data.policyUpdatedAt)+ ) {+ return publicSnapshot(identity, current.data, "current", current.revision);+ }++ revision += 1;+ const next = { data, revision };+ snapshots.set(key, next);+ try {+ writeWorkspacePolicyCache(cachePath, cacheIdentity(identity), data);+ } catch (error) {+ logger?.error?.("Policy cache write failed", error);+ }+ const result = publicSnapshot(identity, data, status, revision);+ broadcast?.(result);+ return result;+ }++ function acceptSuccessfulResponse(identity, data, status) {+ const result = accept(identity, data, status);+ if (result.status !== "current") successfulRefreshes.set(identityKey(identity), now());+ return result;+ }++ async function fetchPolicy(identity) {+ try {+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), requestTimeoutMs);+ try {+ const response = await proxyFetch(`${identity.apiUrl}/api/workspace-policy`, {+ method: "GET",+ headers: withPolicyRequestHeaders(identity.authHeaders, getAppVersion()),+ signal: controller.signal,+ });+ assertIdentityCurrent(identity);++ if (response.status === 404 || response.status === 501) {+ const current = snapshots.get(identityKey(identity));+ if (current?.data.managed) {+ return publicSnapshot(identity, current.data, "cached", current.revision);+ }+ const cached = cachedData(identity);+ if (cached?.managed) return accept(identity, cached, "cached");+ return acceptSuccessfulResponse(+ identity,+ { managed: false, policy: null, policyUpdatedAt: null, endpointSupported: false },+ "unsupported"+ );+ }+ if (!response.ok) {+ const error = new Error(`API error: ${response.status}`);+ error.status = response.status;+ throw error;+ }++ const json = await response.json();+ assertIdentityCurrent(identity);+ const data = {+ ...json?.data,+ endpointSupported: true,+ };+ if (!validatePolicyData(data)) throw new Error("Malformed policy response");+ return acceptSuccessfulResponse(identity, data, "network");+ } finally {+ clearTimeout(timeout);+ }+ } catch (error) {+ try {+ assertIdentityCurrent(identity);+ } catch (authContextError) {+ return {+ success: false,+ status: "error",+ code: authContextError.code,+ error: authContextError.message,+ };+ }++ const cached = cachedData(identity);+ if (cached) {+ 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 });+ return {+ success: false,+ status: "error",+ code: "POLICY_UNAVAILABLE",+ error: error?.message || String(error),+ };+ }+ }++ async function getPolicy(request) {+ let identity;+ try {+ identity = captureIdentity(request ?? {});+ } catch (error) {+ return {+ success: false,+ status: "error",+ code: error.code || "POLICY_UNAVAILABLE",+ error: error.message,+ };+ }+ const key = identityKey(identity);+ const current = snapshots.get(key);+ const lastSuccessfulRefresh = successfulRefreshes.get(key);+ const successfulRefreshAge =+ lastSuccessfulRefresh === undefined ? null : now() - lastSuccessfulRefresh;+ if (+ current &&+ successfulRefreshAge !== null &&+ successfulRefreshAge >= 0 &&+ successfulRefreshAge < successfulRefreshMs+ ) {+ return publicSnapshot(identity, current.data, "current", current.revision);+ }+ if (inFlight.has(key)) {+ return inFlight.get(key).then((result) =>+ result.success+ ? {+ ...result,+ accountId: identity.accountId,+ authGeneration: identity.authGeneration,+ }+ : result+ );+ }+ 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;+ if (attemptIsThrottled) {+ 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",+ };+ }+ const attemptStartedAt = now();+ lastAttempts.set(key, attemptStartedAt);+ if (request?.reason === "recovery") lastRecoveryAttempts.set(key, attemptStartedAt);+ const pending = fetchPolicy(identity).finally(() => {+ if (inFlight.get(key) === pending) inFlight.delete(key);+ });+ inFlight.set(key, pending);+ return pending;+ }++ return { getPolicy };+}++module.exports = { createWorkspacePolicyManager };diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.jsindex c1b2b23fa..37fd23ec4 100644--- a/src/hooks/useAudioRecording.js+++ b/src/hooks/useAudioRecording.js@@ -7,6 +7,11 @@ 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";// Maps a failed selection-replacement code to its `selectionEditing.*` toast// detail key; unlisted codes fall back to the generic "unavailable" message.@@ -38,6 +43,14 @@ export const useAudioRecording = (toast, options = {}) => {startLockRef.current = true;try {if (!audioManagerRef.current) return false;+ const policyState = usePolicyStore.getState();+ if (+ !isTranscriptionContextAllowed(policyState, getSettings(), "dictation") ||+ (voiceAgentRequested && !isAgentAllowed(policyState))+ ) {+ toast({ title: t("common.managedByOrg"), variant: "default" });+ return false;+ }const currentState = audioManagerRef.current.getState();if (currentState.isRecording || currentState.isProcessing) return false;@@ -82,7 +95,7 @@ export const useAudioRecording = (toast, options = {}) => {startLockRef.current = false;}},- []+ [t, toast]);const performStopRecording = useCallback(async () => {diff --git a/src/hooks/useAuth.ts b/src/hooks/useAuth.tsindex 36044823d..7c3dc56dc 100644--- a/src/hooks/useAuth.ts+++ b/src/hooks/useAuth.ts@@ -126,6 +126,11 @@ export function useAuth() {invalidateValidatedAuthContext();}, [sessionError]);+ useEffect(() => {+ if (!sessionResolutionFailed || !resolvedUserId || boundGeneration == null) return;+ void usePolicyStore.getState().fetchPolicy(resolvedUserId, boundGeneration);+ }, [boundGeneration, resolvedUserId, sessionResolutionFailed]);+useEffect(() => {if (boundGeneration == null ||@@ -177,6 +182,7 @@ export function useAuth() {// This legacy marker drives every already-running SyncService window;// its generation gate provides the immediate fence.useSettingsStore.getState().setIsSignedIn(false);+ usePolicyStore.getState().clearPolicy();}await reconcileAccountScope(resolvedUserId, {@@ -192,11 +198,14 @@ export function useAuth() {if (!cancelled) {logger.debug("Auth state sync", { isSignedIn: true, userId: resolvedUserId }, "auth");useSettingsStore.getState().setIsSignedIn(true);- void usePolicyStore.getState().fetchPolicy();+ void usePolicyStore.getState().fetchPolicy(resolvedUserId, boundGeneration);}} else {invalidateValidatedAuthContext();- if (!cancelled) useSettingsStore.getState().setIsSignedIn(false);+ if (!cancelled) {+ useSettingsStore.getState().setIsSignedIn(false);+ usePolicyStore.getState().clearPolicy();+ }}resetAccountScopeRetry();};diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.tsindex 67254a14a..ae15ffba2 100644--- a/src/hooks/useSettings.ts+++ b/src/hooks/useSettings.ts@@ -9,6 +9,7 @@ import type {SelfHostedType,} from "../types/electron";import type { Snippet } from "../utils/snippets";+import { effectiveAudioRetentionDays, usePolicyStore } from "../stores/policyStore";export interface TranscriptionSettings {uiLanguage: string;@@ -178,9 +179,15 @@ function useSettingsInternal() {// Retention periods are enforced by the main process cleanup sweepconst { audioRetentionDays, transcriptRetentionDays } = store;+ const enforcedAudioRetentionDays = usePolicyStore((policyState) =>+ effectiveAudioRetentionDays(policyState, audioRetentionDays)+ );useEffect(() => {- window.electronAPI?.syncRetentionSettings?.({ audioRetentionDays, transcriptRetentionDays });- }, [audioRetentionDays, transcriptRetentionDays]);+ window.electronAPI?.syncRetentionSettings?.({+ audioRetentionDays: enforcedAudioRetentionDays,+ transcriptRetentionDays,+ });+ }, [enforcedAudioRetentionDays, transcriptRetentionDays]);// Sync startup pre-warming preferences to main processconst {diff --git a/src/services/BaseReasoningService.ts b/src/services/BaseReasoningService.tsindex b7244653d..19f4ec022 100644--- a/src/services/BaseReasoningService.ts+++ b/src/services/BaseReasoningService.ts@@ -15,6 +15,7 @@ export interface ReasoningConfig {disableThinking?: boolean;language?: string;requireCompleteOutput?: boolean;+ requiresAgent?: boolean;}export abstract class BaseReasoningService {diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.tsindex 7ab83c198..fa73feb34 100644--- a/src/services/ReasoningService.ts+++ b/src/services/ReasoningService.ts@@ -24,6 +24,8 @@ 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 type { InferenceMode } from "../types/electron";export type ToolMetadata = Record<string, unknown> | Array<Record<string, unknown>>;@@ -45,6 +47,31 @@ export type AgentStreamChunk =}| { type: "done"; finishReason?: string };+function resolveLlmDispatchMode(+ provider: string,+ config: Pick<ReasoningConfig, "lanUrl">+): InferenceMode {+ if (config.lanUrl || provider === "lan") return "self-hosted";+ if (provider === "openwhispr") return "openwhispr";+ if (provider === "local") return "local";+ if (isEnterpriseProvider(provider)) return "enterprise";+ 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.");+ }+ assertReasoningAllowedByPolicy(provider, mode);+}+// Old Ollama/strict proxies reject the `reasoning` object; drop it and retry once.async function fetchWithReasoningFieldFallback(doFetch: () => Promise<Response>,@@ -350,6 +377,10 @@ 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.");+ }+ assertReasoningAllowedByPolicy(providerId, resolveLlmDispatchMode(providerId, config));if (!trimmedModel && providerId !== "openwhispr" && providerId !== "lan") {throw new Error("No reasoning model selected");@@ -407,6 +438,9 @@ class ReasoningService extends BaseReasoningService {lanUrl: config.lanUrl,customApiKey: config.customApiKey,});+ const mode: InferenceMode =+ route.kind === "self-hosted" ? "self-hosted" : route.kind === "local" ? "local" : "providers";+ assertAgentSessionAllowedByPolicy(provider, mode);const isLocalProvider = route.kind === "local";const isLanChat = route.kind === "self-hosted";@@ -616,6 +650,15 @@ class ReasoningService extends BaseReasoningService {customApiKey: config.customApiKey,isEnterpriseProvider: isEnterpriseProvider(provider),});+ const mode: InferenceMode =+ route.kind === "self-hosted"+ ? "self-hosted"+ : route.kind === "enterprise"+ ? "enterprise"+ : route.kind === "local"+ ? "local"+ : "providers";+ assertAgentSessionAllowedByPolicy(provider, mode);const isEnterprise = route.kind === "enterprise";const isLocalProvider = route.kind === "local";const isLanChat = route.kind === "self-hosted";@@ -840,6 +883,7 @@ class ReasoningService extends BaseReasoningService {executeToolCall?: (name: string, args: string) => Promise<ToolExecutionResult>;}): AsyncGenerator<AgentStreamChunk, void, unknown> {+ assertAgentSessionAllowedByPolicy("openwhispr", "openwhispr");const maxSteps = config.tools?.length ? ReasoningService.MAX_TOOL_STEPS : 1;let currentMessages = [...messages];diff --git a/src/services/SyncService.ts b/src/services/SyncService.tsindex 78ac7c19b..26365ac8f 100644--- a/src/services/SyncService.ts+++ b/src/services/SyncService.ts@@ -26,6 +26,7 @@ import {} from "../lib/teamSpacesCapability";import { readIsSubscribed, subscribeIsSubscribed } from "../lib/subscriptionFlag";import { readNoteConflictIds } from "../lib/noteConflictRegistry";+import { isCloudBackupAllowed, usePolicyStore } from "../stores/policyStore";import {buildNoteCreatePayload,buildNoteUpdatePayload,@@ -222,7 +223,8 @@ export class SyncService {hasValidatedAuthContext() &&localStorage.getItem("isSignedIn") === "true" &&localStorage.getItem("cloudBackupEnabled") === "true" &&- readIsSubscribed()+ readIsSubscribed() &&+ isCloudBackupAllowed(usePolicyStore.getState()));}@@ -387,6 +389,9 @@ export class SyncService {// subscription flag itself (post-checkout refetch, invite acceptance)// kicks a pass through the reactive flag instead.subscribeIsSubscribed(() => this.requestSyncAll("start"));+ usePolicyStore.subscribe((policyState) => {+ if (isCloudBackupAllowed(policyState)) this.requestSyncAll("start");+ });setInterval(() => this.requestSyncAll("interval"), AUTO_SYNC_INTERVAL_MS);}diff --git a/src/stores/batchQueueStore.ts b/src/stores/batchQueueStore.tsindex 8055ef26f..24946d73e 100644--- a/src/stores/batchQueueStore.ts+++ b/src/stores/batchQueueStore.ts@@ -2,6 +2,8 @@ import { create } from "zustand";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";export type QueueItemStatus = "queued" | "downloading" | "transcribing" | "done" | "error";@@ -115,6 +117,7 @@ export function processBatchQueue(diarization: DiarizationSettings): void {if (useBatchQueueStore.getState().isProcessing) return;+ if (!isTranscriptionContextAllowed(usePolicyStore.getState(), getSettings(), "upload")) return;const run = ++runId;useBatchQueueStore.setState({ isProcessing: true });diff --git a/src/stores/meetingRecordingStore.ts b/src/stores/meetingRecordingStore.tsindex 22b95c02a..cbad13624 100644--- a/src/stores/meetingRecordingStore.ts+++ b/src/stores/meetingRecordingStore.ts@@ -20,6 +20,7 @@ import {MAX_SPEAKER_COUNT,} from "../constants/speakerDetection.json";import logger from "../utils/logger";+import { isTranscriptionContextAllowed, usePolicyStore } from "./policyStore";import {lockTranscriptSpeaker,normalizeTranscriptSegment,@@ -674,6 +675,7 @@ async function cleanup(): Promise<void> {export async function prepareTranscription(): Promise<void> {if (isPrepared || isRecordingFlag || isStartingFlag) return;+ if (!isTranscriptionContextAllowed(usePolicyStore.getState(), getSettings(), "meeting")) return;if (preparePromise) return preparePromise;logger.info("Meeting transcription preparing (pre-warming WebSockets)...", {}, "meeting");@@ -718,8 +720,15 @@ export interface StartRecordingArgs {expectedCount?: number | null;}-export async function startRecording(args: StartRecordingArgs): Promise<void> {- if (isRecordingFlag || isStartingFlag) return;+export async function startRecording(args: StartRecordingArgs): Promise<boolean> {+ if (isRecordingFlag || isStartingFlag) return true;+ 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.",+ });+ return false;+ }isStartingFlag = true;const initialEnabled =@@ -838,7 +847,7 @@ export async function startRecording(args: StartRecordingArgs): Promise<void> {stopMediaStream(micResult);stopMediaStream(systemCaptureResult.stream);isStartingFlag = false;- return;+ return true;}if (!startResult?.success) {@@ -856,7 +865,7 @@ export async function startRecording(args: StartRecordingArgs): Promise<void> {stopMediaStream(systemCaptureResult.stream);isRecordingFlag = false;isStartingFlag = false;- return;+ return true;}const systemAudioMode = startResult.systemAudioMode || initialSystemAudioAccess.mode;@@ -894,7 +903,7 @@ export async function startRecording(args: StartRecordingArgs): Promise<void> {await window.electronAPI?.meetingTranscriptionStop?.();isRecordingFlag = false;isStartingFlag = false;- return;+ return true;}const segmentCleanup = window.electronAPI?.onMeetingTranscriptionSegment?.(@@ -1198,7 +1207,7 @@ export async function startRecording(args: StartRecordingArgs): Promise<void> {);isStartingFlag = false;await cleanup();- return;+ return true;}isStartingFlag = false;@@ -1225,6 +1234,7 @@ export async function startRecording(args: StartRecordingArgs): Promise<void> {},"meeting");+ return true;} catch (err) {logger.error("Meeting transcription setup failed",@@ -1239,6 +1249,7 @@ export async function startRecording(args: StartRecordingArgs): Promise<void> {isRecordingFlag = false;isStartingFlag = false;await cleanup();+ return true;}}diff --git a/src/stores/policyLifecycle.ts b/src/stores/policyLifecycle.tsnew file mode 100644index 000000000..a7cc9a3ae--- /dev/null+++ b/src/stores/policyLifecycle.ts@@ -0,0 +1,37 @@+export interface PolicySnapshotIdentity {+ accountId: string;+ authGeneration: number;+ revision: number;+}++export const POLICY_SUCCESS_REFRESH_MS = 5 * 60 * 1000;++interface ResolvedPolicyRefreshState {+ status: "idle" | "loading" | "managed" | "unmanaged" | "error";+ accountId: string | null;+ authGeneration: number | null;+}++export function resolvedPolicyRefreshIdentity(+ state: ResolvedPolicyRefreshState+): Omit<PolicySnapshotIdentity, "revision"> | null {+ if (+ (state.status !== "managed" && state.status !== "unmanaged" && state.status !== "error") ||+ !state.accountId ||+ state.authGeneration == null+ ) {+ return null;+ }+ return { accountId: state.accountId, authGeneration: state.authGeneration };+}++export function shouldAcceptPolicySnapshot(+ current: PolicySnapshotIdentity,+ incoming: PolicySnapshotIdentity+): boolean {+ return (+ incoming.accountId === current.accountId &&+ incoming.authGeneration === current.authGeneration &&+ incoming.revision >= current.revision+ );+}diff --git a/src/stores/policyRules.ts b/src/stores/policyRules.tsnew file mode 100644index 000000000..3fd9ca9a5--- /dev/null+++ b/src/stores/policyRules.ts@@ -0,0 +1,216 @@+import type { InferenceMode, ShareVisibility } from "../types/electron";+import type { OrgPolicy, PolicyScope } from "../types/policy";+import { compareAppVersions } from "../utils/version.ts";++export type PolicyStatus = "idle" | "loading" | "managed" | "unmanaged" | "error";++export interface PolicyDecisionSnapshot {+ status: PolicyStatus;+ policy: OrgPolicy | null;+ appVersion: string | null;+}++export function isPolicyActionAllowed(state: PolicyDecisionSnapshot): boolean {+ if (state.status === "idle" || state.status === "unmanaged") return true;+ if (state.status !== "managed" || !state.policy) return false;+ if (!state.policy.minAppVersion) return true;+ if (!state.appVersion) return false;+ 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(+ state: PolicyDecisionSnapshot,+ action: DesktopPolicyAction+): boolean {+ return RECOVERY_ACTIONS.has(action) || isPolicyActionAllowed(state);+}++export function effectiveLocalHistoryEnabled(+ state: PolicyDecisionSnapshot,+ personalPreference: boolean+): boolean {+ if (state.status !== "managed" || !state.policy) return personalPreference;+ const mode = state.policy.dataRetention.localHistoryMode;+ if (mode === "always_on") return true;+ if (mode === "always_off") return false;+ return personalPreference;+}++export function effectiveAudioRetentionDays(+ state: PolicyDecisionSnapshot,+ personalPreference: number+): number {+ if (personalPreference === 0 || state.status !== "managed" || !state.policy) {+ return personalPreference;+ }+ const maximumDays = state.policy.dataRetention.audioRetentionMaxDays;+ return maximumDays === null ? personalPreference : Math.min(personalPreference, maximumDays);+}++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);+}++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);+}++export interface LlmSelection {+ mode: InferenceMode;+ provider: string;+}++export function isLlmSelectionAllowed(+ state: PolicyDecisionSnapshot,+ selection: LlmSelection+): boolean {+ if (!isModeAllowedByPolicy(state, "llm", selection.mode)) return false;+ if (selection.mode === "providers") {+ 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 true;+}++export interface TranscriptionSelection {+ mode: InferenceMode;+ provider: string;+}++export function isTranscriptionSelectionAllowed(+ state: PolicyDecisionSnapshot,+ selection: TranscriptionSelection+): boolean {+ if (!isModeAllowedByPolicy(state, "transcription", selection.mode)) return false;+ if (selection.mode !== "providers") return true;+ return isProviderAllowedByPolicy(state, "transcription", selection.provider);+}++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";+}++export type SharePolicyAction =+ | "create-link"+ | "copy-link"+ | "rotate-link"+ | "invite"+ | "resend-invitation"+ | "create-grant"+ | "change-grant"+ | "set-domain"+ | "make-private"+ | "revoke-invitation"+ | "remove-grant";++export function isShareActionAllowed(+ state: PolicyDecisionSnapshot,+ action: SharePolicyAction,+ currentVisibility: ShareVisibility+): boolean {+ if (action === "make-private" || action === "revoke-invitation" || action === "remove-grant") {+ return true;+ }+ if (action === "copy-link" || action === "rotate-link") {+ return currentVisibility === "link" && isShareVisibilityAllowed(state, "link");+ }+ if (action === "create-link") return isShareVisibilityAllowed(state, "link");+ if (action === "set-domain") return isShareVisibilityAllowed(state, "domain");+ return isShareVisibilityAllowed(state, "invited");+}++export function canChangeCloudBackupPreference(+ policyAllowsBackup: boolean,+ backupCurrentlyEnabled: boolean+): boolean {+ return policyAllowsBackup || backupCurrentlyEnabled;+}++export function isControlPanelViewAllowed(+ view: string,+ agentAllowed: boolean,+ policyActionsAllowed: boolean+): boolean {+ if (view === "chat") return agentAllowed;+ if (view === "upload") return policyActionsAllowed;+ return true;+}++interface CloudProviderOption {+ id: string;+ models?: ReadonlyArray<{ id: string }>;+}++export function reconcileCloudProviderSelection({+ selectedProvider,+ selectedModel,+ allowedProviders,+ customAllowed,+ hasCustomUrl,+}: {+ selectedProvider: string;+ selectedModel: string;+ allowedProviders: readonly CloudProviderOption[];+ customAllowed: boolean;+ hasCustomUrl: boolean;+}): { provider: string; model: string } | null {+ if (selectedProvider === "custom" && customAllowed) return null;+ const selected = allowedProviders.find((provider) => provider.id === selectedProvider);+ if (selected) {+ if (selectedModel || !selected.models?.length) return null;+ return { provider: selected.id, model: selected.models[0].id };+ }+ if (hasCustomUrl && customAllowed) {+ return { provider: "custom", model: selectedModel || "whisper-1" };+ }+ const first = allowedProviders[0];+ if (!first) return null;+ return { provider: first.id, model: first.models?.[0]?.id ?? "" };+}diff --git a/src/stores/policyStore.ts b/src/stores/policyStore.tsindex 4828d2538..5be99dcf9 100644--- a/src/stores/policyStore.ts+++ b/src/stores/policyStore.ts@@ -1,269 +1,437 @@import { create } from "zustand";import logger from "../utils/logger";-import { useSettingsStore, selectResolvedLLMConfig, setResolvedLLMConfig } from "./settingsStore";-import { INFERENCE_SCOPES, type InferenceScope } from "../config/inferenceScopes";-import {- isProviderValidForMode,- getTranscriptionProviders,- modelRegistry,- REASONING_PROVIDERS,- ENTERPRISE_PROVIDERS,-} from "../models/ModelRegistry";+import type { SettingsState } from "./settingsStore";import type { InferenceMode, ShareVisibility } from "../types/electron";import type { OrgPolicy, PolicyScope } from "../types/policy";+import {+ POLICY_SUCCESS_REFRESH_MS,+ resolvedPolicyRefreshIdentity,+ shouldAcceptPolicySnapshot,+} 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";-interface PolicyState {+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;- /** The resolved policy, or null when unmanaged. */- policy: OrgPolicy | null;- /** True after the first fetch resolves (success or fail-closed cache). */+ /** True after the first fetch resolves from the network, cache, or an error. */loaded: boolean;- fetchPolicy: () => Promise<void>;+ fetchPolicy: (+ accountId: string,+ authGeneration: number,+ reason?: "default" | "recovery"+ ) => Promise<void>;+ clearPolicy: () => void;}// Several components mount useAuth at startup; share one in-flight fetch// between them instead of hitting the API once per consumer.-let fetchInFlight: Promise<void> | null = null;+let fetchInFlight: {+ accountId: string;+ authGeneration: number;+ promise: Promise<void>;+} | null = null;+let fetchSequence = 0;+let lifecycleListenersReady = false;+let appVersionPromise: Promise<string | null> | null = null;++interface PolicyIpcSnapshot {+ success: boolean;+ status?: string;+ revision?: number;+ accountId?: string | null;+ authGeneration?: number | null;+ managed?: boolean;+ policy?: OrgPolicy | null;+ policyUpdatedAt?: string | null;+ endpointSupported?: boolean;+ code?: string;+ error?: string;+}++function readAppVersion(): Promise<string | null> {+ if (!appVersionPromise) {+ appVersionPromise =+ window.electronAPI+ .getAppVersion?.()+ .then((result) => result?.version ?? null)+ .catch((error) => {+ logger.error("Failed to read app version for workspace policy:", error);+ return null;+ }) ?? Promise.resolve(null);+ }+ return appVersionPromise;+}++function normalizeSnapshot(+ result: PolicyIpcSnapshot,+ current: PolicyState+): Required<+ Pick<+ PolicyIpcSnapshot,+ | "revision"+ | "accountId"+ | "authGeneration"+ | "managed"+ | "policy"+ | "policyUpdatedAt"+ | "endpointSupported"+ >+> {+ return {+ revision: result.revision ?? current.revision + 1,+ // A mixed new-renderer/old-main response has no credential identity. It+ // must never inherit the renderer's requested account or generation,+ // because an older main may be returning a global cache from another user.+ accountId: result.accountId ?? null,+ authGeneration: result.authGeneration ?? null,+ managed: Boolean(result.managed),+ policy: result.policy ?? null,+ policyUpdatedAt: result.policyUpdatedAt ?? null,+ endpointSupported: result.endpointSupported !== false,+ };+}-export const usePolicyStore = create<PolicyState>()((set) => ({+function applyPolicySnapshot(result: PolicyIpcSnapshot, appVersion: string | null): boolean {+ const current = usePolicyStore.getState();+ const snapshot = normalizeSnapshot(result, current);+ if (+ !current.accountId ||+ current.authGeneration == null ||+ snapshot.accountId !== current.accountId ||+ snapshot.authGeneration !== current.authGeneration ||+ !shouldAcceptPolicySnapshot(+ {+ accountId: current.accountId,+ authGeneration: current.authGeneration,+ revision: current.revision,+ },+ {+ accountId: snapshot.accountId,+ authGeneration: snapshot.authGeneration,+ revision: snapshot.revision,+ }+ )+ ) {+ return false;+ }++ if (snapshot.managed && !snapshot.policy) return false;+ usePolicyStore.setState({+ 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;+}++function ensurePolicyLifecycleListeners(): void {+ if (lifecycleListenersReady) return;+ lifecycleListenersReady = true;+ window.electronAPI.onWorkspacePolicyChanged?.((snapshot) => {+ void readAppVersion().then((appVersion) => applyPolicySnapshot(snapshot, appVersion));+ });+ const refreshResolvedPolicy = (): void => {+ const state = usePolicyStore.getState();+ const identity = resolvedPolicyRefreshIdentity(state);+ if (!identity) return;+ void state.fetchPolicy(identity.accountId, identity.authGeneration);+ };+ window.addEventListener("online", refreshResolvedPolicy);+ window.addEventListener("focus", refreshResolvedPolicy);+ window.setInterval(refreshResolvedPolicy, POLICY_SUCCESS_REFRESH_MS);+}++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: (): Promise<void> => {- fetchInFlight ??= (async () => {+ fetchPolicy: (+ accountId: string,+ authGeneration: number,+ reason: "default" | "recovery" = "default"+ ): Promise<void> => {+ ensurePolicyLifecycleListeners();+ if (fetchInFlight?.accountId === accountId && fetchInFlight.authGeneration === authGeneration) {+ return fetchInFlight.promise;+ }++ const previous = get();+ const sameIdentity =+ previous.accountId === accountId && previous.authGeneration === authGeneration;+ const preserveResolvedPolicy =+ sameIdentity && (previous.status === "managed" || previous.status === "unmanaged");+ const sequence = ++fetchSequence;+ if (!preserveResolvedPolicy) {+ set({+ 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?.();+ const result = await window.electronAPI.getWorkspacePolicy?.(+ accountId,+ authGeneration,+ reason+ );+ const appVersion = await versionPromise;+ if (sequence !== fetchSequence) return;if (result?.success) {- const managed = Boolean(result.managed);- const policy = result.policy ?? null;- set({ managed, policy, loaded: true });- if (managed && policy) reconcileSettingsWithPolicy(policy);- return;+ if (applyPolicySnapshot(result, appVersion)) return;+ throw new Error("Workspace policy response did not match the active credential");}- // Fetch failed with no cached policy: treat as unmanaged until a- // later fetch succeeds.- set({ loaded: true });+ throw new Error(result?.error || "Workspace policy is unavailable");} catch (error) {+ if (sequence !== fetchSequence) return;logger.error("Failed to fetch workspace policy:", error);- set({ loaded: true });+ const current = get();+ if (+ current.accountId === accountId &&+ (current.status === "managed" || current.status === "unmanaged")+ ) {+ set({ loaded: true });+ } else {+ set({+ accountId,+ status: "error",+ managed: false,+ policy: null,+ appVersion: await versionPromise,+ loaded: true,+ });+ }} finally {- fetchInFlight = null;+ if (+ fetchInFlight?.accountId === accountId &&+ fetchInFlight.authGeneration === authGeneration+ ) {+ fetchInFlight = null;+ }}})();- return fetchInFlight;++ fetchInFlight = { accountId, authGeneration, promise };+ return promise;+ },+ clearPolicy: (): void => {+ fetchSequence += 1;+ fetchInFlight = null;+ set({+ 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: Pick<PolicyState, "managed" | "policy">,+ state: PolicySelectorState,scope: PolicyScope,mode: InferenceMode): boolean {- if (!state.managed || !state.policy) return true;- return state.policy[scope].allowedModes.includes(mode);+ return isModeAllowedByPolicy(state, scope, mode);}/** Whether a BYOK provider id is allowed for a scope. Unmanaged users allow everything. */export function isProviderAllowed(- state: Pick<PolicyState, "managed" | "policy">,+ state: PolicySelectorState,scope: PolicyScope,providerId: string): boolean {- if (!state.managed || !state.policy) return true;- return state.policy[scope].allowedByokProviders.includes(providerId);+ return isProviderAllowedByPolicy(state, scope, providerId);}/** Whether an enterprise-cloud provider id is allowed. Unmanaged users allow everything. */export function isEnterpriseProviderAllowed(- state: Pick<PolicyState, "managed" | "policy">,+ state: PolicySelectorState,providerId: string): boolean {- if (!state.managed || !state.policy) return true;+ 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: Pick<PolicyState, "managed" | "policy">): boolean {- if (!state.managed || !state.policy) return true;+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: Pick<PolicyState, "managed" | "policy">): boolean {- if (!state.managed || !state.policy) return true;+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: Pick<PolicyState, "managed" | "policy">,+ state: PolicySelectorState,visibility: ShareVisibility): boolean {- if (!state.managed || !state.policy) return true;- const mode = state.policy.sharing.externalLinkSharing;- if (mode === "allowed") return true;- if (mode === "domain_only") return visibility !== "link";- return visibility !== "link" && visibility !== "domain";+ 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: Pick<PolicyState, "managed" | "policy">-): boolean | null {- if (!state.managed || !state.policy) return null;+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: Pick<PolicyState, "managed" | "policy">): boolean {- if (!state.managed || !state.policy) return true;+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: Pick<PolicyState, "managed" | "policy">-): number | null {- if (!state.managed || !state.policy) return null;+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: Pick<PolicyState, "managed" | "policy">,- managedBadge: string-): T[] {- if (!state.managed || !state.policy) return options;+>(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 });}--// Force any already-selected setting the policy disallows onto an allowed-// value, mirroring what the settings UI does on a manual change. Without this,-// stored settings would keep using values the org has blocked and the policy-// would only gate future UI clicks.-function reconcileSettingsWithPolicy(policy: OrgPolicy): void {- reconcileModes(policy);- reconcileProviders(policy);- reconcileFeaturesAndRetention(policy);-}--function reconcileModes(policy: OrgPolicy): void {- const settings = useSettingsStore.getState();-- if (!policy.transcription.allowedModes.includes(settings.transcriptionMode)) {- const next = policy.transcription.allowedModes[0];- if (next) {- settings.setTranscriptionMode(next);- settings.setUseLocalWhisper(next === "local");- settings.setCloudTranscriptionMode(next === "openwhispr" ? "openwhispr" : "byok");- }- }-- const llmNext = policy.llm.allowedModes[0];- if (!llmNext) return;- let switched = false;- for (const scope of Object.keys(INFERENCE_SCOPES) as InferenceScope[]) {- const config = selectResolvedLLMConfig(useSettingsStore.getState(), scope);- if (policy.llm.allowedModes.includes(config.mode)) continue;- const patch: Parameters<typeof setResolvedLLMConfig>[1] = {- mode: llmNext,- cloudMode: llmNext === "openwhispr" ? "openwhispr" : "byok",- };- if (!isProviderValidForMode(config.provider, llmNext)) {- patch.provider = "";- patch.model = "";- }- setResolvedLLMConfig(scope, patch);- switched = true;- }- if (- switched &&- (llmNext === "openwhispr" || llmNext === "self-hosted" || llmNext === "enterprise")- ) {- window.electronAPI?.llamaServerStop?.();- }-}--// The transcription provider is a single store field, so it is reconciled-// unconditionally. LLM providers are per-scope and only reconciled for the-// mode that actually uses them; stale values behind an inactive mode are-// filtered by the pickers when re-entered.-function reconcileProviders(policy: OrgPolicy): void {- const settings = useSettingsStore.getState();-- const transcriptionAllowed = policy.transcription.allowedByokProviders;- if (!transcriptionAllowed.includes(settings.cloudTranscriptionProvider)) {- const next = getTranscriptionProviders().find((p) => transcriptionAllowed.includes(p.id));- if (next) {- settings.setCloudTranscriptionProvider(next.id);- settings.setCloudTranscriptionModel(next.models[0]?.id ?? "");- }- }-- for (const scope of Object.keys(INFERENCE_SCOPES) as InferenceScope[]) {- const config = selectResolvedLLMConfig(useSettingsStore.getState(), scope);- if (!config.provider) continue;-- if (config.mode === "providers" && !policy.llm.allowedByokProviders.includes(config.provider)) {- const next = modelRegistry- .getCloudProviders()- .find((p) => policy.llm.allowedByokProviders.includes(p.id));- setResolvedLLMConfig(scope, {- provider: next?.id ?? "",- model: next ? (REASONING_PROVIDERS[next.id]?.models[0]?.value ?? "") : "",- });- }-- if (- config.mode === "enterprise" &&- !policy.llm.allowedEnterpriseProviders.includes(config.provider)- ) {- const next = ENTERPRISE_PROVIDERS.find((id) =>- policy.llm.allowedEnterpriseProviders.includes(id)- );- setResolvedLLMConfig(scope, {- provider: next ?? "",- model: next ? (REASONING_PROVIDERS[next]?.models[0]?.value ?? "") : "",- });- }- }-}--function reconcileFeaturesAndRetention(policy: OrgPolicy): void {- const settings = useSettingsStore.getState();-- if (!policy.features.agentEnabled && settings.useDictationAgent) {- settings.setUseDictationAgent(false);- }-- const historyMode = policy.dataRetention.localHistoryMode;- if (historyMode === "always_on" && !settings.dataRetentionEnabled) {- settings.setDataRetentionEnabled(true);- } else if (historyMode === "always_off" && settings.dataRetentionEnabled) {- settings.setDataRetentionEnabled(false);- }-- if (!policy.dataRetention.cloudBackupAllowed && settings.cloudBackupEnabled) {- settings.setCloudBackupEnabled(false);- }-- const maxDays = policy.dataRetention.audioRetentionMaxDays;- // audioRetentionDays === 0 means audio is not kept at all, which is always- // within any cap — only clamp values above the cap.- if (maxDays !== null && settings.audioRetentionDays > maxDays) {- settings.setAudioRetentionDays(maxDays);- }-}diff --git a/src/types/electron.ts b/src/types/electron.tsindex 01c9e569e..c9bf77540 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -13,6 +13,14 @@ export type SelfHostedType = "openai-compatible" | "lan";export type TranscriptionStatus = "completed" | "failed" | "pending" | "discarded";+export interface PolicyFailureMetadata {+ error?: string;+ code?: string;+ status?: number;+ minAppVersion?: string;+ details?: unknown;+}+export type TranscriptionErrorCode =| "TIMEOUT"| "NETWORK"@@ -764,22 +772,47 @@ declare global {onStopDictation?: (callback: () => void) => () => void;// STT config- getSttConfig?: () => Promise<{- success: boolean;- dictation: { mode: string };- notes: { mode: string };- streamingProvider: string;- } | null>;+ getSttConfig?: () => Promise<+ | ({+ success: boolean;+ dictation?: { mode: string };+ notes?: { mode: string };+ streamingProvider?: string;+ } & PolicyFailureMetadata)+ | null+ >;// Org policy (see src/types/policy.ts)- getWorkspacePolicy?: () => Promise<{+ getWorkspacePolicy?: (+ accountId?: string,+ expectedAuthGeneration?: number,+ reason?: "default" | "recovery"+ ) => Promise<{success: boolean;- status?: "ok" | "cached" | "error";+ status?: "network" | "cached" | "current" | "unsupported" | "restricted" | "error";+ revision?: number;+ accountId?: string | null;+ authGeneration?: number | null;managed?: boolean;policy?: OrgPolicy | null;policyUpdatedAt?: string | null;+ endpointSupported?: boolean;+ code?: string;error?: string;}>;+ onWorkspacePolicyChanged?: (+ callback: (snapshot: {+ success: true;+ status: "network" | "cached" | "current" | "unsupported";+ revision: number;+ accountId: string | null;+ authGeneration: number;+ managed: boolean;+ policy: OrgPolicy | null;+ policyUpdatedAt: string | null;+ endpointSupported: boolean;+ }) => void+ ) => () => void;getNoteRecordingConfig?: () => Promise<{success: boolean;@@ -1210,12 +1243,12 @@ declare global {freed_mb?: number;error?: string;}>;- cancelParakeetDownload: () => Promise<{- success: boolean;- message?: string;- error?: string;- code?: string;- }>;+ cancelParakeetDownload: () => Promise<+ {+ success: boolean;+ message?: string;+ } & PolicyFailureMetadata+ >;getParakeetDiagnostics: () => Promise<ParakeetDiagnosticsResult>;// Local AI model management@@ -1585,17 +1618,17 @@ declare global {cloudTranscribe?: (audioBuffer: ArrayBuffer,opts: { language?: string; prompt?: string; useCase?: string; diarization?: boolean }- ) => Promise<{- success: boolean;- text?: string;- warning?: string;- clientTranscriptionId?: string;- wordsUsed?: number;- wordsRemaining?: number;- limitReached?: boolean;- error?: string;- code?: string;- }>;+ ) => Promise<+ {+ success: boolean;+ text?: string;+ warning?: string;+ clientTranscriptionId?: string;+ wordsUsed?: number;+ wordsRemaining?: number;+ limitReached?: boolean;+ } & PolicyFailureMetadata+ >;cloudReason?: (text: string,opts: {@@ -1698,26 +1731,24 @@ declare global {body?: unknown;public?: boolean;expectedAuthGeneration?: number;- }) => Promise<{- success: boolean;- data?: unknown;- error?: string;- code?: string;- status?: number;- details?: unknown;- }>;+ }) => Promise<+ {+ success: boolean;+ data?: unknown;+ } & PolicyFailureMetadata+ >;// Cloud audio file transcriptiontranscribeAudioFileCloud?: (filePath: string,options?: { requestId?: string }- ) => Promise<{- success: boolean;- text?: string;- warning?: string;- error?: string;- code?: string;- }>;+ ) => Promise<+ {+ success: boolean;+ text?: string;+ warning?: string;+ } & PolicyFailureMetadata+ >;cancelUploadTranscription?: (requestId: string) => Promise<{ success: boolean }>;@@ -1757,21 +1788,18 @@ declare global {getPendingInvitationToken?: () => Promise<string | null>;// AssemblyAI Streaming- assemblyAiStreamingWarmup?: (options?: {- sampleRate?: number;- language?: string;- }) => Promise<{- success: boolean;- alreadyWarm?: boolean;- error?: string;- code?: string;- }>;- assemblyAiStreamingStart?: (options?: { sampleRate?: number; language?: string }) => Promise<{- success: boolean;- usedWarmConnection?: boolean;- error?: string;- code?: string;- }>;+ assemblyAiStreamingWarmup?: (options?: { sampleRate?: number; language?: string }) => Promise<+ {+ success: boolean;+ alreadyWarm?: boolean;+ } & PolicyFailureMetadata+ >;+ assemblyAiStreamingStart?: (options?: { sampleRate?: number; language?: string }) => Promise<+ {+ success: boolean;+ usedWarmConnection?: boolean;+ } & PolicyFailureMetadata+ >;assemblyAiStreamingSend?: (audioBuffer: ArrayBuffer) => void;assemblyAiStreamingForceEndpoint?: () => void;assemblyAiStreamingStop?: () => Promise<{@@ -1957,12 +1985,12 @@ declare global {sampleRate?: number;language?: string;forceNew?: boolean;- }) => Promise<{- success: boolean;- usedWarmConnection?: boolean;- error?: string;- code?: string;- }>;+ }) => Promise<+ {+ success: boolean;+ usedWarmConnection?: boolean;+ } & PolicyFailureMetadata+ >;deepgramStreamingSend?: (audioBuffer: ArrayBuffer) => void;deepgramStreamingFinalize?: () => void;deepgramStreamingStop?: () => Promise<{@@ -1987,13 +2015,13 @@ declare global {tenant?: string;language?: string;keyterms?: string[];- }) => Promise<{ success: boolean; error?: string; code?: string }>;+ }) => Promise<{ success: boolean } & PolicyFailureMetadata>;cortiStreamingStart?: (options?: {environment?: string;tenant?: string;language?: string;keyterms?: string[];- }) => Promise<{ success: boolean; error?: string; code?: string }>;+ }) => Promise<{ success: boolean } & PolicyFailureMetadata>;cortiStreamingSend?: (audioBuffer: ArrayBuffer) => void;cortiStreamingFinalize?: () => void;cortiStreamingStop?: () => Promise<{@@ -2042,7 +2070,7 @@ declare global {}) => void) => () => void;onAgentStreamError?: (- callback: (error: { error: string; code?: string }) => void+ callback: (error: PolicyFailureMetadata & { error: string }) => void) => () => void;onAgentStreamEnd?: (callback: () => void) => () => void;@@ -2051,16 +2079,17 @@ declare global {agentWebSearch?: (query: string,numResults?: number- ) => Promise<{- success: boolean;- results?: Array<{- title: string;- url: string;- text: string;- publishedDate?: string;- }>;- error?: string;- }>;+ ) => Promise<+ {+ success: boolean;+ results?: Array<{+ title: string;+ url: string;+ text: string;+ publishedDate?: string;+ }>;+ } & PolicyFailureMetadata+ >;// Google CalendargcalStartOAuth?: () => Promise<{ success: boolean; email?: string; error?: string }>;@@ -2108,19 +2137,20 @@ declare global {provider?: string;model?: string;language?: string;- }) => Promise<{ success: boolean; alreadyPrepared?: boolean; error?: string }>;+ }) => Promise<{ success: boolean; alreadyPrepared?: boolean } & PolicyFailureMetadata>;meetingTranscriptionStart?: (options: {provider?: string;model?: string;language?: string;noteId?: number | null;- }) => Promise<{- success: boolean;- error?: string;- systemAudioMode?: SystemAudioMode;- systemAudioStrategy?: SystemAudioStrategy;- oneOnOneAttendee?: { displayName: string; email: string | null } | null;- }>;+ }) => Promise<+ {+ success: boolean;+ systemAudioMode?: SystemAudioMode;+ systemAudioStrategy?: SystemAudioStrategy;+ oneOnOneAttendee?: { displayName: string; email: string | null } | null;+ } & PolicyFailureMetadata+ >;meetingTranscriptionSend?: (buffer: ArrayBuffer, source: "mic" | "system") => void;meetingTranscriptionStop?: () => Promise<{success: boolean;@@ -2256,11 +2286,11 @@ declare global {dictationRealtimeWarmup?: (options: {model?: string;mode?: "byok" | "openwhispr";- }) => Promise<{ success: boolean; error?: string }>;+ }) => Promise<{ success: boolean } & PolicyFailureMetadata>;dictationRealtimeStart?: (options: {model?: string;mode?: "byok" | "openwhispr";- }) => Promise<{ success: boolean; error?: string }>;+ }) => Promise<{ success: boolean } & PolicyFailureMetadata>;dictationRealtimeSend?: (buffer: ArrayBuffer) => void;dictationRealtimeStop?: () => Promise<{ success: boolean; text: string }>;onDictationRealtimePartial?: (callback: (text: string) => void) => () => void;diff --git a/src/utils/version.ts b/src/utils/version.tsindex 283e29716..f9e14aef8 100644--- a/src/utils/version.ts+++ b/src/utils/version.ts@@ -1,20 +1,21 @@-/**- * Compare two dotted numeric versions (e.g. "1.8.0" vs "1.10.2").- * Prerelease/build suffixes are ignored ("1.8.0-beta" compares as "1.8.0").- * Returns negative when a < b, positive when a > b, 0 when equal.- */+import {+ isCanonicalAppVersion as isCanonicalVersion,+ parseCanonicalAppVersion,+} from "../helpers/appVersion.js";++export function isCanonicalAppVersion(value: unknown): value is string {+ return isCanonicalVersion(value);+}++/** Returns negative when a < b, positive when a > b, and zero when equal. */export function compareAppVersions(a: string, b: string): number {- const parse = (version: string): number[] =>- version- .trim()- .split(".")- .map((segment) => parseInt(segment, 10) || 0);- const left = parse(a);- const right = parse(b);- const length = Math.max(left.length, right.length);- for (let i = 0; i < length; i += 1) {- const diff = (left[i] ?? 0) - (right[i] ?? 0);- if (diff !== 0) return diff;+ const left = parseCanonicalAppVersion(a);+ const right = parseCanonicalAppVersion(b);+ if (!left) return right ? -1 : 0;+ if (!right) return 1;+ for (let index = 0; index < 3; index += 1) {+ const difference = left[index] - right[index];+ if (difference !== 0) return difference;}return 0;}diff --git a/test/helpers/appVersion.test.js b/test/helpers/appVersion.test.jsnew file mode 100644index 000000000..a8a9a67d6--- /dev/null+++ b/test/helpers/appVersion.test.js@@ -0,0 +1,23 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/utils/version.ts");++test("recognizes only canonical three-part app versions", async () => {+ const { isCanonicalAppVersion } = await load();++ for (const version of ["0.0.0", "1.8.1", "24.10.300"]) {+ assert.equal(isCanonicalAppVersion(version), true, version);+ }+ for (const version of ["1.8", "1.8.1.0", "01.8.1", "1.8.1-beta.1", "required", "1.x.1"]) {+ assert.equal(isCanonicalAppVersion(version), false, version);+ }+});++test("an invalid installed version never satisfies a valid minimum", async () => {+ const { compareAppVersions } = await load();++ assert.equal(compareAppVersions("required", "1.8.1"), -1);+ assert.equal(compareAppVersions("1.8.1-beta.1", "1.8.1"), -1);+ assert.equal(compareAppVersions("1.9.0", "1.8.1"), 1);+});diff --git a/test/helpers/cloudApiRequest.test.js b/test/helpers/cloudApiRequest.test.jsindex 754d704b9..126c53186 100644--- a/test/helpers/cloudApiRequest.test.js+++ b/test/helpers/cloudApiRequest.test.js@@ -84,6 +84,7 @@ test("a stable authenticated request is bearer-only and returns parsed data", asassert.equal(url, "https://api.openwhispr.test/api/me/spaces");assert.equal(options.useSessionCookies, false);assert.equal(options.headers.Authorization, "Bearer token-a");+ assert.equal(options.headers["x-openwhispr-policy-version"], "1");assert.equal(options.headers["x-openwhispr-version"], "1.2.3");return new Response(JSON.stringify({ data: [{ id: "space-a" }] }));});@@ -104,6 +105,8 @@ test("public requests carry neither bearer nor cookies", async () => {const handler = createHandler(state, async (_url, options) => {assert.equal(options.useSessionCookies, false);assert.equal(options.headers.Authorization, undefined);+ assert.equal(options.headers["x-openwhispr-policy-version"], undefined);+ assert.equal(options.headers["x-openwhispr-version"], "1.2.3");return new Response(JSON.stringify({ data: { invite: "preview" } }));});@@ -114,3 +117,34 @@ test("public requests carry neither bearer nor cookies", async () => {});assert.equal(result.success, true);});++test("preserves policy and upgrade metadata from authenticated cloud failures", async () => {+ const state = { current: { token: "token-a", generation: 22 } };+ const handler = createHandler(+ state,+ async () =>+ new Response(+ JSON.stringify({+ error: "Upgrade required",+ code: "UPGRADE_REQUIRED",+ data: { minAppVersion: "2.0.0" },+ }),+ { status: 426 }+ )+ );++ const result = await handler({+ method: "POST",+ path: "/api/transcriptions/create",+ expectedAuthGeneration: 22,+ });++ assert.deepEqual(result, {+ success: false,+ error: "Upgrade required",+ status: 426,+ code: "UPGRADE_REQUIRED",+ details: { minAppVersion: "2.0.0" },+ minAppVersion: "2.0.0",+ });+});diff --git a/test/helpers/discardedRecording.test.js b/test/helpers/discardedRecording.test.jsindex 3815c71e9..26198e0aa 100644--- a/test/helpers/discardedRecording.test.js+++ b/test/helpers/discardedRecording.test.js@@ -38,3 +38,21 @@ test("handles missing settings", async () => {assert.equal(shouldSaveDiscardedRecording(null, 3), false);assert.equal(shouldSaveDiscardedRecording(undefined, 3), false);});++test("uses the policy-effective history setting without changing raw settings", async () => {+ const { shouldSaveDiscardedRecording } = await load();+ const settings = { ...base };+ const policyState = {+ status: "managed",+ appVersion: "1.8.1",+ policy: {+ dataRetention: {+ audioRetentionMaxDays: 7,+ localHistoryMode: "always_off",+ },+ },+ };++ assert.equal(shouldSaveDiscardedRecording(settings, 3, policyState), false);+ assert.deepEqual(settings, base);+});diff --git a/test/helpers/ipcPolicyHeaderCoverage.test.js b/test/helpers/ipcPolicyHeaderCoverage.test.jsnew file mode 100644index 000000000..96dfebbce--- /dev/null+++ b/test/helpers/ipcPolicyHeaderCoverage.test.js@@ -0,0 +1,60 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const path = require("node:path");++const source = fs.readFileSync(path.join(__dirname, "../../src/helpers/ipcHandlers.js"), "utf8");++test("all OpenWhispr multipart transcription transports use policy headers", () => {+ assert.match(source, /async function chunkedCloudTranscribe\([\s\S]*?policyHeaders/);+ assert.doesNotMatch(source, /postMultipart\(url, body, boundary, authHeader/);+ assert.doesNotMatch(source, /chunkedCloudTranscribe\(\{[\s\S]{0,300}?\bauthHeader,/);+ assert.ok(+ (+ source.match(+ /postMultipart\(\s*url,\s*body,\s*boundary,\s*(?:policyHeaders|withPolicyHeaders\(authHeader\))/g+ ) ?? []+ ).length >= 4+ );+});++test("direct policy-aware JSON and token routes apply the shared headers", () => {+ assert.match(+ source,+ /const postServerToken[\s\S]{0,900}?headers:\s*withPolicyHeaders\(/,+ "the shared realtime-token helper must apply policy headers"+ );+ for (const route of [+ "streaming-token",+ "deepgram-streaming-token",+ "reason",+ "agent/stream",+ "agent/web-search",+ ]) {+ const directCalls = source.match(+ new RegExp(+ "proxyFetch\\(`\\$\\{apiUrl\\}/api/" ++ route ++ "`[\\s\\S]{0,300}?headers:\\s*withPolicyHeaders\\(",+ "g"+ )+ );+ assert.ok(directCalls?.length, `/api/${route} direct calls must use policy 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/);+ }+});diff --git a/test/helpers/meetingPolicyStartRecovery.test.js b/test/helpers/meetingPolicyStartRecovery.test.jsnew file mode 100644index 000000000..34871ecb4--- /dev/null+++ b/test/helpers/meetingPolicyStartRecovery.test.js@@ -0,0 +1,171 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { EventEmitter } = require("node:events");+const fs = require("node:fs");+const Module = require("node:module");+const os = require("node:os");+const path = require("node:path");++function loadMeetingDetectionEngine() {+ const originalLoad = Module._load;+ Module._load = function loadWithMeetingMocks(request, parent, isMain) {+ if (request === "electron") {+ return { shell: { openExternal: async () => {} } };+ }+ if (request === "./windowBroadcast") {+ return { broadcastToWindows() {} };+ }+ return originalLoad.call(this, request, parent, isMain);+ };++ try {+ const modulePath = require.resolve("../../src/helpers/meetingDetectionEngine");+ delete require.cache[modulePath];+ return require(modulePath);+ } finally {+ Module._load = originalLoad;+ }+}++test("a policy-rejected automatic meeting start restores manager mode before clearing", async (t) => {+ const MeetingDetectionEngine = loadMeetingDetectionEngine();+ const reminderScheduler = { getActiveMeetingState: () => ({}) };+ const processDetector = new EventEmitter();+ const audioDetector = Object.assign(new EventEmitter(), {+ resetPrompt() {},+ setUserRecording() {},+ });+ let navigationRequest = null;+ const windowManager = {+ notificationPrefs: {},+ queueMeetingNoteNavigation: async (request) => {+ navigationRequest = request;+ },+ };+ const databaseManager = {+ getActiveEvents: () => [],+ saveNote: () => ({ note: { id: 41, title: "New note" } }),+ getMeetingsFolder: () => ({ id: 7 }),+ };+ const engine = new MeetingDetectionEngine(+ reminderScheduler,+ processDetector,+ audioDetector,+ windowManager,+ databaseManager+ );++ await engine.startManualMeeting();+ assert.equal(engine._meetingModeActive, true);+ assert.deepEqual(+ { noteId: navigationRequest.noteId, folderId: navigationRequest.folderId },+ { noteId: 41, folderId: 7 }+ );++ 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-meeting-policy-test-"));+ const vite = await createServer({+ root: path.resolve(__dirname, "../../src"),+ cacheDir,+ configFile: false,+ appType: "custom",+ logLevel: "silent",+ optimizeDeps: { noDiscovery: true },+ plugins: [+ {+ name: "meeting-policy-test-app-version",+ enforce: "pre",+ resolveId(source) {+ return source.endsWith("/helpers/appVersion.js") ? "\0meeting-policy-app-version" : null;+ },+ load(id) {+ if (id !== "\0meeting-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 { handleMeetingRecordingRequest } = await vite.ssrLoadModule(+ "/helpers/meetingRecordingRequest.ts"+ );+ const { startRecording, useMeetingRecordingStore } = await vite.ssrLoadModule(+ "/stores/meetingRecordingStore.ts"+ );+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");+ usePolicyStore.setState({+ status: "managed",+ appVersion: "1.8.1",+ policy: {+ version: 1,+ transcription: { allowedModes: [], allowedByokProviders: [] },+ llm: {+ allowedModes: ["openwhispr"],+ allowedByokProviders: [],+ allowedEnterpriseProviders: [],+ },+ features: { agentEnabled: false, webSearchEnabled: false },+ sharing: { externalLinkSharing: "disabled" },+ dataRetention: {+ audioRetentionMaxDays: null,+ localHistoryMode: "user_choice",+ cloudBackupAllowed: false,+ },+ minAppVersion: null,+ },+ });++ const lifecycle = [];+ await handleMeetingRecordingRequest({+ args: {+ noteId: navigationRequest.noteId,+ noteTitle: "New note",+ folderId: navigationRequest.folderId,+ },+ startRecording,+ restoreFromMeetingMode: async () => {+ lifecycle.push("restored");+ engine.setMeetingModeActive(false);+ },+ onHandled: () => lifecycle.push("handled"),+ });++ assert.equal(engine._meetingModeActive, false);+ assert.deepEqual(lifecycle, ["restored", "handled"]);+ assert.equal(+ useMeetingRecordingStore.getState().error,+ "Meeting transcription is restricted by your organization."+ );+});diff --git a/test/helpers/policyLifecycle.test.js b/test/helpers/policyLifecycle.test.jsnew file mode 100644index 000000000..d0e1c1354--- /dev/null+++ b/test/helpers/policyLifecycle.test.js@@ -0,0 +1,40 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/stores/policyLifecycle.ts");++test("accepts only monotonic snapshots for the active account and credential generation", async () => {+ const { shouldAcceptPolicySnapshot } = await load();+ const current = { accountId: "account-a", authGeneration: 7, revision: 4 };++ assert.equal(+ shouldAcceptPolicySnapshot(current, { accountId: "account-a", authGeneration: 7, revision: 5 }),+ true+ );+ assert.equal(+ shouldAcceptPolicySnapshot(current, { accountId: "account-a", authGeneration: 7, revision: 3 }),+ false+ );+ assert.equal(+ shouldAcceptPolicySnapshot(current, { accountId: "account-b", authGeneration: 7, revision: 5 }),+ false+ );+ assert.equal(+ shouldAcceptPolicySnapshot(current, { accountId: "account-a", authGeneration: 8, revision: 5 }),+ false+ );+});++test("selects only resolved policy identities for cadence and focus refresh", async () => {+ const { resolvedPolicyRefreshIdentity } = await load();+ const identity = { accountId: "account-a", authGeneration: 7 };++ assert.deepEqual(resolvedPolicyRefreshIdentity({ ...identity, status: "managed" }), identity);+ assert.deepEqual(resolvedPolicyRefreshIdentity({ ...identity, status: "unmanaged" }), identity);+ assert.deepEqual(resolvedPolicyRefreshIdentity({ ...identity, status: "error" }), identity);+ assert.equal(resolvedPolicyRefreshIdentity({ ...identity, status: "loading" }), null);+ assert.equal(+ resolvedPolicyRefreshIdentity({ status: "managed", accountId: null, authGeneration: null }),+ null+ );+});diff --git a/test/helpers/policyPreferencePreservation.test.js b/test/helpers/policyPreferencePreservation.test.jsnew file mode 100644index 000000000..f6f5c0f7b--- /dev/null+++ b/test/helpers/policyPreferencePreservation.test.js@@ -0,0 +1,120 @@+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");++test("managed policy gates preserve the user's raw preferences", async (t) => {+ const originalWindow = globalThis.window;+ const originalLocalStorage = globalThis.localStorage;+ const values = new Map([+ ["transcriptionMode", "local"],+ ["useLocalWhisper", "true"],+ ["cloudBackupEnabled", "true"],+ ["dataRetentionEnabled", "true"],+ ["audioRetentionDays", "90"],+ ]);+ const storage = {+ getItem: (key) => values.get(key) ?? null,+ setItem: (key, value) => values.set(key, String(value)),+ removeItem: (key) => values.delete(key),+ };+ const policy = {+ version: 1,+ transcription: { allowedModes: ["openwhispr"], allowedByokProviders: [] },+ llm: {+ allowedModes: ["openwhispr"],+ allowedByokProviders: [],+ allowedEnterpriseProviders: [],+ },+ features: { agentEnabled: false, webSearchEnabled: false },+ sharing: { externalLinkSharing: "disabled" },+ dataRetention: {+ audioRetentionMaxDays: 7,+ localHistoryMode: "always_off",+ cloudBackupAllowed: false,+ },+ minAppVersion: null,+ };+ globalThis.localStorage = storage;+ globalThis.window = {+ localStorage: storage,+ addEventListener() {},+ setInterval() {+ return 1;+ },+ electronAPI: {+ getAppVersion: async () => ({ version: "1.8.1" }),+ getWorkspacePolicy: async () => ({+ success: true,+ status: "network",+ revision: 1,+ accountId: "account-a",+ authGeneration: 1,+ managed: true,+ policy,+ policyUpdatedAt: "2026-08-05T00:00:00.000Z",+ endpointSupported: true,+ }),+ onWorkspacePolicyChanged() {},+ },+ };++ const { createServer } = await import("vite");+ const cacheDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-policy-prefs-test-"));+ const vite = await createServer({+ root: path.resolve(__dirname, "../../src"),+ cacheDir,+ configFile: false,+ appType: "custom",+ logLevel: "silent",+ optimizeDeps: { noDiscovery: true },+ plugins: [+ {+ name: "policy-preferences-test-app-version",+ enforce: "pre",+ resolveId(source) {+ return source.endsWith("/helpers/appVersion.js") ? "\0policy-prefs-app-version" : null;+ },+ load(id) {+ if (id !== "\0policy-prefs-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;+ }+ `;+ },+ },+ ],+ server: { middlewareMode: true },+ });+ 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 { usePolicyStore, isCloudBackupAllowed, lockedLocalHistoryValue } =+ await vite.ssrLoadModule("/stores/policyStore.ts");+ const { useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");+ const before = useSettingsStore.getState();+ assert.equal(before.transcriptionMode, "local");+ assert.equal(before.cloudBackupEnabled, true);++ await usePolicyStore.getState().fetchPolicy("account-a", 1);++ const after = useSettingsStore.getState();+ assert.equal(after.transcriptionMode, "local");+ assert.equal(after.cloudBackupEnabled, true);+ assert.equal(after.dataRetentionEnabled, true);+ assert.equal(after.audioRetentionDays, 90);+ assert.equal(isCloudBackupAllowed(usePolicyStore.getState()), false);+ assert.equal(lockedLocalHistoryValue(usePolicyStore.getState()), false);+});diff --git a/test/helpers/policyRequestHeaders.test.js b/test/helpers/policyRequestHeaders.test.jsnew file mode 100644index 000000000..c5472d218--- /dev/null+++ b/test/helpers/policyRequestHeaders.test.js@@ -0,0 +1,37 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const {+ POLICY_CAPABILITY_VERSION,+ withPolicyRequestHeaders,+} = require("../../src/helpers/policyRequestHeaders");++test("adds the exact policy capability and canonical app version headers", () => {+ assert.equal(POLICY_CAPABILITY_VERSION, "1");+ assert.deepEqual(withPolicyRequestHeaders({ Authorization: "Bearer token" }, "1.8.1"), {+ Authorization: "Bearer token",+ "x-openwhispr-policy-version": "1",+ "x-openwhispr-version": "1.8.1",+ });+});++test("does not allow callers to override desktop policy capability headers", () => {+ assert.deepEqual(+ withPolicyRequestHeaders(+ {+ "x-openwhispr-policy-version": "2",+ "x-openwhispr-version": "0.0.1",+ },+ "1.8.1"+ ),+ {+ "x-openwhispr-policy-version": "1",+ "x-openwhispr-version": "1.8.1",+ }+ );+});++test("rejects a non-canonical app version instead of advertising a malformed client", () => {+ assert.throws(() => withPolicyRequestHeaders({}, "1.8"), /canonical app version/i);+ assert.throws(() => withPolicyRequestHeaders({}, "1.8.1-beta.1"), /canonical app version/i);+});diff --git a/test/helpers/policyResponseError.test.js b/test/helpers/policyResponseError.test.jsnew file mode 100644index 000000000..5077bc97b--- /dev/null+++ b/test/helpers/policyResponseError.test.js@@ -0,0 +1,48 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const {+ createPolicyResponseError,+ readPolicyResponseError,+ toPolicyFailure,+} = require("../../src/helpers/policyResponseError");++test("preserves policy denial code, status, details, and minimum version", async () => {+ for (const [status, code] of [+ [403, "POLICY_TRANSCRIPTION_BLOCKED"],+ [426, "UPGRADE_REQUIRED"],+ ]) {+ const response = new Response(+ JSON.stringify({+ error: "Request blocked by workspace policy",+ code,+ data: { minAppVersion: "2.0.0", action: "transcription" },+ }),+ { status }+ );+ const error = await readPolicyResponseError(response, "Request failed");++ assert.deepEqual(toPolicyFailure(error), {+ success: false,+ error: "Request blocked by workspace policy",+ code,+ status,+ minAppVersion: "2.0.0",+ details: { minAppVersion: "2.0.0", action: "transcription" },+ });+ }+});++test("normalizes parsed multipart policy errors without losing legacy statusCode", () => {+ const error = createPolicyResponseError(+ 426,+ { error: { message: "Update OpenWhispr" }, code: "UPGRADE_REQUIRED", minAppVersion: "2.1.0" },+ "Transcription failed"+ );++ assert.equal(error.message, "Update OpenWhispr");+ assert.equal(error.code, "UPGRADE_REQUIRED");+ assert.equal(error.status, 426);+ assert.equal(error.statusCode, 426);+ assert.equal(error.minAppVersion, "2.1.0");+});diff --git a/test/helpers/policyRules.test.js b/test/helpers/policyRules.test.jsnew file mode 100644index 000000000..a31c18cda--- /dev/null+++ b/test/helpers/policyRules.test.js@@ -0,0 +1,311 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/stores/policyRules.ts");++const policy = {+ version: 1,+ transcription: {+ allowedModes: ["openwhispr", "local"],+ allowedByokProviders: ["openai"],+ },+ llm: {+ allowedModes: ["openwhispr", "providers"],+ allowedByokProviders: ["openai"],+ allowedEnterpriseProviders: [],+ },+ features: { agentEnabled: true, webSearchEnabled: true },+ sharing: { externalLinkSharing: "allowed" },+ dataRetention: {+ audioRetentionMaxDays: null,+ localHistoryMode: "user_choice",+ cloudBackupAllowed: true,+ },+ minAppVersion: null,+};++test("allows guests and resolved unmanaged accounts", async () => {+ const { isPolicyActionAllowed } = await load();++ assert.equal(isPolicyActionAllowed({ status: "idle", policy: null, appVersion: null }), true);+ assert.equal(+ isPolicyActionAllowed({ status: "unmanaged", policy: null, appVersion: null }),+ true+ );+});++test("blocks authenticated actions while policy is loading or unavailable", async () => {+ const { isPolicyActionAllowed } = await load();++ assert.equal(+ isPolicyActionAllowed({ status: "loading", policy: null, appVersion: "1.8.1" }),+ false+ );+ assert.equal(+ isPolicyActionAllowed({ status: "error", policy: null, appVersion: "1.8.1" }),+ false+ );+});++test("enforces the managed minimum app version", async () => {+ const { isPolicyActionAllowed } = await load();+ const versionedPolicy = { ...policy, minAppVersion: "1.9.0" };++ assert.equal(+ isPolicyActionAllowed({ status: "managed", policy: versionedPolicy, appVersion: "1.8.1" }),+ false+ );+ assert.equal(+ isPolicyActionAllowed({ status: "managed", policy: versionedPolicy, appVersion: "1.9.0" }),+ true+ );+ assert.equal(+ isPolicyActionAllowed({ status: "managed", policy: versionedPolicy, appVersion: null }),+ false+ );+});++test("mode and provider decisions fail closed for empty allowlists", async () => {+ const { isModeAllowedByPolicy, isProviderAllowedByPolicy } = await load();+ const emptyPolicy = {+ ...policy,+ transcription: { allowedModes: [], allowedByokProviders: [] },+ };+ const snapshot = { status: "managed", policy: emptyPolicy, appVersion: "1.8.1" };++ assert.equal(isModeAllowedByPolicy(snapshot, "transcription", "local"), false);+ assert.equal(isProviderAllowedByPolicy(snapshot, "transcription", "openai"), false);+});++test("empty managed scope allowlists make that scope unavailable", async () => {+ const { isLlmSelectionAllowed } = await load();+ const emptyLlmPolicy = {+ ...policy,+ llm: { allowedModes: [], allowedByokProviders: [], allowedEnterpriseProviders: [] },+ };+ const snapshot = { status: "managed", policy: emptyLlmPolicy, appVersion: "1.8.1" };++ assert.equal(isLlmSelectionAllowed(snapshot, { mode: "providers", provider: "openai" }), false);+ assert.equal(+ isLlmSelectionAllowed(+ { status: "unmanaged", policy: null, appVersion: null },+ { mode: "providers", provider: "openai" }+ ),+ true+ );+});++test("LLM dispatch requires an allowed mode and provider", async () => {+ const { isLlmSelectionAllowed } = await load();+ const noProviderPolicy = {+ ...policy,+ llm: {+ allowedModes: ["providers", "local"],+ allowedByokProviders: [],+ allowedEnterpriseProviders: [],+ },+ };+ const snapshot = { status: "managed", policy: noProviderPolicy, appVersion: "1.8.1" };++ assert.equal(isLlmSelectionAllowed(snapshot, { mode: "providers", provider: "openai" }), false);+ assert.equal(isLlmSelectionAllowed(snapshot, { mode: "local", provider: "local" }), true);+ assert.equal(isLlmSelectionAllowed(snapshot, { mode: "enterprise", provider: "bedrock" }), false);+});++test("blocks transcription contexts whose stored mode is disallowed", async () => {+ const { isTranscriptionSelectionAllowed } = await load();+ const snapshot = { status: "managed", policy, appVersion: "1.8.1" };++ assert.equal(+ isTranscriptionSelectionAllowed(snapshot, { mode: "self-hosted", provider: "" }),+ false+ );+ assert.equal(isTranscriptionSelectionAllowed(snapshot, { mode: "local", provider: "" }), true);+});++test("blocks BYOK transcription when no provider is allowed", async () => {+ const { isTranscriptionSelectionAllowed } = await load();+ const noProviderPolicy = {+ ...policy,+ transcription: { allowedModes: ["providers"], allowedByokProviders: [] },+ };+ const snapshot = { status: "managed", policy: noProviderPolicy, appVersion: "1.8.1" };++ assert.equal(+ isTranscriptionSelectionAllowed(snapshot, { mode: "providers", provider: "openai" }),+ false+ );+});++test("does not require a BYOK provider for local transcription", async () => {+ const { isTranscriptionSelectionAllowed } = await load();+ const localOnlyPolicy = {+ ...policy,+ transcription: { allowedModes: ["local"], allowedByokProviders: [] },+ };+ const snapshot = { status: "managed", policy: localOnlyPolicy, appVersion: "1.8.1" };++ assert.equal(+ isTranscriptionSelectionAllowed(snapshot, { mode: "local", provider: "openai" }),+ true+ );+});++test("domain-only sharing permits only private recovery and domain visibility", async () => {+ const { isShareActionAllowed, isShareVisibilityAllowed } = await load();+ const snapshot = {+ status: "managed",+ policy: {+ ...policy,+ sharing: { externalLinkSharing: "domain_only" },+ },+ appVersion: "1.8.1",+ };++ assert.equal(isShareVisibilityAllowed(snapshot, "private"), true);+ assert.equal(isShareVisibilityAllowed(snapshot, "domain"), true);+ assert.equal(isShareVisibilityAllowed(snapshot, "invited"), false);+ assert.equal(isShareVisibilityAllowed(snapshot, "link"), false);+ assert.equal(isShareActionAllowed(snapshot, "copy-link", "link"), false);+ assert.equal(isShareActionAllowed(snapshot, "rotate-link", "link"), false);+ assert.equal(isShareActionAllowed(snapshot, "invite", "private"), false);+});++test("sharing recovery remains available when exposure-increasing actions are blocked", async () => {+ const { isShareActionAllowed } = await load();+ const blockedSnapshots = [+ { status: "loading", policy: null, appVersion: "1.8.1" },+ {+ status: "managed",+ policy: { ...policy, sharing: { externalLinkSharing: "disabled" } },+ appVersion: "1.8.1",+ },+ {+ status: "managed",+ policy: { ...policy, minAppVersion: "2.0.0" },+ appVersion: "1.8.1",+ },+ ];++ for (const snapshot of blockedSnapshots) {+ assert.equal(isShareActionAllowed(snapshot, "make-private", "link"), true);+ assert.equal(isShareActionAllowed(snapshot, "revoke-invitation", "invited"), true);+ assert.equal(isShareActionAllowed(snapshot, "remove-grant", "invited"), true);+ assert.equal(isShareActionAllowed(snapshot, "create-link", "private"), false);+ }+});++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" };+ const alwaysOn = {+ status: "managed",+ policy: {+ ...policy,+ dataRetention: { ...policy.dataRetention, localHistoryMode: "always_on" },+ },+ appVersion: "1.8.1",+ };+ const alwaysOff = {+ status: "managed",+ policy: {+ ...policy,+ dataRetention: { ...policy.dataRetention, localHistoryMode: "always_off" },+ },+ appVersion: "1.8.1",+ };++ assert.equal(effectiveLocalHistoryEnabled(unmanaged, false), false);+ assert.equal(effectiveLocalHistoryEnabled(unmanaged, true), true);+ assert.equal(effectiveLocalHistoryEnabled(alwaysOn, false), true);+ assert.equal(effectiveLocalHistoryEnabled(alwaysOff, true), false);+});++test("caps effective audio retention while preserving disabled and raw values", async () => {+ const { effectiveAudioRetentionDays } = await load();+ const unmanaged = { status: "unmanaged", policy: null, appVersion: "1.8.1" };+ const capped = {+ status: "managed",+ policy: {+ ...policy,+ dataRetention: { ...policy.dataRetention, audioRetentionMaxDays: 7 },+ },+ appVersion: "1.8.1",+ };++ assert.equal(effectiveAudioRetentionDays(unmanaged, 90), 90);+ assert.equal(effectiveAudioRetentionDays(capped, 90), 7);+ assert.equal(effectiveAudioRetentionDays(capped, 3), 3);+ assert.equal(effectiveAudioRetentionDays(capped, 0), 0);+});++test("an enabled cloud-backup preference can always be turned off", async () => {+ const { canChangeCloudBackupPreference } = await load();++ assert.equal(canChangeCloudBackupPreference(false, true), true);+ assert.equal(canChangeCloudBackupPreference(false, false), false);+ assert.equal(canChangeCloudBackupPreference(true, false), true);+});++test("re-entering providers mode replaces a dormant policy-disallowed provider", async () => {+ const { reconcileCloudProviderSelection } = await load();+ const allowedProviders = [+ { id: "openai", models: [{ id: "whisper-1" }] },+ { id: "mistral", models: [{ id: "voxtral-mini" }] },+ ];++ assert.deepEqual(+ reconcileCloudProviderSelection({+ selectedProvider: "groq",+ selectedModel: "whisper-large-v3",+ allowedProviders,+ customAllowed: false,+ hasCustomUrl: false,+ }),+ { provider: "openai", model: "whisper-1" }+ );+ assert.equal(+ reconcileCloudProviderSelection({+ selectedProvider: "mistral",+ selectedModel: "voxtral-mini",+ allowedProviders,+ customAllowed: false,+ hasCustomUrl: false,+ }),+ null+ );+});++test("active control-panel views reroute on their specific policy capability", async () => {+ const { isControlPanelViewAllowed } = await load();++ assert.equal(isControlPanelViewAllowed("chat", false, true), false);+ assert.equal(isControlPanelViewAllowed("chat", true, true), true);+ assert.equal(isControlPanelViewAllowed("upload", true, false), false);+ assert.equal(isControlPanelViewAllowed("upload", false, true), true);+ assert.equal(isControlPanelViewAllowed("home", false, false), true);+});diff --git a/test/helpers/policyValidation.test.js b/test/helpers/policyValidation.test.jsindex fa84f0008..9941f04e3 100644--- a/test/helpers/policyValidation.test.js+++ b/test/helpers/policyValidation.test.js@@ -28,19 +28,54 @@ test("accepts a well-formed policy", () => {assert.equal(isValidPolicyShape(validPolicy()), true);});-test("accepts empty provider allowlists", () => {+test("ignores stale additive analytics metadata", () => {const policy = validPolicy();- policy.transcription.allowedByokProviders = [];- policy.llm.allowedByokProviders = [];+ policy.analytics = {+ enabled: false,+ provider: "legacy-server-field",+ };++ assert.equal(isValidPolicyShape(policy), true);+});++test("requires the supported policy schema version", () => {+ for (const version of [undefined, null, 0, 2, "1"]) {+ const policy = validPolicy();+ policy.version = version;+ assert.equal(isValidPolicyShape(policy), false, String(version));+ }+});++test("accepts empty allowlists", () => {+ const policy = validPolicy();+ policy.transcription.allowedModes = [];+ policy.llm.allowedModes = [];policy.llm.allowedEnterpriseProviders = [];assert.equal(isValidPolicyShape(policy), true);});-test("rejects empty allowedModes (canonical schema enforces min 1)", () => {- for (const scope of ["transcription", "llm"]) {+test("rejects unknown modes and providers", () => {+ const cases = [+ [+ "transcription.allowedModes",+ (policy) => policy.transcription.allowedModes.push("enterprise"),+ ],+ ["llm.allowedModes", (policy) => policy.llm.allowedModes.push("future-mode")],+ [+ "transcription.allowedByokProviders",+ (policy) => policy.transcription.allowedByokProviders.push("future-stt"),+ ],+ ["llm.allowedByokProviders", (policy) => policy.llm.allowedByokProviders.push("future-llm")],+ [+ "llm.allowedEnterpriseProviders",+ (policy) => policy.llm.allowedEnterpriseProviders.push("future-enterprise"),+ ],+ ];++ for (const [label, mutate] of cases) {const policy = validPolicy();- policy[scope].allowedModes = [];- assert.equal(isValidPolicyShape(policy), false, `${scope}.allowedModes empty`);+ mutate(policy);+ assert.equal(isValidPolicyShape(policy), false, label);}});@@ -114,9 +149,15 @@ test("rejects mistyped retention fields", () => {const cappedDays = validPolicy();cappedDays.dataRetention.audioRetentionMaxDays = 30;assert.equal(isValidPolicyShape(cappedDays), true);++ for (const value of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) {+ const policy = validPolicy();+ policy.dataRetention.audioRetentionMaxDays = value;+ assert.equal(isValidPolicyShape(policy), false, String(value));+ }});-test("accepts null or string minAppVersion, rejects other types", () => {+test("accepts null or canonical minAppVersion, rejects malformed versions", () => {const versioned = validPolicy();versioned.minAppVersion = "1.8.0";assert.equal(isValidPolicyShape(versioned), true);@@ -125,6 +166,12 @@ test("accepts null or string minAppVersion, rejects other types", () => {badVersion.minAppVersion = 1.8;assert.equal(isValidPolicyShape(badVersion), false);+ for (const value of ["1.8", "01.8.1", "1.8.1-beta.1", "required"]) {+ const policy = validPolicy();+ policy.minAppVersion = value;+ assert.equal(isValidPolicyShape(policy), false, value);+ }+const noVersion = validPolicy();delete noVersion.minAppVersion;assert.equal(isValidPolicyShape(noVersion), false);diff --git a/test/helpers/retentionSettings.test.js b/test/helpers/retentionSettings.test.jsindex 0bb689c52..a86d28317 100644--- a/test/helpers/retentionSettings.test.js+++ b/test/helpers/retentionSettings.test.js@@ -4,6 +4,7 @@ const assert = require("node:assert/strict");const {DEFAULT_RETENTION_SETTINGS,applyRetentionSettings,+ createRetentionSettingsHandler,} = require("../../src/helpers/retentionSettings");test("reports a change when a retention period is shortened", () => {@@ -40,3 +41,39 @@ test("keeps the current value when an incoming value is missing or unusable", ()});}});++test("only the main renderer can replace process-global retention settings", () => {+ const mainRenderer = {};+ const auxiliaryRenderers = [{}, {}, {}];+ const managedSettings = { audioRetentionDays: 7, transcriptRetentionDays: 30 };+ let current = { ...DEFAULT_RETENTION_SETTINGS };+ let cleanupRuns = 0;+ const handleRetentionSettingsChanged = createRetentionSettingsHandler({+ getCurrentSettings: () => current,+ getOwner: () => mainRenderer,+ onSettingsChanged: (settings) => {+ current = settings;+ cleanupRuns += 1;+ },+ });++ handleRetentionSettingsChanged({ sender: mainRenderer }, managedSettings);+ assert.deepEqual(current, managedSettings);+ assert.equal(cleanupRuns, 1);++ for (const auxiliaryRenderer of auxiliaryRenderers) {+ handleRetentionSettingsChanged(+ { sender: auxiliaryRenderer },+ { audioRetentionDays: 90, transcriptRetentionDays: 0 }+ );+ assert.deepEqual(current, managedSettings);+ assert.equal(cleanupRuns, 1);+ }++ handleRetentionSettingsChanged(+ { sender: mainRenderer },+ { audioRetentionDays: 90, transcriptRetentionDays: 0 }+ );+ assert.deepEqual(current, { audioRetentionDays: 90, transcriptRetentionDays: 0 });+ assert.equal(cleanupRuns, 2);+});diff --git a/test/helpers/sttConfigRequest.test.js b/test/helpers/sttConfigRequest.test.jsnew file mode 100644index 000000000..3ac3ce167--- /dev/null+++ b/test/helpers/sttConfigRequest.test.js@@ -0,0 +1,58 @@+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/workspacePolicyCache.test.js b/test/helpers/workspacePolicyCache.test.jsnew file mode 100644index 000000000..7d8344049--- /dev/null+++ b/test/helpers/workspacePolicyCache.test.js@@ -0,0 +1,97 @@+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 {+ readWorkspacePolicyCache,+ writeWorkspacePolicyCache,+} = require("../../src/helpers/workspacePolicyCache");++const policyData = {+ managed: false,+ policy: null,+ policyUpdatedAt: null,+ endpointSupported: true,+};++function withTempCache(run) {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-policy-cache-"));+ const cachePath = path.join(tempDir, "workspace-policy.json");+ try {+ run(cachePath);+ } finally {+ fs.rmSync(tempDir, { recursive: true, force: true });+ }+}++test("keys policy verdicts by API origin and the credential actually used", () => {+ withTempCache((cachePath) => {+ const identity = {+ apiOrigin: "https://api.openwhispr.test",+ credentialHash: "credential-a",+ accountId: "account-a",+ };+ writeWorkspacePolicyCache(cachePath, identity, policyData);++ assert.deepEqual(readWorkspacePolicyCache(cachePath, identity), policyData);+ assert.equal(+ readWorkspacePolicyCache(cachePath, { ...identity, credentialHash: "credential-b" }),+ null+ );+ assert.equal(+ readWorkspacePolicyCache(cachePath, {+ ...identity,+ apiOrigin: "https://self-hosted.openwhispr.test",+ }),+ null+ );+ assert.deepEqual(+ readWorkspacePolicyCache(cachePath, { ...identity, accountId: "account-b" }),+ policyData+ );+ });+});++test("preserves cached verdicts for multiple credentials and origins", () => {+ withTempCache((cachePath) => {+ const first = {+ apiOrigin: "https://api.openwhispr.test",+ credentialHash: "credential-a",+ accountId: "account-a",+ };+ const second = {+ apiOrigin: "https://self-hosted.openwhispr.test",+ credentialHash: "credential-b",+ accountId: "account-b",+ };+ writeWorkspacePolicyCache(cachePath, first, policyData);+ writeWorkspacePolicyCache(cachePath, second, {+ ...policyData,+ endpointSupported: false,+ });++ assert.equal(readWorkspacePolicyCache(cachePath, first)?.endpointSupported, true);+ assert.equal(readWorkspacePolicyCache(cachePath, second)?.endpointSupported, false);+ });+});++test("ignores legacy account-only and malformed cache envelopes", () => {+ withTempCache((cachePath) => {+ fs.writeFileSync(+ cachePath,+ JSON.stringify({ accountId: "account-a", data: policyData }),+ "utf8"+ );+ const identity = {+ apiOrigin: "https://api.openwhispr.test",+ credentialHash: "credential-a",+ accountId: "account-a",+ };+ assert.equal(readWorkspacePolicyCache(cachePath, identity), null);++ fs.writeFileSync(cachePath, JSON.stringify({ version: 2, entries: "invalid" }), "utf8");+ assert.equal(readWorkspacePolicyCache(cachePath, identity), null);+ });+});diff --git a/test/helpers/workspacePolicyManager.test.js b/test/helpers/workspacePolicyManager.test.jsnew file mode 100644index 000000000..d374abec4--- /dev/null+++ b/test/helpers/workspacePolicyManager.test.js@@ -0,0 +1,618 @@+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 { createWorkspacePolicyManager } = require("../../src/helpers/workspacePolicyManager");++const validPolicy = (updatedAt = "2026-08-05T00:00:00.000Z") => ({+ data: {+ managed: true,+ policy: {+ version: 1,+ transcription: { allowedModes: ["local"], allowedByokProviders: [] },+ llm: { allowedModes: ["local"], allowedByokProviders: [], allowedEnterpriseProviders: [] },+ features: { agentEnabled: false, webSearchEnabled: false },+ sharing: { externalLinkSharing: "disabled" },+ dataRetention: {+ audioRetentionMaxDays: 30,+ localHistoryMode: "always_off",+ cloudBackupAllowed: false,+ },+ minAppVersion: "1.8.1",+ },+ policyUpdatedAt: updatedAt,+ },+});++function response(status, body) {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" },+ });+}++function setup(proxyFetch, overrides = {}) {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-policy-manager-"));+ const cachePath = path.join(tempDir, "workspace-policy.json");+ const tokenState = { token: "token-a", generation: 1 };+ const broadcasts = [];+ const manager = createWorkspacePolicyManager({+ cachePath,+ getApiUrl: () => "https://api.openwhispr.test",+ getAppVersion: () => "1.8.1",+ proxyFetch,+ tokenStore: { getState: () => ({ ...tokenState }) },+ broadcast: (snapshot) => broadcasts.push(snapshot),+ logger: { error() {}, warn() {} },+ requestTimeoutMs: 20,+ successfulRefreshMs: 0,+ minimumAttemptIntervalMs: 0,+ ...overrides,+ });+ return {+ manager,+ cachePath,+ tokenState,+ broadcasts,+ cleanup: () => fs.rmSync(tempDir, { recursive: true, force: true }),+ };+}++test("caches authoritative unmanaged verdicts for offline startup", async (t) => {+ let online = true;+ const context = setup(async (_url, init) => {+ assert.equal(init.headers["x-openwhispr-policy-version"], "1");+ assert.equal(init.headers["x-openwhispr-version"], "1.8.1");+ if (!online) throw new Error("offline");+ return response(200, { data: { managed: false, policy: null, policyUpdatedAt: null } });+ });+ t.after(context.cleanup);++ const first = await context.manager.getPolicy({+ accountId: "account-a",+ expectedAuthGeneration: 1,+ });+ online = false;+ const second = await context.manager.getPolicy({+ accountId: "account-a",+ expectedAuthGeneration: 1,+ });++ assert.equal(first.managed, false);+ assert.equal(second.success, true);+ assert.equal(second.status, "cached");+ assert.equal(second.managed, false);+});++test("renderer account labels do not override credential-bound cache identity", async (t) => {+ let online = true;+ const context = setup(async () => {+ if (!online) throw new Error("offline");+ return response(200, { data: { managed: false, policy: null, policyUpdatedAt: null } });+ });+ t.after(context.cleanup);++ await context.manager.getPolicy({ accountId: "renderer-label-a", expectedAuthGeneration: 1 });+ online = false;+ const cached = await context.manager.getPolicy({+ accountId: "renderer-label-b",+ expectedAuthGeneration: 1,+ });++ assert.equal(cached.success, true);+ assert.equal(cached.status, "cached");+ assert.equal(cached.accountId, "renderer-label-b");+});++test("legacy cookie-authenticated callers cache unmanaged policy by the credential used", async (t) => {+ let online = true;+ const context = setup(async (_url, init) => {+ assert.equal(init.headers.Cookie, "session=legacy-account");+ assert.equal(init.headers.Authorization, undefined);+ if (!online) throw new Error("offline");+ return response(200, { data: { managed: false, policy: null, policyUpdatedAt: null } });+ });+ t.after(context.cleanup);+ context.tokenState.token = null;++ const request = {+ accountId: "legacy-account",+ expectedAuthGeneration: 1,+ authHeaders: { Cookie: "session=legacy-account" },+ };+ const first = await context.manager.getPolicy(request);+ online = false;+ const cached = await context.manager.getPolicy(request);++ assert.equal(first.managed, false);+ assert.equal(cached.success, true);+ assert.equal(cached.status, "cached");+});++test("accepts and caches the API's legacy-compatible unmanaged default-policy envelope", async (t) => {+ const defaultPolicy = {+ version: 1,+ transcription: {+ allowedModes: ["openwhispr", "providers", "local", "self-hosted"],+ allowedByokProviders: ["openai", "groq", "xai", "mistral", "corti", "tinfoil"],+ },+ llm: {+ allowedModes: ["openwhispr", "providers", "local", "self-hosted", "enterprise"],+ allowedByokProviders: ["openai", "anthropic", "gemini", "groq", "tinfoil", "corti"],+ allowedEnterpriseProviders: ["bedrock", "azure", "vertex"],+ },+ features: { agentEnabled: true, webSearchEnabled: true },+ sharing: { externalLinkSharing: "allowed" },+ dataRetention: {+ audioRetentionMaxDays: null,+ localHistoryMode: "user_choice",+ cloudBackupAllowed: true,+ },+ minAppVersion: null,+ };+ let online = true;+ const context = setup(async () => {+ if (!online) throw new Error("offline");+ return response(200, {+ data: { managed: false, policy: defaultPolicy, policyUpdatedAt: null },+ });+ });+ t.after(context.cleanup);++ const first = await context.manager.getPolicy({+ accountId: "account-a",+ expectedAuthGeneration: 1,+ });+ online = false;+ const cached = await context.manager.getPolicy({+ accountId: "account-a",+ expectedAuthGeneration: 1,+ });++ assert.equal(first.success, true);+ assert.equal(first.managed, false);+ assert.deepEqual(first.policy, defaultPolicy);+ assert.equal(cached.status, "cached");+ assert.equal(cached.managed, false);+ assert.deepEqual(cached.policy, defaultPolicy);+});++test("treats 404 and 501 policy endpoints as authoritative legacy unmanaged servers", async (t) => {+ for (const status of [404, 501]) {+ const context = setup(async () => response(status, { error: "unsupported" }));+ t.after(context.cleanup);+ const result = await context.manager.getPolicy({+ accountId: `account-${status}`,+ expectedAuthGeneration: 1,+ });+ assert.equal(result.success, true, String(status));+ assert.equal(result.managed, false, String(status));+ assert.equal(result.endpointSupported, false, String(status));+ }+});++test("a 404 cannot replace an in-memory managed last-good policy", async (t) => {+ const responses = [response(200, validPolicy()), response(404, { error: "not found" })];+ const context = setup(async () => responses.shift());+ t.after(context.cleanup);++ const managed = await context.manager.getPolicy({+ accountId: "account-a",+ expectedAuthGeneration: 1,+ });+ const fallback = await context.manager.getPolicy({+ accountId: "account-a",+ expectedAuthGeneration: 1,+ });++ assert.equal(fallback.status, "cached");+ assert.equal(fallback.managed, true);+ assert.deepEqual(fallback.policy, managed.policy);+ assert.equal(fallback.policyUpdatedAt, managed.policyUpdatedAt);+ assert.equal(context.broadcasts.length, 1);+});++test("a 501 after restart cannot replace a disk-cached managed last-good policy", async (t) => {+ const context = setup(async () => response(200, validPolicy()));+ t.after(context.cleanup);+ const request = { accountId: "account-a", expectedAuthGeneration: 1 };+ await context.manager.getPolicy(request);++ const restarted = createWorkspacePolicyManager({+ cachePath: context.cachePath,+ getApiUrl: () => "https://api.openwhispr.test",+ getAppVersion: () => "1.8.1",+ proxyFetch: async () => response(501, { error: "not implemented" }),+ tokenStore: { getState: () => ({ ...context.tokenState }) },+ logger: { error() {}, warn() {} },+ });+ const fallback = await restarted.getPolicy(request);++ const offlineRestart = createWorkspacePolicyManager({+ cachePath: context.cachePath,+ getApiUrl: () => "https://api.openwhispr.test",+ getAppVersion: () => "1.8.1",+ proxyFetch: async () => {+ throw new Error("offline");+ },+ tokenStore: { getState: () => ({ ...context.tokenState }) },+ logger: { error() {}, warn() {} },+ });+ const cached = await offlineRestart.getPolicy(request);++ assert.equal(fallback.status, "cached");+ assert.equal(fallback.managed, true);+ assert.equal(cached.managed, true);+ assert.deepEqual(cached.policy, fallback.policy);+ assert.equal(cached.policyUpdatedAt, fallback.policyUpdatedAt);+});++test("reuses a successful managed policy for five minutes, then accepts an update", async (t) => {+ let currentTime = 0;+ let requestCount = 0;+ const initial = validPolicy("2026-08-05T00:00:00.000Z");+ const updated = validPolicy("2026-08-05T00:05:00.000Z");+ updated.data.policy.features.agentEnabled = true;+ const responses = [response(200, initial), response(200, updated)];+ const context = setup(+ async () => {+ requestCount += 1;+ return responses.shift();+ },+ { now: () => currentTime, successfulRefreshMs: 300_000 }+ );+ t.after(context.cleanup);+ const request = { accountId: "account-a", expectedAuthGeneration: 1 };++ const first = await context.manager.getPolicy(request);+ currentTime = 299_999;+ const fresh = await context.manager.getPolicy(request);+ currentTime = 300_000;+ const refreshed = await context.manager.getPolicy(request);++ assert.equal(first.policy.features.agentEnabled, false);+ assert.equal(fresh.policy.features.agentEnabled, false);+ assert.equal(refreshed.policy.features.agentEnabled, true);+ assert.equal(requestCount, 2);+ assert.equal(context.broadcasts.length, 2);+});++test("refreshes a managed identity to authoritative unmanaged after five minutes", async (t) => {+ let currentTime = 0;+ let requestCount = 0;+ const responses = [+ response(200, validPolicy()),+ response(200, { data: { managed: false, policy: null, policyUpdatedAt: null } }),+ ];+ const context = setup(+ async () => {+ requestCount += 1;+ return responses.shift();+ },+ { now: () => currentTime, successfulRefreshMs: 300_000 }+ );+ t.after(context.cleanup);+ const request = { accountId: "account-a", expectedAuthGeneration: 1 };++ assert.equal((await context.manager.getPolicy(request)).managed, true);+ currentTime = 299_999;+ assert.equal((await context.manager.getPolicy(request)).managed, true);+ currentTime = 300_000;+ assert.equal((await context.manager.getPolicy(request)).managed, false);+ assert.equal(requestCount, 2);+ assert.equal(context.broadcasts.length, 2);+});++test("cached errors do not extend successful policy freshness", async (t) => {+ let currentTime = 0;+ let requestCount = 0;+ const updated = validPolicy("2026-08-05T00:05:00.000Z");+ updated.data.policy.features.agentEnabled = true;+ const context = setup(+ async () => {+ requestCount += 1;+ if (requestCount === 1) return response(200, validPolicy());+ if (requestCount === 2) throw new Error("offline");+ return response(200, updated);+ },+ { now: () => currentTime, successfulRefreshMs: 300_000 }+ );+ t.after(context.cleanup);+ const request = { accountId: "account-a", expectedAuthGeneration: 1 };++ await context.manager.getPolicy(request);+ currentTime = 300_000;+ assert.equal((await context.manager.getPolicy(request)).status, "cached");+ currentTime = 300_001;+ const recovered = await context.manager.getPolicy(request);++ assert.equal(recovered.policy.features.agentEnabled, true);+ assert.equal(requestCount, 3);+});++test("known-managed unsupported fallbacks do not extend successful freshness", async (t) => {+ let currentTime = 0;+ let requestCount = 0;+ const updated = validPolicy("2026-08-05T00:05:00.000Z");+ updated.data.policy.features.agentEnabled = true;+ const context = setup(+ async () => {+ requestCount += 1;+ if (requestCount === 1) return response(200, validPolicy());+ if (requestCount === 2) return response(404, { error: "not found" });+ return response(200, updated);+ },+ { now: () => currentTime, successfulRefreshMs: 300_000 }+ );+ t.after(context.cleanup);+ const request = { accountId: "account-a", expectedAuthGeneration: 1 };++ await context.manager.getPolicy(request);+ currentTime = 300_000;+ const fallback = await context.manager.getPolicy(request);+ currentTime = 300_001;+ const recovered = await context.manager.getPolicy(request);++ assert.equal(fallback.status, "cached");+ assert.equal(fallback.managed, true);+ assert.equal(recovered.policy.features.agentEnabled, true);+ assert.equal(requestCount, 3);+});++test("throttles sequential focus refreshes after a fallback but lets recovery retry", async (t) => {+ let currentTime = 0;+ let requestCount = 0;+ const updated = validPolicy("2026-08-05T00:05:00.000Z");+ updated.data.policy.features.agentEnabled = true;+ const context = setup(+ async () => {+ requestCount += 1;+ if (requestCount === 1) return response(200, validPolicy());+ if (requestCount <= 3) throw new Error("offline");+ return response(200, updated);+ },+ {+ now: () => currentTime,+ successfulRefreshMs: 300_000,+ minimumAttemptIntervalMs: 5_000,+ }+ );+ t.after(context.cleanup);+ const request = { accountId: "account-a", expectedAuthGeneration: 1 };++ await context.manager.getPolicy(request);+ currentTime = 300_000;+ assert.equal((await context.manager.getPolicy(request)).status, "cached");+ currentTime = 300_001;+ 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" });+ assert.equal(recovered.policy.features.agentEnabled, true);+ assert.equal(requestCount, 4);+});++test("a stale managed HTTP response cannot replace a newer disk policy after restart", async (t) => {+ const context = setup(async () => response(200, validPolicy("2026-08-05T00:10:00.000Z")));+ t.after(context.cleanup);+ const request = { accountId: "account-a", expectedAuthGeneration: 1 };+ const newer = await context.manager.getPolicy(request);++ const restartedBroadcasts = [];+ const restarted = createWorkspacePolicyManager({+ cachePath: context.cachePath,+ getApiUrl: () => "https://api.openwhispr.test",+ getAppVersion: () => "1.8.1",+ proxyFetch: async () => response(200, validPolicy("2026-08-05T00:05:00.000Z")),+ tokenStore: { getState: () => ({ ...context.tokenState }) },+ broadcast: (snapshot) => restartedBroadcasts.push(snapshot),+ logger: { error() {}, warn() {} },+ });+ const result = await restarted.getPolicy(request);++ assert.equal(result.managed, true);+ assert.equal(result.policyUpdatedAt, newer.policyUpdatedAt);+ assert.equal(result.status, "current");+ assert.equal(restartedBroadcasts.length, 0);+});++test("times out a policy request and returns a matching cache when available", async (t) => {+ let hang = false;+ const context = setup(async (_url, init) => {+ if (!hang)+ return response(200, { data: { managed: false, policy: null, policyUpdatedAt: null } });+ return new Promise((_resolve, reject) => {+ init.signal.addEventListener("abort", () => reject(init.signal.reason), { once: true });+ });+ });+ t.after(context.cleanup);+ await context.manager.getPolicy({ accountId: "account-a", expectedAuthGeneration: 1 });+ hang = true;++ const result = await context.manager.getPolicy({+ accountId: "account-a",+ expectedAuthGeneration: 1,+ });+ assert.equal(result.success, true);+ assert.equal(result.status, "cached");+});++test("a delayed account A response cannot mutate state after credentials switch to B", async (t) => {+ let resolveRequest;+ const context = setup(() => new Promise((resolve) => (resolveRequest = resolve)), {+ requestTimeoutMs: 1000,+ });+ t.after(context.cleanup);++ const pending = context.manager.getPolicy({ accountId: "account-a", expectedAuthGeneration: 1 });+ context.tokenState.token = "token-b";+ context.tokenState.generation = 2;+ resolveRequest(response(200, validPolicy()));+ const result = await pending;++ assert.equal(result.success, false);+ assert.equal(result.code, "AUTH_CONTEXT_CHANGED");+ assert.equal(context.broadcasts.length, 0);+});++test("deduplicates concurrent window requests and broadcasts one authoritative snapshot", async (t) => {+ let calls = 0;+ let resolveRequest;+ const context = setup(() => {+ calls += 1;+ return new Promise((resolve) => (resolveRequest = resolve));+ });+ t.after(context.cleanup);++ const first = context.manager.getPolicy({ accountId: "account-a", expectedAuthGeneration: 1 });+ const second = context.manager.getPolicy({ accountId: "account-a", expectedAuthGeneration: 1 });+ resolveRequest(response(200, validPolicy()));+ const [firstResult, secondResult] = await Promise.all([first, second]);++ assert.equal(calls, 1);+ assert.equal(firstResult.revision, secondResult.revision);+ assert.equal(context.broadcasts.length, 1);+});++test("rejects an older policy response instead of downgrading main or cache state", async (t) => {+ const responses = [+ response(200, validPolicy("2026-08-05T02:00:00.000Z")),+ response(200, validPolicy("2026-08-05T01:00:00.000Z")),+ ];+ const context = setup(async () => responses.shift());+ t.after(context.cleanup);++ const newest = await context.manager.getPolicy({+ accountId: "account-a",+ expectedAuthGeneration: 1,+ });+ const stale = await context.manager.getPolicy({+ accountId: "account-a",+ expectedAuthGeneration: 1,+ });++ assert.equal(stale.policyUpdatedAt, newest.policyUpdatedAt);+ assert.equal(stale.revision, newest.revision);+ assert.equal(context.broadcasts.length, 1);+});++test("invalid managed policy fails closed and is never broadcast", async (t) => {+ const malformed = validPolicy();+ malformed.data.policy.version = 2;+ const context = setup(async () => response(200, malformed));+ t.after(context.cleanup);++ const result = await context.manager.getPolicy({+ accountId: "account-a",+ expectedAuthGeneration: 1,+ });+ assert.equal(result.success, false);+ assert.equal(result.code, "POLICY_UNAVAILABLE");+ assert.equal(context.broadcasts.length, 0);+});++test("a first policy-enabled offline launch remains unavailable without a policy verdict", async (t) => {+ const context = setup(async () => {+ throw new Error("offline");+ });+ t.after(context.cleanup);++ const result = await context.manager.getPolicy({+ accountId: "account-a",+ expectedAuthGeneration: 1,+ });++ assert.equal(result.success, false);+ assert.equal(result.status, "error");+ assert.equal(result.code, "POLICY_UNAVAILABLE");+ assert.equal(context.broadcasts.length, 0);+});++test("HTTP policy denials and malformed success payloads remain unavailable", async (t) => {+ for (const proxyFetch of [+ async () => response(403, { error: "managed policy denied", code: "POLICY_DENIED" }),+ async () => response(200, { data: { managed: true, policy: null } }),+ ]) {+ const context = setup(proxyFetch);+ t.after(context.cleanup);+ const result = await context.manager.getPolicy({+ accountId: "account-a",+ expectedAuthGeneration: 1,+ });+ assert.equal(result.success, false);+ assert.equal(result.status, "error");+ }+});++test("a corrupt policy cache cannot authorize an offline identity", async (t) => {+ const context = setup(async () => {+ throw new Error("offline");+ });+ t.after(context.cleanup);+ fs.writeFileSync(context.cachePath, "{not valid json", "utf8");++ const result = await context.manager.getPolicy({+ accountId: "account-a",+ expectedAuthGeneration: 1,+ });++ assert.equal(result.success, false);+ assert.equal(result.code, "POLICY_UNAVAILABLE");+ assert.equal(context.broadcasts.length, 0);+});++test("an unmanaged verdict cannot be rebound to a new credential or API origin", async (t) => {+ let online = true;+ const context = setup(async () => {+ if (!online) throw new Error("offline");+ return response(200, { data: { managed: false, policy: null, policyUpdatedAt: null } });+ });+ t.after(context.cleanup);+ const originalRequest = { accountId: "account-a", expectedAuthGeneration: 1 };++ const original = await context.manager.getPolicy(originalRequest);+ assert.equal(original.managed, false);+ online = false;+ context.tokenState.token = "token-b";+ context.tokenState.generation = 2;+ const newCredential = await context.manager.getPolicy({+ accountId: "account-a",+ expectedAuthGeneration: 2,+ });++ assert.equal(newCredential.success, false);+ assert.equal(newCredential.code, "POLICY_UNAVAILABLE");++ context.tokenState.token = "token-a";+ context.tokenState.generation = 1;+ const differentOrigin = createWorkspacePolicyManager({+ cachePath: context.cachePath,+ getApiUrl: () => "https://self-host.openwhispr.test",+ getAppVersion: () => "1.8.1",+ proxyFetch: async () => {+ throw new Error("offline");+ },+ tokenStore: { getState: () => ({ ...context.tokenState }) },+ logger: { error() {}, warn() {} },+ requestTimeoutMs: 20,+ successfulRefreshMs: 0,+ minimumAttemptIntervalMs: 0,+ });+ const reboundOrigin = await differentOrigin.getPolicy(originalRequest);++ assert.equal(reboundOrigin.success, false);+ assert.equal(reboundOrigin.code, "POLICY_UNAVAILABLE");+});