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
feat(transcription): managed enterprise STT (Azure) via workload identity (#1964)
Gabriel Stein24e1162a41ea
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b3504dc63..088d2639a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+## [1.10.0] - Unreleased++### Added++- Managed enterprise transcription: workspaces on Azure OpenAI or AI Foundry can distribute a speech-to-text deployment to every member with no API keys on user machines. Dictation, retry from history, and file upload use it; meeting recording keeps its existing lanes.+- Enterprise cloud is now a selectable transcription mode when workspace policy allows it.++### Changed++- Managed enterprise providers no longer require SSO. Require SSO stays an independent workspace control.+- Managed Azure text processing accepts AI Foundry and AI Services endpoints.+## [1.9.2] - 2026-08-29A repair release for two 1.9.1 regressions. Windows desktop sign-in works again — every provider button had gone dead — and the three transcription paths that only failed in packaged builds are back on all platforms. Meetings get three fixes of their own: recordings that captured only your voice on Windows, prompts that stopped appearing after the first call, and swipe-to-dismiss on the prompt cards.@@ -21,7 +33,7 @@ A repair release for two 1.9.1 regressions. Windows desktop sign-in works again### Meetings-- **Windows meetings that recorded only your own voice.** On some machines the system-audio helper starts up reporting itself healthy and then captures nothing but digital silence, so meeting notes contained your microphone and none of the other participants — with no error anywhere in the app. The check that picked the capture method only asked Windows whether loopback capture was *available*, never whether any audio was actually arriving, so the working fallback was never reached. The helper now compares its own output against what your speakers or headphones are really playing, and a recording that hits this switches to the fallback a few seconds in and keeps the rest of the call. (#1935, thanks @KishenG)+- **Windows meetings that recorded only your own voice.** On some machines the system-audio helper starts up reporting itself healthy and then captures nothing but digital silence, so meeting notes contained your microphone and none of the other participants — with no error anywhere in the app. The check that picked the capture method only asked Windows whether loopback capture was _available_, never whether any audio was actually arriving, so the working fallback was never reached. The helper now compares its own output against what your speakers or headphones are really playing, and a recording that hits this switches to the fallback a few seconds in and keeps the rest of the call. (#1935, thanks @KishenG)- **Meeting prompts kept appearing after the first call.** Closing a meeting prompt any way other than its own buttons — a compositor killing the window on Hyprland, a failed load, onboarding taking over the screen — left the detection marked as still on screen, so no later meeting ever prompted again for the rest of the session. On Linux the prompt also fired on OpenWhispr's own microphone use, and it now waits until the audio server has said which application owns the capture. A second call raises a fresh prompt once the first one's microphone has actually gone quiet, while an ongoing call still prompts only once. Explicitly dismissing keeps its five-minute pause, and letting a card expire still costs nothing. (#1918, thanks @IdrisGit)- **Meeting prompts swipe away like desktop notifications.** A horizontal pointer swipe of 80px in either direction dismisses a meeting card — detection, calendar reminder, or the auto-end restart offer — taking the same path as its close button. Swipes that start on an action button are ignored. (#1906)diff --git a/package-lock.json b/package-lock.jsonindex 93ecf05bc..e147ade82 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "open-whispr",- "version": "1.9.2",+ "version": "1.10.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "open-whispr",- "version": "1.9.2",+ "version": "1.10.0","hasInstallScript": true,"license": "MIT","dependencies": {diff --git a/package.json b/package.jsonindex ddb1b66ba..9d1b9631f 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-whispr",- "version": "1.9.2",+ "version": "1.10.0","description": "A desktop dictation application using whisper.cpp for speech-to-text transcription","main": "main.js","private": true,diff --git a/preload.js b/preload.jsindex 434e87102..823532268 100644--- a/preload.js+++ b/preload.js@@ -228,6 +228,11 @@ contextBridge.exposeInMainWorld("electronAPI", {getSpaces: () => ipcRenderer.invoke("db-get-spaces"),setActiveAccountScope: (accountId, expectedAuthGeneration) =>ipcRenderer.invoke("set-active-account-scope", accountId, expectedAuthGeneration),+ getActiveAccountScope: () => ipcRenderer.invoke("get-active-account-scope"),+ onActiveAccountScopeChanged: registerListener(+ "active-account-scope-changed",+ (callback) => (_event, scope) => callback(scope)+ ),deleteAccountData: (accountId, expectedAuthGeneration) =>ipcRenderer.invoke("delete-account-data", accountId, expectedAuthGeneration),updateSpace: (id, updates) => ipcRenderer.invoke("db-update-space", id, updates),@@ -664,6 +669,7 @@ contextBridge.exposeInMainWorld("electronAPI", {(callback) => (_event, snapshot) => callback(snapshot)),clearManagedEnterpriseIdentity: () => ipcRenderer.invoke("clear-managed-enterprise-identity"),+ managedTranscribe: (data) => ipcRenderer.invoke("managed-transcribe", data),// llama.cppllamaCppCheck: () => ipcRenderer.invoke("llama-cpp-check"),diff --git a/src/AppRouter.jsx b/src/AppRouter.jsxindex 0ca3815d6..38aef7323 100644--- a/src/AppRouter.jsx+++ b/src/AppRouter.jsx@@ -10,6 +10,7 @@ import { LEGACY_ONBOARDING_STEP_KEY, ONBOARDING_SESSION_KEY } from "./componentsimport { useAuth } from "./hooks/useAuth";import { useControlPanelWindowDrag } from "./hooks/useControlPanelWindowDrag";import { useTheme } from "./hooks/useTheme";+import { mirrorActiveAccountScope } from "./lib/accountScopeMirror";import { usePolicyStore } from "./stores/policyStore";import { resolveSettledControlPanelWindowMode } from "./utils/controlPanelWindowMode.ts";import { isControlPanelWindow } from "./utils/windowContext.ts";@@ -83,6 +84,13 @@ function MainApp() {}}, [autoSyncReady, isControlPanel]);+ useEffect(() => {+ // The dictation window cannot resolve a session (see mirrorActiveAccountScope),+ // so its policy and managed identity follow the main process's account scope.+ if (!isDictationPanel) return;+ return mirrorActiveAccountScope();+ }, [isDictationPanel]);+useEffect(() => {if (!authLoaded) return;diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsxindex 3b05da521..0b15325e3 100644--- a/src/components/ControlPanel.tsx+++ b/src/components/ControlPanel.tsx@@ -48,6 +48,7 @@ import {isTranscriptionContextAllowed,isUpdateRequiredByOrg,} from "../stores/policyRules";+import { getManagedTranscriptionResolution } from "../services/managedTranscription";import {useIsMeetingMode,useIsNarrowWindow,@@ -600,11 +601,20 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelProasync (id: number, options?: { isRecover?: boolean }) => {try {const s = getSettings();- if (!isTranscriptionContextAllowed(usePolicyStore.getState(), s, "dictation")) {+ const managed = getManagedTranscriptionResolution();+ if (managed?.kind === "error") {+ toast({+ title: managed.messageKey ? t(managed.messageKey) : managed.message,+ variant: "destructive",+ });+ return;+ }+ if (!managed && !isTranscriptionContextAllowed(usePolicyStore.getState(), s, "dictation")) {toast({ title: t("common.managedByOrg"), variant: "default" });return;}const result = await window.electronAPI.retryTranscription(id, {+ managed,useLocalWhisper: s.useLocalWhisper,localTranscriptionProvider: s.localTranscriptionProvider,cloudTranscriptionMode: s.cloudTranscriptionMode,@@ -778,7 +788,7 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro} else {toast({title: t("controlPanel.history.retryError"),- description: result.error,+ description: result.messageKey ? t(result.messageKey) : result.error,variant: "destructive",});}diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 74a86f59c..c1f523caa 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -18,6 +18,7 @@ import {Key,Cpu,Network,+ ShieldCheck,Sparkles,AlertTriangle,Loader2,@@ -123,6 +124,7 @@ import { syncService } from "../services/SyncService.js";import { formatBytes } from "../utils/formatBytes";import {clearMissingLocalModelSelections,+ TRANSCRIPTION_ENTERPRISE_POLICY_PROVIDER_IDS,TRANSCRIPTION_POLICY_PROVIDER_IDS,useSettingsStore,} from "../stores/settingsStore";@@ -135,6 +137,7 @@ import {effectiveLocalHistoryEnabled,isAgentAllowed,isCloudBackupAllowed,+ isEnterpriseTranscriptionOfferable,lockedLocalHistoryValue,maxAudioRetentionDays,} from "../stores/policyRules";@@ -148,7 +151,8 @@ import EnterpriseCheckoutDialog from "./settings/EnterpriseCheckoutDialog";import CreateWorkspaceDialog from "./CreateWorkspaceDialog";import ProfileSection from "./settings/ProfileSection";import { formatAmount } from "../utils/formatAmount";-import { getTranscriptionProvider } from "../models/ModelRegistry";+import { enterpriseProviderName, getTranscriptionProvider } from "../models/ModelRegistry";+import { useManagedScopeResolution } from "../stores/enterpriseIdentityStore";import { supportsLiveTranscriptionPreview } from "../utils/transcriptionPreview";export type SettingsSectionType =@@ -547,6 +551,15 @@ function TranscriptionSection({toast,}: TranscriptionSectionProps) {const { t } = useTranslation();+ const policySnapshot = usePolicySnapshot();+ const enterpriseTranscriptionSetupMode = useSettingsStore(+ (s) => s.enterpriseTranscriptionSetupMode+ );+ const setEnterpriseTranscriptionSetupMode = useSettingsStore(+ (s) => s.setEnterpriseTranscriptionSetupMode+ );+ const managed = useManagedScopeResolution("transcription", enterpriseTranscriptionSetupMode);+ const managedAvailable = useManagedScopeResolution("transcription", "managed");const {modes: transcriptionModes,effectiveMode: effectiveTranscriptionMode,@@ -579,10 +592,23 @@ function TranscriptionSection({description: t("settingsPage.transcription.modes.selfHostedDesc"),icon: <Network className="w-4 h-4" />,},+ ...(isEnterpriseTranscriptionOfferable(policySnapshot)+ ? [+ {+ id: "enterprise" as const,+ label: t("settingsPage.transcription.modes.enterprise"),+ description: t("settingsPage.transcription.modes.enterpriseDesc"),+ icon: <ShieldCheck className="w-4 h-4" />,+ },+ ]+ : []),],"transcription",transcriptionMode,- { byokProviders: TRANSCRIPTION_POLICY_PROVIDER_IDS }+ {+ byokProviders: TRANSCRIPTION_POLICY_PROVIDER_IDS,+ enterpriseProviders: TRANSCRIPTION_ENTERPRISE_POLICY_PROVIDER_IDS,+ });const handleTranscriptionModeSelect = (mode: InferenceMode) => {if (!isModeAllowed(mode)) return;@@ -595,12 +621,14 @@ function TranscriptionSection({setUseLocalWhisper(mode === "local");updateTranscriptionSettings({ useLocalWhisper: mode === "local" });setCloudTranscriptionMode(mode === "openwhispr" ? "openwhispr" : "byok");+ if (mode === "enterprise") setEnterpriseTranscriptionSetupMode("managed");const toastKey = {openwhispr: "switchedCloud",providers: "switchedProviders",local: "switchedLocal","self-hosted": "switchedSelfHosted",+ enterprise: "switchedEnterprise",}[mode];toast({title: t(`settingsPage.transcription.toasts.${toastKey}.title`),@@ -680,28 +708,113 @@ function TranscriptionSection({/>);+ // Local decoding still serves meetings and uploads under a managed-config+ // error, so this stays a card alongside the rest of the section (including+ // the GPU selector below) instead of an early return that hides it.+ const errorCard =+ managed.kind === "error" ? (+ <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-3" role="alert">+ <div className="flex items-start gap-2">+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-destructive" />+ <div>+ <p className="text-sm font-medium">+ {t("settingsPage.aiModels.managedEnterprise.errorTitle")}+ </p>+ <p className="mt-0.5 text-xs text-muted-foreground">+ {managed.messageKey ? t(managed.messageKey) : managed.message}+ </p>+ </div>+ </div>+ </div>+ ) : null;++ const managedCard =+ managed.kind === "managed" ? (+ <div className="space-y-3 rounded-lg border border-primary/20 bg-primary/[0.03] p-3">+ <div className="flex items-start gap-2.5">+ <div className="rounded-md bg-primary/10 p-1.5 text-primary">+ <ShieldCheck className="h-4 w-4" />+ </div>+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium">+ {t("settingsPage.aiModels.managedEnterprise.title")}+ </p>+ <p className="mt-0.5 text-xs text-muted-foreground">+ {enterpriseProviderName(managed.provider)} ·{" "}+ <span className="font-mono">{managed.model}</span>+ </p>+ <p className="mt-1 text-xs text-muted-foreground">+ {t("settingsPage.aiModels.managedEnterprise.description")}+ </p>+ </div>+ </div>+ {managed.mode !== "managed_required" && managed.allowManualSetup && (+ <div className="flex flex-wrap items-center gap-2 border-t border-border/60 pt-3">+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={() => setEnterpriseTranscriptionSetupMode("manual")}+ >+ {t("settingsPage.aiModels.managedEnterprise.usePersonalSetup")}+ </Button>+ </div>+ )}+ </div>+ ) : null;+return (<div className="space-y-4">- <InferenceModeSelector- modes={transcriptionModes}- activeMode={effectiveTranscriptionMode}- onSelect={handleTranscriptionModeSelect}- />+ {errorCard}+ {managedCard}+ {!errorCard && !managedCard && (+ <>+ {enterpriseTranscriptionSetupMode === "manual" && managedAvailable.kind === "managed" && (+ <div className="flex items-center justify-between gap-3 rounded-lg border bg-muted/30 p-3">+ <div className="min-w-0">+ <p className="text-sm font-medium">+ {t("settingsPage.aiModels.managedEnterprise.availableTitle")}+ </p>+ <p className="text-xs text-muted-foreground">+ {t("settingsPage.aiModels.managedEnterprise.availableDescription", {+ provider: enterpriseProviderName(managedAvailable.provider),+ })}+ </p>+ </div>+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="shrink-0"+ onClick={() => setEnterpriseTranscriptionSetupMode("managed")}+ >+ {t("settingsPage.aiModels.managedEnterprise.useManaged")}+ </Button>+ </div>+ )}+ <InferenceModeSelector+ modes={transcriptionModes}+ activeMode={effectiveTranscriptionMode}+ onSelect={handleTranscriptionModeSelect}+ />- {effectiveTranscriptionMode === "providers" && renderTranscriptionPicker("cloud")}- {effectiveTranscriptionMode === "local" && renderTranscriptionPicker("local")}- {previewAvailable && renderPreviewToggle()}-- {effectiveTranscriptionMode === "self-hosted" && (- <SelfHostedPanel- service="transcription"- url={remoteTranscriptionUrl}- onUrlChange={setRemoteTranscriptionUrl}- model={remoteTranscriptionModel}- onModelChange={setRemoteTranscriptionModel}- />+ {effectiveTranscriptionMode === "providers" && renderTranscriptionPicker("cloud")}+ {effectiveTranscriptionMode === "local" && renderTranscriptionPicker("local")}+ {previewAvailable && renderPreviewToggle()}++ {effectiveTranscriptionMode === "self-hosted" && (+ <SelfHostedPanel+ service="transcription"+ url={remoteTranscriptionUrl}+ onUrlChange={setRemoteTranscriptionUrl}+ model={remoteTranscriptionModel}+ onModelChange={setRemoteTranscriptionModel}+ />+ )}+ </>)}+ {/* Local decoding still serves meetings and uploads, so the GPU choice stays reachable. */}<GpuDeviceSelector purpose="transcription" /></div>);diff --git a/src/components/notes/UploadAudioView.tsx b/src/components/notes/UploadAudioView.tsxindex 65bd9f809..9dbf68afe 100644--- a/src/components/notes/UploadAudioView.tsx+++ b/src/components/notes/UploadAudioView.tsx@@ -71,6 +71,8 @@ import { usePolicyStore } from "../../stores/policyStore";import { usePolicySnapshot, useTranscriptionContextAllowed } from "../../hooks/usePolicy";import { byokFileSizeLimit, resolveTranscriptionRoute } from "../../helpers/transcriptionRoute";import { saveUploadNote, uploadTitleFallback } from "../../services/uploadNotes";+import { useManagedScopeResolution } from "../../stores/enterpriseIdentityStore";+import { isManagedTranscriptionActive } from "../../services/managedTranscription";import { UploadCompleteWarnings, UploadModelSettingsButton } from "./UploadAudioFeedback";type UploadState = "idle" | "selected" | "downloading" | "transcribing" | "complete" | "error";@@ -317,6 +319,11 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploareturn selectIsCloudCleanupMode(effectiveSettings) ? "" : effectiveSettings.cleanupModel;});const useCleanupModel = useSettingsStore((s) => s.useCleanupModel);+ const enterpriseTranscriptionSetupMode = useSettingsStore(+ (s) => s.enterpriseTranscriptionSetupMode+ );+ const managedActive =+ useManagedScopeResolution("transcription", enterpriseTranscriptionSetupMode).kind === "managed";const isOpenWhisprCloud =isSignedIn && cloudTranscriptionMode === "openwhispr" && !useLocalWhisper;@@ -405,6 +412,10 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: UploauseEffect(() => {let cancelled = false;const checkProviderReady = async () => {+ if (managedActive) {+ setProviderReady(true);+ return;+ }if (isOpenWhisprCloud) {setProviderReady(true);return;@@ -455,6 +466,7 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploacancelled = true;};}, [+ managedActive,isOpenWhisprCloud,isSelfHosted,remoteTranscriptionUrl,@@ -628,7 +640,10 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa};const handleTranscribe = async () => {if (!file || batch.isProcessing) return;- if (!isTranscriptionContextAllowed(usePolicyStore.getState(), getSettings(), "upload")) {+ if (+ !isManagedTranscriptionActive() &&+ !isTranscriptionContextAllowed(usePolicyStore.getState(), getSettings(), "upload")+ ) {setError(t("common.managedByOrg"));return;}@@ -727,7 +742,9 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: UploasetError(errorKey? t(`notes.upload.${errorKey}`)- : res.error || t("notes.upload.transcriptionFailed")+ : res.messageKey+ ? t(res.messageKey)+ : res.error || t("notes.upload.transcriptionFailed"));setState("error");}@@ -864,7 +881,10 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploaconst startBatchProcessing = async () => {if (state === "downloading" || state === "transcribing") return;- if (!isTranscriptionContextAllowed(usePolicyStore.getState(), getSettings(), "upload")) {+ if (+ !isManagedTranscriptionActive() &&+ !isTranscriptionContextAllowed(usePolicyStore.getState(), getSettings(), "upload")+ ) {setBatchUrlNotice(t("common.managedByOrg"));return;}diff --git a/src/components/settings/InferenceConfigEditor.tsx b/src/components/settings/InferenceConfigEditor.tsxindex 8ef992fdf..e93c20082 100644--- a/src/components/settings/InferenceConfigEditor.tsx+++ b/src/components/settings/InferenceConfigEditor.tsx@@ -189,7 +189,9 @@ export default function InferenceConfigEditor({<p className="text-sm font-medium">{t("settingsPage.aiModels.managedEnterprise.errorTitle")}</p>- <p className="mt-0.5 text-xs text-muted-foreground">{managed.message}</p>+ <p className="mt-0.5 text-xs text-muted-foreground">+ {managed.messageKey ? t(managed.messageKey) : managed.message}+ </p></div></div></div>diff --git a/src/components/settings/MeetingSettings.tsx b/src/components/settings/MeetingSettings.tsxindex 5a7e74df5..c6ae5d6ed 100644--- a/src/components/settings/MeetingSettings.tsx+++ b/src/components/settings/MeetingSettings.tsx@@ -2,7 +2,8 @@ import { useCallback } from "react";import { useTranslation } from "react-i18next";import { Cloud, Key, Cpu, Network } from "lucide-react";import { useSettingsStore } from "../../stores/settingsStore";-import { usePolicyModeOptions } from "../../hooks/usePolicy";+import { usePolicyModeOptions, usePolicySnapshot } from "../../hooks/usePolicy";+import { isModeAllowedByPolicy } from "../../stores/policyRules";import { InferenceModeSelector, SettingsRow } from "../ui/SettingsSection";import type { InferenceModeOption } from "../ui/SettingsSection";import { Toggle } from "../ui/toggle";@@ -35,6 +36,7 @@ const noop = () => {};export function MeetingTranscriptionPanel() {const { t } = useTranslation();const startOnboarding = useStartOnboarding();+ const policySnapshot = usePolicySnapshot();const {isSignedIn,@@ -155,8 +157,20 @@ export function MeetingTranscriptionPanel() {/>);+ // Only true when the org's policy actually allows the enterprise+ // transcription mode — an empty list can also mean e.g. a self-hosted-only+ // policy, where this specific explanation would be false.+ const emptyListIsEnterpriseOnly =+ transcriptionModes.length === 0 &&+ isModeAllowedByPolicy(policySnapshot, "transcription", "enterprise");+return (<div className="space-y-3">+ {emptyListIsEnterpriseOnly && (+ <p className="text-sm text-muted-foreground">+ {t("settingsPage.transcription.meetingEnterpriseOnly")}+ </p>+ )}<InferenceModeSelectormodes={transcriptionModes}activeMode={effectiveTranscriptionMode}diff --git a/src/components/settings/UploadSettings.tsx b/src/components/settings/UploadSettings.tsxindex 6c5b657f3..1a11956ea 100644--- a/src/components/settings/UploadSettings.tsx+++ b/src/components/settings/UploadSettings.tsx@@ -1,8 +1,13 @@import { useCallback } from "react";import { useTranslation } from "react-i18next";-import { Cloud, Key, Cpu, Network } from "lucide-react";-import { TRANSCRIPTION_POLICY_PROVIDER_IDS, useSettingsStore } from "../../stores/settingsStore";-import { usePolicyModeOptions } from "../../hooks/usePolicy";+import { Cloud, Key, Cpu, Network, ShieldCheck } from "lucide-react";+import {+ TRANSCRIPTION_ENTERPRISE_POLICY_PROVIDER_IDS,+ TRANSCRIPTION_POLICY_PROVIDER_IDS,+ useSettingsStore,+} from "../../stores/settingsStore";+import { usePolicyModeOptions, usePolicySnapshot } from "../../hooks/usePolicy";+import { isEnterpriseTranscriptionOfferable } from "../../stores/policyRules";import { InferenceModeSelector } from "../ui/SettingsSection";import type { InferenceModeOption } from "../ui/SettingsSection";import TranscriptionModelPicker from "../TranscriptionModelPicker";@@ -13,6 +18,7 @@ import { useStartOnboarding } from "../../hooks/useStartOnboarding";export function UploadTranscriptionPanel() {const { t } = useTranslation();const startOnboarding = useStartOnboarding();+ const policySnapshot = usePolicySnapshot();const {isSignedIn,@@ -34,6 +40,7 @@ export function UploadTranscriptionPanel() {uploadCloudTranscriptionBaseUrl,setUploadCloudTranscriptionBaseUrl,setUploadCloudTranscriptionMode,+ setEnterpriseTranscriptionSetupMode,remoteTranscriptionUrl,setRemoteTranscriptionUrl,remoteTranscriptionModel,@@ -71,10 +78,23 @@ export function UploadTranscriptionPanel() {description: t("settingsPage.transcription.modes.selfHostedDesc"),icon: <Network className="w-4 h-4" />,},+ ...(isEnterpriseTranscriptionOfferable(policySnapshot)+ ? [+ {+ id: "enterprise" as const,+ label: t("settingsPage.transcription.modes.enterprise"),+ description: t("settingsPage.transcription.modes.enterpriseDesc"),+ icon: <ShieldCheck className="w-4 h-4" />,+ },+ ]+ : []),],"transcription",uploadTranscriptionMode,- { byokProviders: TRANSCRIPTION_POLICY_PROVIDER_IDS }+ {+ byokProviders: TRANSCRIPTION_POLICY_PROVIDER_IDS,+ enterpriseProviders: TRANSCRIPTION_ENTERPRISE_POLICY_PROVIDER_IDS,+ });const handleTranscriptionModeSelect = (mode: InferenceMode) => {if (!isModeAllowed(mode)) return;@@ -86,6 +106,7 @@ export function UploadTranscriptionPanel() {setUploadTranscriptionMode(mode);setUploadUseLocalWhisper(mode === "local");setUploadCloudTranscriptionMode(mode === "openwhispr" ? "openwhispr" : "byok");+ if (mode === "enterprise") setEnterpriseTranscriptionSetupMode("managed");};const handleLocalTranscriptionModelSelect = useCallback(diff --git a/src/helpers/accountScopeBinding.js b/src/helpers/accountScopeBinding.jsindex 24c083f0b..c47781f07 100644--- a/src/helpers/accountScopeBinding.js+++ b/src/helpers/accountScopeBinding.js@@ -45,6 +45,15 @@ function resolveBootAccountScope({ token, binding }) {return binding.accountId;}+// The scope a window without a resolvable session hydrates from (the dictation+// window has no cross-origin fetch, so its session never resolves): the same+// validated binding boot restores, paired with the credential generation the+// policy and managed-config handlers gate on.+function resolveActiveAccountScope({ token, generation, binding }) {+ const accountId = resolveBootAccountScope({ token, binding });+ return accountId ? { accountId, authGeneration: generation } : null;+}+function read() {try {const parsed = JSON.parse(fs.readFileSync(bindingFile(), "utf8"));@@ -77,4 +86,12 @@ function clear() {}}-module.exports = { clear, evaluateScopeRequest, hashToken, persist, read, resolveBootAccountScope };+module.exports = {+ clear,+ evaluateScopeRequest,+ hashToken,+ persist,+ read,+ resolveActiveAccountScope,+ resolveBootAccountScope,+};diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex 1b00dfa1c..9685d9aff 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -64,6 +64,10 @@ import {} from "../models/ModelRegistry";import { TINFOIL_PROXY_REQUIRED_ERROR } from "../services/transcriptionBaseUrl";import { resolveByokModel, resolveTranscriptionRoute } from "./transcriptionRoute.ts";+import {+ getManagedTranscriptionResolution,+ isManagedTranscriptionActive,+} from "../services/managedTranscription.ts";import { shouldSkipTranscriptionApiKey } from "./transcriptionAuth";import {isSelfHostedTranscription,@@ -392,6 +396,29 @@ const STREAMING_PROVIDERS = {// Batch providers that must transcribe via a main-process proxy (CORS,// non-Bearer auth, OAuth, or attested transport) instead of a renderer fetch.+function audioExtensionForMime(mimeType) {+ if (mimeType.includes("ogg")) return "ogg";+ if (mimeType.includes("mp4")) return "mp4";+ if (mimeType.includes("mpeg")) return "mp3";+ if (mimeType.includes("wav")) return "wav";+ return "webm";+}++// Workspace-managed Azure STT: the Entra token lives in the main process, so+// dictation dispatches over IPC exactly like the proxied providers below.+const MANAGED_TRANSCRIPTION_SPEC = {+ displayName: "Managed Azure",+ ipc: () => window.electronAPI?.managedTranscribe,+ buildPayload: ({ audioBuffer, language, dictionaryPrompt, managedResolution, mimeType }) => ({+ audioBuffer,+ fileName: `audio.${audioExtensionForMime(mimeType)}`,+ mimeType,+ language,+ prompt: dictionaryPrompt || undefined,+ managed: { provider: managedResolution.provider, context: managedResolution.context },+ }),+};+const PROXY_TRANSCRIPTION_PROVIDERS = {tinfoil: {displayName: "Tinfoil",@@ -890,7 +917,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);isRecordingAllowedByPolicy() {const policyState = usePolicyStore.getState();return (- isTranscriptionContextAllowed(policyState, getSettings(), "dictation") &&+ (isManagedTranscriptionActive() ||+ isTranscriptionContextAllowed(policyState, getSettings(), "dictation")) &&(!this.voiceAgentRequested || isAgentAllowed(policyState)));}@@ -1863,7 +1891,16 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);let result;let activeModel;- if (useLocalWhisper) {+ // Managed enterprise STT outranks the local and OpenWhispr Cloud lanes,+ // matching the LLM scopes; users opt out via "Use personal setup" when+ // the administrator allows it. Error resolutions fail closed inside+ // processWithOpenAIAPI with their own code.+ const managedTranscription = getManagedTranscriptionResolution();+ if (managedTranscription) {+ activeModel =+ managedTranscription.kind === "managed" ? managedTranscription.deployment : null;+ result = await this.processWithOpenAIAPI(audioBlob, metadata, wasCancelled);+ } else if (useLocalWhisper) {if (isSherpaLocalProvider(localProvider)) {activeModel = localProvider === "cohere" ? settings.cohereModel : parakeetModel;result = await this.processWithLocalParakeet(@@ -3377,13 +3414,25 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);"transcription");- const apiKey = await this.getAPIKey();+ // Managed enterprise STT outranks every personal setting.+ const managedResolution = getManagedTranscriptionResolution();+ if (managedResolution?.kind === "error") {+ throw Object.assign(new Error(managedResolution.message), {+ code: managedResolution.code,+ messageKey: managedResolution.messageKey,+ });+ }++ const apiKey = managedResolution ? null : await this.getAPIKey();const optimizedAudio = audioBlob;// Dispatch before endpoint resolution (which defaults to OpenAI and would leak// the key). Self-hosted wins, so a leftover proxied provider isn't diverted here.- const proxySpec = PROXY_TRANSCRIPTION_PROVIDERS[provider];- if (proxySpec && !isSelfHostedTranscription(apiSettings)) {+ const proxySpec = managedResolution+ ? MANAGED_TRANSCRIPTION_SPEC+ : PROXY_TRANSCRIPTION_PROVIDERS[provider];+ if (proxySpec && (managedResolution || !isSelfHostedTranscription(apiSettings))) {+ const providerName = managedResolution ? "azure-managed" : provider;const call = proxySpec.ipc();if (!call) {throw new Error(`${proxySpec.displayName} transcription is unavailable in this window`);@@ -3394,6 +3443,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);model,language,apiSettings,+ managedResolution,+ mimeType: optimizedAudio.type || "audio/webm",dictionaryPrompt: this.getWhisperPrompt(apiSettings),keyterms: this.getKeyterms().map((t) => t.trim().slice(0, 50))@@ -3416,27 +3467,19 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}timings.transcriptionProcessingDurationMs = Math.round(performance.now() - apiCallStart);const reasoningStart = performance.now();- const text = await this.processTranscription(proxyText, provider, wasCancelled);+ const text = await this.processTranscription(proxyText, providerName, wasCancelled);timings.reasoningProcessingDurationMs = Math.round(performance.now() - reasoningStart);- const source = (await this.isReasoningAvailable()) ? `${provider}-reasoned` : provider;+ const source = (await this.isReasoningAvailable())+ ? `${providerName}-reasoned`+ : providerName;return { success: true, text, rawText: proxyText, source, timings };}const formData = new FormData();// Determine the correct file extension based on the blob typeconst mimeType = optimizedAudio.type || "audio/webm";- const extension = mimeType.includes("webm")- ? "webm"- : mimeType.includes("ogg")- ? "ogg"- : mimeType.includes("mp4")- ? "mp4"- : mimeType.includes("mpeg")- ? "mp3"- : mimeType.includes("wav")- ? "wav"- : "webm";+ const extension = audioExtensionForMime(mimeType);logger.debug("FormData preparation",@@ -3971,6 +4014,10 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);const s = getSettings();if (s.useLocalWhisper) return false;+ // Managed enterprise STT is batch-only and outranks personal streaming+ // setups; an error resolution must fail closed on the batch path too.+ if (getManagedTranscriptionResolution()) return false;+// Self-hosted transcription is batch HTTP to the user's server, never cloud realtime WS.if (isSelfHostedTranscription(s)) return false;diff --git a/src/helpers/enterpriseAiProviders.js b/src/helpers/enterpriseAiProviders.jsindex 6a0ab7c12..8e131ae85 100644--- a/src/helpers/enterpriseAiProviders.js+++ b/src/helpers/enterpriseAiProviders.js@@ -8,6 +8,8 @@// app startup doesn't eager-load ~100 MB of AWS/Azure/Google SDKs for users// who never select an enterprise provider.+const { isAllowedAzureEndpoint } = require("./enterpriseManagedConfig.mjs");+async function getEnterpriseAIModel(provider, model, apiKey, enterprise) {switch (provider) {case "bedrock":@@ -82,23 +84,22 @@ function createAzureModel(model, apiKey, enterprise) {})(model);}+// One allowlist for managed Azure hosts (resource, AI Services, and Foundry),+// shared with the envelope validator so the two can never disagree.+//+// @ai-sdk/azure appends `/v1` and `?api-version=` itself ONLY when the base+// URL's hostname ends in `.openai.azure.com`; for every other host it uses the+// base URL verbatim and sends no api-version, so the version segment has to be+// part of it here or AI Services / Foundry requests land on `/openai/<path>`+// and 404.function toAzureOpenAIBaseUrl(endpoint) {- const url = new URL(endpoint);- const hostname = url.hostname.toLowerCase();- if (- url.protocol !== "https:" ||- url.username ||- url.password ||- (url.port && url.port !== "443") ||- !hostname.endsWith(".openai.azure.com") ||- hostname.length <= ".openai.azure.com".length ||- (url.pathname !== "" && url.pathname !== "/") ||- url.search ||- url.hash- ) {+ if (!isAllowedAzureEndpoint(endpoint)) {throw new Error("Managed Azure OpenAI requires a public Azure resource origin");}- return `${url.origin}/openai`;+ const url = new URL(endpoint);+ return url.hostname.endsWith(".openai.azure.com")+ ? `${url.origin}/openai`+ : `${url.origin}/openai/v1`;}function createVertexModel(model, apiKey, enterprise) {diff --git a/src/helpers/enterpriseIdentityManager.js b/src/helpers/enterpriseIdentityManager.jsindex 6b32eb6d4..33a7e685c 100644--- a/src/helpers/enterpriseIdentityManager.js+++ b/src/helpers/enterpriseIdentityManager.js@@ -3,6 +3,7 @@ const fs = require("fs");const {resolveManagedEnterpriseScope,validateManagedEnterpriseEnvelope,+ managedScopesForConfig,} = require("./enterpriseManagedConfig.mjs");const { AuthContextError } = require("./cloudApiRequest");@@ -102,7 +103,7 @@ function requiresEnforcedManagedAccess(config) {);}-function responseError(code, error, identity = null, enforcementRequired) {+function responseError(code, error, identity = null, enforcementRequired, enforcedScopes) {return {success: false,status: "error",@@ -112,6 +113,7 @@ function responseError(code, error, identity = null, enforcementRequired) {code,error,...(typeof enforcementRequired === "boolean" ? { enforcementRequired } : {}),+ ...(Array.isArray(enforcedScopes) ? { enforcedScopes } : {}),};}@@ -145,7 +147,7 @@ function createEnterpriseIdentityManager({}}- function evictIdentity(identity, code, enforcementRequired = false) {+ function evictIdentity(identity, code, enforcementRequired = false, enforcedScopes = []) {configs.delete(identity.cacheKey);configRequests.delete(identity.cacheKey);clearIdentityCredentials(identity);@@ -157,6 +159,7 @@ function createEnterpriseIdentityManager({config: null,code,enforcementRequired,+ enforcedScopes,});}@@ -306,7 +309,14 @@ function createEnterpriseIdentityManager({const prior = configs.get(identity.cacheKey)?.config || cachedConfig(cachePath, identity);error.enforcementRequired =error?.code === "ENTERPRISE_REQUIRED" ? false : requiresEnforcedManagedAccess(prior);- evictIdentity(identity, error.code || "MANAGED_CONFIG_FAILED", error.enforcementRequired);+ error.enforcedScopes =+ error?.code === "ENTERPRISE_REQUIRED" ? [] : managedScopesForConfig(prior).enforced;+ evictIdentity(+ identity,+ error.code || "MANAGED_CONFIG_FAILED",+ error.enforcementRequired,+ error.enforcedScopes+ );throw error;}if (!isTransientConfigError(error)) throw error;@@ -345,19 +355,20 @@ function createEnterpriseIdentityManager({error.code || "MANAGED_CONFIG_FAILED",error.message,identity,- error.enforcementRequired+ error.enforcementRequired,+ error.enforcedScopes);}}- async function fetchAssertion(identity, provider) {+ async function fetchAssertion(identity, provider, inferenceScope) {const url = `${identity.apiUrl}/api/workspaces/${encodeURIComponent(identity.workspaceId)}/enterprise-providers/${provider}/assertion`;const response = await fetchWithTimeout(url, {method: "POST",headers: requestHeaders(identity, true),- body: "{}",+ body: JSON.stringify(inferenceScope ? { inferenceScope } : {}),});assertIdentityCurrent(identity);if (!response.ok) {@@ -370,7 +381,9 @@ function createEnterpriseIdentityManager({const prior = configs.get(identity.cacheKey)?.config || cachedConfig(cachePath, identity);error.enforcementRequired =error.code === "ENTERPRISE_REQUIRED" ? false : requiresEnforcedManagedAccess(prior);- evictIdentity(identity, error.code, error.enforcementRequired);+ error.enforcedScopes =+ error.code === "ENTERPRISE_REQUIRED" ? [] : managedScopesForConfig(prior).enforced;+ evictIdentity(identity, error.code, error.enforcementRequired, error.enforcedScopes);}throw error;}@@ -421,7 +434,7 @@ function createEnterpriseIdentityManager({return {credentialProvider: () =>dedupeCredential(key, async () => {- const assertion = await fetchAssertion(identity, "bedrock");+ const assertion = await fetchAssertion(identity, "bedrock", resolution.inferenceScope);const credentials = await createAwsWebIdentityProvider({roleArn: record.config.roleArn,roleSessionName: `openwhispr-${identity.workspaceId.slice(0, 8)}`,@@ -456,7 +469,7 @@ function createEnterpriseIdentityManager({return {tokenProvider: () =>dedupeCredential(key, async () => {- const assertion = await fetchAssertion(identity, "azure");+ const assertion = await fetchAssertion(identity, "azure", resolution.inferenceScope);const tokenUrl = `https://login.microsoftonline.com/${encodeURIComponent(record.config.tenantId)}/oauth2/v2.0/token`;@@ -514,7 +527,11 @@ function createEnterpriseIdentityManager({config: resolution.record.config,version: resolution.record.version,generation: config.generation,- ...managedProviderFunctions(identity, { ...resolution, generation: config.generation }),+ ...managedProviderFunctions(identity, {+ ...resolution,+ generation: config.generation,+ inferenceScope: request.inferenceScope,+ }),};}diff --git a/src/helpers/enterpriseManagedConfig.mjs b/src/helpers/enterpriseManagedConfig.mjsindex 0486644aa..a84374859 100644--- a/src/helpers/enterpriseManagedConfig.mjs+++ b/src/helpers/enterpriseManagedConfig.mjs@@ -6,6 +6,9 @@ const ENTERPRISE_INFERENCE_SCOPES = ["dictationTranslation",];+/** The managed speech-to-text scope; resolved from the Azure `transcription` config section. */+const ENTERPRISE_TRANSCRIPTION_SCOPE = "transcription";+const ENTERPRISE_PROVIDERS = ["bedrock", "azure"];const PROVIDER_MODES = ["disabled", "managed_default", "managed_required"];const AWS_ROLE_ARN = /^arn:(aws|aws-us-gov):iam::\d{12}:role\/[A-Za-z0-9+=,.@_/-]{1,512}$/;@@ -40,13 +43,21 @@ function isSafeHttpsUrl(value) {}}+// Azure OpenAI resource hosts, including AI Foundry deployments.+const AZURE_HOST_SUFFIXES = [+ ".openai.azure.com",+ ".cognitiveservices.azure.com",+ ".services.ai.azure.com",+];+function isAllowedAzureEndpoint(value) {if (!isSafeHttpsUrl(value)) return false;const url = new URL(value);const hostname = url.hostname.toLowerCase();return (- hostname.endsWith(".openai.azure.com") &&- hostname.length > ".openai.azure.com".length &&+ AZURE_HOST_SUFFIXES.some(+ (suffix) => hostname.endsWith(suffix) && hostname.length > suffix.length+ ) &&(url.pathname === "" || url.pathname === "/") &&!url.search &&!url.hash@@ -57,16 +68,7 @@ function isAllowedAzureApiVersion(value) {return value === "v1" || value === "preview" || AZURE_LEGACY_API_VERSION.test(value);}-function isValidProviderConfig(record) {- if (!record || !ENTERPRISE_PROVIDERS.includes(record.provider)) return false;- if (!PROVIDER_MODES.includes(record.mode) || typeof record.allowManualSetup !== "boolean") {- return false;- }- if (!Number.isSafeInteger(record.version) || record.version < 1) return false;- const config = record.config;- if (!config || typeof config !== "object") return false;- const allowed = record.provider === "bedrock" ? config.allowedModels : config.allowedDeployments;- const defaults = config.scopeDefaults;+function isValidLlmSection(allowed, defaults) {if (!Array.isArray(allowed) || allowed.length === 0 || !allowed.every(isNonEmptyString)) {return false;}@@ -77,18 +79,52 @@ function isValidProviderConfig(record) {) {return false;}- if (!Object.values(defaults).every((model) => allowed.includes(model))) return false;+ return Object.values(defaults).every((model) => allowed.includes(model));+}++function isValidTranscriptionSection(transcription) {+ return (+ transcription &&+ typeof transcription === "object" &&+ Array.isArray(transcription.allowedDeployments) &&+ transcription.allowedDeployments.length > 0 &&+ transcription.allowedDeployments.every(isNonEmptyString) &&+ isNonEmptyString(transcription.defaultDeployment) &&+ transcription.allowedDeployments.includes(transcription.defaultDeployment)+ );+}++function isValidProviderConfig(record) {+ if (!record || !ENTERPRISE_PROVIDERS.includes(record.provider)) return false;+ if (!PROVIDER_MODES.includes(record.mode) || typeof record.allowManualSetup !== "boolean") {+ return false;+ }+ if (!Number.isSafeInteger(record.version) || record.version < 1) return false;+ const config = record.config;+ if (!config || typeof config !== "object") return false;if (record.provider === "bedrock") {const partition = typeof config.roleArn === "string" ? config.roleArn.split(":")[1] : null;const isGovRegion = typeof config.region === "string" && config.region.startsWith("us-gov-");return (+ isValidLlmSection(config.allowedModels, config.scopeDefaults) &&AWS_ROLE_ARN.test(config.roleArn) &&AWS_REGION.test(config.region) &&(partition === "aws-us-gov") === isGovRegion &&!config.region.startsWith("cn-"));}+ // Azure carries independent text and transcription sections; at least one+ // must be present and every present section must be complete.+ const hasLlmSection =+ config.allowedDeployments !== undefined || config.scopeDefaults !== undefined;+ if (!hasLlmSection && config.transcription === undefined) return false;+ if (hasLlmSection && !isValidLlmSection(config.allowedDeployments, config.scopeDefaults)) {+ return false;+ }+ if (config.transcription !== undefined && !isValidTranscriptionSection(config.transcription)) {+ return false;+ }return (UUID.test(config.tenantId) &&UUID.test(config.clientId) &&@@ -134,14 +170,21 @@ function resolutionError(code, message) {return { kind: "error", code, message };}+function managedModelFor(record, scope) {+ if (scope === ENTERPRISE_TRANSCRIPTION_SCOPE) {+ return record.config.transcription?.defaultDeployment;+ }+ return record.config.scopeDefaults?.[scope];+}+function resolveManagedEnterpriseScope(envelope, scope, setupMode = "auto") {- if (!ENTERPRISE_INFERENCE_SCOPES.includes(scope)) {+ if (!ENTERPRISE_INFERENCE_SCOPES.includes(scope) && scope !== ENTERPRISE_TRANSCRIPTION_SCOPE) {return resolutionError("MANAGED_SCOPE_INVALID", "The requested inference scope is invalid.");}if (!envelope?.providers?.length) return { kind: "manual" };const configured = envelope.providers.filter(- (record) => record.mode !== "disabled" && isNonEmptyString(record.config.scopeDefaults[scope])+ (record) => record.mode !== "disabled" && isNonEmptyString(managedModelFor(record, scope)));if (!configured.length) return { kind: "manual" };@@ -161,16 +204,40 @@ function resolveManagedEnterpriseScope(envelope, scope, setupMode = "auto") {return {kind: "managed",provider: record.provider,- model: record.config.scopeDefaults[scope],+ model: managedModelFor(record, scope),mode: record.mode,allowManualSetup: record.allowManualSetup,record,};}+/**+ * Scopes any active record resolves a managed model for, and the subset that+ * is enforced (managed_required or manual setup disallowed). Enforcement is+ * per scope: a text-only workspace must never fail transcription closed.+ */+function managedScopesForConfig(config) {+ const managed = [];+ const enforced = [];+ for (const record of config?.providers ?? []) {+ if (record.mode === "disabled") continue;+ const isEnforced = record.mode === "managed_required" || !record.allowManualSetup;+ for (const scope of [...ENTERPRISE_INFERENCE_SCOPES, ENTERPRISE_TRANSCRIPTION_SCOPE]) {+ if (!isNonEmptyString(managedModelFor(record, scope))) continue;+ if (!managed.includes(scope)) managed.push(scope);+ if (isEnforced && !enforced.includes(scope)) enforced.push(scope);+ }+ }+ return { managed, enforced };+}+export {+ AZURE_HOST_SUFFIXES,ENTERPRISE_INFERENCE_SCOPES,+ ENTERPRISE_TRANSCRIPTION_SCOPE,ENTERPRISE_PROVIDERS,+ isAllowedAzureEndpoint,validateManagedEnterpriseEnvelope,resolveManagedEnterpriseScope,+ managedScopesForConfig,};diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex bd0cb279a..379646526 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -166,6 +166,9 @@ const AUDIO_MIME_TYPES = {};const CLOUD_INLINE_LIMIT = 4 * 1024 * 1024;+// The enterprise "Test Connection" probe only needs one word back, but the+// Azure Responses API rejects max_output_tokens below 16.+const CONNECTION_TEST_MAX_OUTPUT_TOKENS = 16;const CLOUD_CHUNK_SEGMENT_SECONDS = 240;const { createAbortError } = require("./abortError");@@ -642,6 +645,7 @@ class IPCHandlers {if (!token) {this.databaseManager.setActiveAccountId(null);accountScopeBinding.clear();+ broadcastToWindows("active-account-scope-changed", null);}broadcastToWindows("auth-token-state-changed", {generation,@@ -2046,9 +2050,20 @@ class IPCHandlers {this.databaseManager.setActiveAccountId(accountId);if (accountId !== null) accountScopeBinding.persist(accountId, state.token);else accountScopeBinding.clear();+ broadcastToWindows(+ "active-account-scope-changed",+ accountId !== null ? { accountId, authGeneration: state.generation } : null+ );return { success: true };});+ ipcMain.handle("get-active-account-scope", () =>+ accountScopeBinding.resolveActiveAccountScope({+ ...tokenStore.getState(),+ binding: accountScopeBinding.read(),+ })+ );+ipcMain.handle("delete-account-data", async (_event, accountId, expectedGeneration) => {const state = tokenStore.getState();if (@@ -4462,7 +4477,7 @@ class IPCHandlers {return generateText({model,prompt: "Say hello in one word.",- maxOutputTokens: 10,+ maxOutputTokens: CONNECTION_TEST_MAX_OUTPUT_TOKENS,abortSignal,maxRetries: 0,});@@ -4472,7 +4487,7 @@ class IPCHandlers {await generateText({model,prompt: "Say hello in one word.",- maxOutputTokens: 10,+ maxOutputTokens: CONNECTION_TEST_MAX_OUTPUT_TOKENS,});}@@ -5778,6 +5793,35 @@ class IPCHandlers {},};};+ const { createManagedTranscriptionExecutor } = require("./managedTranscriptionExecutor");+ const executeManagedTranscription = createManagedTranscriptionExecutor({+ resolveEnterpriseRuntime,+ proxyFetch,+ buildUrl: async (endpoint, deployment, apiVersion) => {+ const { buildManagedAzureTranscriptionUrl } = await import("../utils/urlUtils.ts");+ return buildManagedAzureTranscriptionUrl(endpoint, deployment, apiVersion);+ },+ });+ this.executeManagedTranscription = executeManagedTranscription;++ ipcMain.handle(+ "managed-transcribe",+ serializeIpcError(+ async (event, { audioBuffer, fileName, mimeType, language, prompt, managed }) => {+ const text = await executeManagedTranscription(+ event,+ { provider: managed.provider, context: managed.context, language },+ {+ audioBuffer: Buffer.from(audioBuffer),+ fileName: fileName || "audio.webm",+ contentType: mimeType || "audio/webm",+ prompt,+ }+ );+ return { text };+ }+ )+ );const handleSttConfigRequest = createCloudConfigRequestHandler({getApiUrl,getAuthHeader,@@ -5953,6 +5997,7 @@ class IPCHandlers {const route = resolveTranscriptionRoute({settings: settings || {},providers: transcriptionProviderBaseUrls(),+ managed: settings?.managed,request: { effectiveLanguage: language },});@@ -5969,7 +6014,14 @@ class IPCHandlers {throw err;}- if (route.transport === "http-batch" && route.provider === "self-hosted") {+ if (route.transport === "managed") {+ const text = await this.executeManagedTranscription(event, route, {+ audioBuffer: buffer,+ fileName: "audio.webm",+ contentType: "audio/webm",+ });+ result = { text, source: "azure-managed", model: route.deployment };+ } else if (route.transport === "http-batch" && route.provider === "self-hosted") {const formData = new FormData();formData.append("file", new Blob([buffer], { type: "audio/webm" }), "audio.webm");if (route.model) {@@ -9324,6 +9376,7 @@ class IPCHandlers {transcriptionMode,remoteTranscriptionUrl,remoteTranscriptionModel,+ managed,}) => {const fs = require("fs");@@ -9347,12 +9400,31 @@ class IPCHandlers {cortiTenant: tenant,},providers: transcriptionProviderBaseUrls(),+ managed,request: { effectiveLanguage: language || undefined },});// Fail closed: a misconfigured route must never fall through to a default.if (route.transport === "error") {- return { success: false, error: route.message, code: route.code };+ return {+ success: false,+ error: route.message,+ code: route.code,+ messageKey: route.messageKey,+ };+ }++ if (route.transport === "managed") {+ if (fs.statSync(realByok).size > route.sizeCapBytes) {+ return { success: false, error: byokSizeCapError(route.sizeCapBytes) };+ }+ const ext = path.extname(realByok).toLowerCase().replace(".", "");+ const text = await this.executeManagedTranscription(event, route, {+ audioBuffer: fs.readFileSync(realByok),+ fileName: path.basename(realByok),+ contentType: AUDIO_MIME_TYPES[ext] || "audio/mpeg",+ });+ return { success: true, text };}if (route.transport === "http-batch" && route.provider === "self-hosted") {@@ -9548,7 +9620,12 @@ class IPCHandlers {return { success: true, text: data.data.text, ...(segments ? { segments } : {}) };} catch (error) {debugLogger.error("BYOK audio file transcription error", { error: error.message });- return { success: false, error: error.message };+ return {+ success: false,+ error: error.message,+ code: error.code,+ messageKey: error.messageKey,+ };}});diff --git a/src/helpers/managedTranscriptionExecutor.js b/src/helpers/managedTranscriptionExecutor.jsnew file mode 100644index 000000000..a7e1774c6--- /dev/null+++ b/src/helpers/managedTranscriptionExecutor.js@@ -0,0 +1,85 @@+// Managed Azure STT shared by dictation, file upload, and history retry:+// re-validates the renderer's managed context (MANAGED_CONFIG_CHANGED on+// mismatch), mints an Entra token, and posts the audio straight to the+// workspace's Azure resource. No user-owned API key is involved.+const DEFAULT_TIMEOUT_MS = 120_000;++// Azure keys the accepted-format check off the multipart filename's extension+// and does not list "opus". Every .opus file is Opus in an Ogg container, so+// the .ogg name it does accept describes the same bytes.+function azureFileName(fileName) {+ return fileName.replace(/\.opus$/i, ".ogg");+}++function createManagedTranscriptionExecutor({+ resolveEnterpriseRuntime,+ proxyFetch,+ buildUrl,+ timeoutMs = DEFAULT_TIMEOUT_MS,+}) {+ return async function executeManagedTranscription(+ event,+ route,+ { audioBuffer, fileName, contentType, prompt }+ ) {+ if (route?.provider !== "azure" || route?.context?.inferenceScope !== "transcription") {+ throw Object.assign(new Error("Managed transcription route is invalid"), {+ code: "MANAGED_ROUTE_INVALID",+ messageKey: "hooks.audioRecording.errorDescriptions.managedRouteInvalid",+ });+ }+ const runtime = await resolveEnterpriseRuntime(event, route.provider, null, {+ managedContext: route.context,+ });+ const { azureEndpoint, azureApiVersion, managedTokenProvider } = runtime.enterprise;+ // The workspace's default deployment wins over anything the renderer sent.+ const deployment = runtime.model;+ const endpoint = await buildUrl(azureEndpoint, deployment, azureApiVersion);+ if (!endpoint) {+ throw new Error("Managed Azure transcription endpoint could not be built");+ }+ const token = await managedTokenProvider();+ const formData = new FormData();+ formData.append(+ "file",+ new Blob([audioBuffer], { type: contentType }),+ azureFileName(fileName)+ );+ formData.append("model", deployment);+ formData.append("response_format", "json");+ if (route.language && route.language !== "auto") {+ formData.append("language", route.language);+ }+ if (prompt) formData.append("prompt", prompt);+ const response = await proxyFetch(endpoint, {+ method: "POST",+ headers: { Authorization: `Bearer ${token}` },+ body: formData,+ signal: AbortSignal.timeout(timeoutMs),+ });+ if (!response.ok) {+ const errorText = await response.text();+ const err = new Error(`Azure transcription error: ${response.status} ${errorText}`);+ if (response.status === 429) {+ err.code = "PROVIDER_RATE_LIMITED";+ err.messageKey = "hooks.audioRecording.errorDescriptions.providerRateLimited";+ } else if (response.status === 401 || response.status === 403) {+ err.code = "MANAGED_AUTH_REJECTED";+ err.messageKey = "hooks.audioRecording.errorDescriptions.managedAuthRejected";+ } else if (response.status >= 500) {+ err.code = "SERVER_ERROR";+ }+ throw err;+ }+ const result = await response.json();+ if (typeof result?.text !== "string") {+ throw new Error("Managed transcription response was malformed");+ }+ if (!result.text.trim()) {+ throw Object.assign(new Error("No speech detected in audio"), { code: "NO_SPEECH_DETECTED" });+ }+ return result.text;+ };+}++module.exports = { createManagedTranscriptionExecutor };diff --git a/src/helpers/policyValidation.js b/src/helpers/policyValidation.jsindex 0e25458b7..214cb2597 100644--- a/src/helpers/policyValidation.js+++ b/src/helpers/policyValidation.js@@ -7,8 +7,16 @@ 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_MODES = new Set([+ "openwhispr",+ "providers",+ "local",+ "self-hosted",+ "enterprise",+]);+const LLM_MODES = TRANSCRIPTION_MODES;+// Enterprise clouds with a managed transcription implementation (Azure only for now).+const TRANSCRIPTION_ENTERPRISE_PROVIDERS = new Set(["azure"]);const TRANSCRIPTION_PROVIDERS = new Set(modelRegistryData.transcriptionProviders.map((provider) => provider.id).concat("custom"));@@ -33,6 +41,12 @@ function isValidPolicyShape(policy) {POLICY_SCOPES.every((scope) => Boolean(policy[scope])) &&isKnownList(policy.transcription.allowedModes, TRANSCRIPTION_MODES) &&isKnownList(policy.transcription.allowedByokProviders, TRANSCRIPTION_PROVIDERS) &&+ // Additive within policy version 1: absent (older server) means none.+ (policy.transcription.allowedEnterpriseProviders === undefined ||+ isKnownList(+ policy.transcription.allowedEnterpriseProviders,+ TRANSCRIPTION_ENTERPRISE_PROVIDERS+ )) &&isKnownList(policy.llm.allowedModes, LLM_MODES) &&isKnownList(policy.llm.allowedByokProviders, LLM_PROVIDERS) &&isKnownList(policy.llm.allowedEnterpriseProviders, ENTERPRISE_PROVIDERS) &&diff --git a/src/helpers/transcriptionRoute.ts b/src/helpers/transcriptionRoute.tsindex 623f5a94e..8b422a952 100644--- a/src/helpers/transcriptionRoute.ts+++ b/src/helpers/transcriptionRoute.ts@@ -26,6 +26,7 @@ import {TINFOIL_PROXY_REQUIRED_ERROR,type TranscriptionProviderBaseUrl,} from "../services/transcriptionBaseUrl.ts";+import type { ManagedEnterpriseRequestContext } from "../types/enterpriseIdentity.ts";const BYOK_FILE_SIZE_LIMIT = 25 * 1024 * 1024;@@ -39,6 +40,8 @@ export function byokFileSizeLimit(provider: string): number {const CUSTOM_ENDPOINT_INVALID_MESSAGE_KEY ="hooks.audioRecording.errorDescriptions.customEndpointInvalid";+const MANAGED_TRANSCRIPTION_UNAVAILABLE_MESSAGE_KEY =+ "hooks.audioRecording.errorDescriptions.managedTranscriptionUnavailable";export interface TranscriptionRouteSettings {transcriptionMode?: string;@@ -53,6 +56,20 @@ export interface TranscriptionRouteSettings {preferredLanguage?: string;}+/**+ * Outcome of managed enterprise STT resolution, computed by the caller+ * (renderer: enterpriseIdentityStore; main: enterpriseIdentityManager). The+ * context is identity metadata for main-process re-validation, never a secret.+ */+export type ManagedTranscriptionResolution =+ | {+ kind: "managed";+ provider: "azure";+ deployment: string;+ context: ManagedEnterpriseRequestContext;+ }+ | { kind: "error"; message: string; code: string; messageKey?: string };+export interface TranscriptionRouteInput {/** Policy-EFFECTIVE, scope-resolved snapshot — the resolver never re-maps selections. */settings: TranscriptionRouteSettings;@@ -60,6 +77,8 @@ export interface TranscriptionRouteInput {policy?: PolicyDecisionSnapshot | null;/** Provider registry, for the Tinfoil-host guard. Renderer passes ModelRegistry, main the raw JSON. */providers?: readonly TranscriptionProviderBaseUrl[];+ /** Managed enterprise STT outcome; when present it outranks every personal setting. */+ managed?: ManagedTranscriptionResolution | null;request?: {/** Explicit model override; doubles as the Azure deployment name. */model?: string;@@ -88,6 +107,16 @@ export type TranscriptionRoute =auth: { scheme: "bearer" | "azure-api-key" | "none"; keyRef: string | null };sizeCapBytes: number | null;language?: string;+ }+ | {+ // Workspace-managed Azure STT. Executed only in the main process, which+ // re-validates the context and holds the Entra token.+ transport: "managed";+ provider: "azure";+ deployment: string;+ context: ManagedEnterpriseRequestContext;+ sizeCapBytes: number;+ language?: string;};// xAI STT supports 25 languages; language must be in this set to enable ITN via format=true@@ -178,10 +207,44 @@ export function resolveTranscriptionRoute({settings,policy,providers = [],+ managed: managedResolution,request,}: TranscriptionRouteInput): TranscriptionRoute {const s = settings || {};const managed = policy?.status === "managed";+ const language =+ request?.effectiveLanguage ??+ (!s.preferredLanguage || s.preferredLanguage === "auto"+ ? undefined+ : s.preferredLanguage.split("-")[0]);++ // Managed enterprise STT outranks every personal setting; the resolution is+ // already policy-checked where it was computed (enterpriseIdentityStore /+ // enterpriseIdentityManager), so the selection floor below does not apply.+ if (managedResolution) {+ if (managedResolution.kind === "error") {+ return error(managedResolution.message, managedResolution.code, managedResolution.messageKey);+ }+ return {+ transport: "managed",+ provider: managedResolution.provider,+ deployment: managedResolution.deployment,+ context: managedResolution.context,+ sizeCapBytes: BYOK_FILE_SIZE_LIMIT,+ language,+ };+ }++ // A policy-effective "enterprise" selection with no managed resolution means+ // the managed config has not resolved (loading, evicted, or absent). Never+ // fall through to a personal lane in that state.+ if (s.transcriptionMode === "enterprise") {+ return error(+ "Managed transcription is not available right now. Try again in a moment.",+ "MANAGED_CONFIG_UNAVAILABLE",+ MANAGED_TRANSCRIPTION_UNAVAILABLE_MESSAGE_KEY+ );+ }// Fail-closed floor only: callers pass policy-effective settings, so a// disallowed selection here means the policy layer was bypassed upstream.@@ -199,12 +262,6 @@ export function resolveTranscriptionRoute({);}- const language =- request?.effectiveLanguage ??- (!s.preferredLanguage || s.preferredLanguage === "auto"- ? undefined- : s.preferredLanguage.split("-")[0]);-// Self-hosted wins over everything, including stale useLocalWhisper flags.// The route needs a configured URL: `byok + custom` also persists// transcriptionMode="self-hosted" (deriveTranscriptionMode), sodiff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.jsindex 7db3c8af4..4d70f49e5 100644--- a/src/hooks/useAudioRecording.js+++ b/src/hooks/useAudioRecording.js@@ -13,6 +13,7 @@ import {isScreenContextAllowed,isTranscriptionContextAllowed,} from "../stores/policyRules";+import { isManagedTranscriptionActive } from "../services/managedTranscription";import { usePolicyStore } from "../stores/policyStore";import { getOnboardingDemoKind } from "../utils/onboardingDemo";import {@@ -118,7 +119,8 @@ export const useAudioRecording = (toast, options = {}) => {if (!audioManagerRef.current) return false;const policyState = usePolicyStore.getState();if (- !isTranscriptionContextAllowed(policyState, getSettings(), "dictation") ||+ (!isManagedTranscriptionActive() &&+ !isTranscriptionContextAllowed(policyState, getSettings(), "dictation")) ||(voiceAgentRequested && !isAgentAllowed(policyState))) {toast({ title: t("common.managedByOrg"), variant: "default" });diff --git a/src/lib/accountScopeMirror.ts b/src/lib/accountScopeMirror.tsnew file mode 100644index 000000000..8d647d8cd--- /dev/null+++ b/src/lib/accountScopeMirror.ts@@ -0,0 +1,57 @@+import { useEnterpriseIdentityStore } from "../stores/enterpriseIdentityStore";+import { usePolicyStore } from "../stores/policyStore";+import { ACTIVE_WORKSPACE_KEY, refreshManagedEnterpriseIdentity } from "../stores/workspaceStore";+import type { ActiveAccountScope } from "../types/electron";++/**+ * Hydrates the workspace policy and managed enterprise identity in a window+ * that cannot resolve its own session. The dictation window is sandboxed with+ * web security enforced, so Better Auth's cross-origin session fetch fails+ * there and the session-driven hydration in useAuth never runs. The control+ * panel validates the session and the main process persists that scope; this+ * mirrors it back over IPC, both the value at boot and every later change+ * (re-validation under a new credential generation, sign-out). The active+ * workspace is the control panel's choice, read from the localStorage key it+ * writes, which every window of this origin shares.+ */+export function mirrorActiveAccountScope(): () => void {+ let scope: ActiveAccountScope | null = null;+ let broadcastReceived = false;++ const refreshIdentity = () => {+ if (!scope) return;+ refreshManagedEnterpriseIdentity(+ scope.accountId,+ scope.authGeneration,+ localStorage.getItem(ACTIVE_WORKSPACE_KEY)+ );+ };+ const applyScope = (next: ActiveAccountScope | null) => {+ scope = next;+ if (!next) {+ usePolicyStore.getState().clearPolicy();+ useEnterpriseIdentityStore.getState().clear();+ return;+ }+ void usePolicyStore.getState().fetchPolicy(next.accountId, next.authGeneration);+ refreshIdentity();+ };+ const onStorage = (event: StorageEvent) => {+ if (event.key === ACTIVE_WORKSPACE_KEY) refreshIdentity();+ };++ window.addEventListener("storage", onStorage);+ const unsubscribe = window.electronAPI?.onActiveAccountScopeChanged?.((next) => {+ broadcastReceived = true;+ applyScope(next);+ });+ // A scope validated while the boot read was in flight has already arrived by+ // broadcast; the read's answer is the older of the two.+ void window.electronAPI?.getActiveAccountScope?.().then((next) => {+ if (!broadcastReceived) applyScope(next);+ });+ return () => {+ window.removeEventListener("storage", onStorage);+ unsubscribe?.();+ };+}diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 15e65d498..41d54a6a6 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -201,7 +201,10 @@"skip": "Überspringen","policyAiProcessingRestricted": "Die KI-Verarbeitung ist durch Ihre Organisation eingeschränkt.","policyAgentRestricted": "Die Nutzung des KI-Agenten ist durch Ihre Organisation eingeschränkt.",- "policyTranscriptionRestricted": "Die Transkription ist durch Ihre Organisation eingeschränkt."+ "policyTranscriptionRestricted": "Die Transkription ist durch Ihre Organisation eingeschränkt.",+ "managedConfigLoading": "Die verwaltete Einrichtung Ihrer Organisation wird überprüft. Versuchen Sie es gleich noch einmal.",+ "managedConfigUnavailable": "Der verwaltete Unternehmenszugriff ist nicht verfügbar. Melden Sie sich erneut an oder wenden Sie sich an Ihren Administrator.",+ "managedPolicyConflict": "Der verwaltete Zugriff wird durch Ihre Workspace-Richtlinie blockiert. Wenden Sie sich an Ihren Administrator."},"onboarding": {"rehaul": {@@ -903,7 +906,10 @@"chunkLoss": "Ein Netzwerkproblem hat zu viel von der Aufnahme verloren. Transkribieren Sie sie über den Verlauf erneut.","agentReasoningFailed": "Ihr Sprachassistent konnte den Befehl nicht verarbeiten – stattdessen wurde das unbearbeitete Transkript eingefügt.","screenContextSkipped": "Der Screenshot konnte nicht gesendet werden, daher lief Ihr Befehl ohne Bildschirmkontext.",- "customEndpointInvalid": "Ihr benutzerdefinierter Transkriptionsendpunkt ist nicht konfiguriert oder seine URL ist ungültig. Aktualisieren Sie ihn unter Einstellungen → Sprache zu Text."+ "customEndpointInvalid": "Ihr benutzerdefinierter Transkriptionsendpunkt ist nicht konfiguriert oder seine URL ist ungültig. Aktualisieren Sie ihn unter Einstellungen → Sprache zu Text.",+ "managedTranscriptionUnavailable": "Die verwaltete Transkription ist derzeit nicht verfügbar. Versuchen Sie es gleich noch einmal.",+ "managedRouteInvalid": "Die verwaltete Transkription konnte aufgrund einer Konfigurationsabweichung nicht gestartet werden. Versuchen Sie es erneut oder wenden Sie sich an Ihren Administrator.",+ "managedAuthRejected": "Die verwalteten Transkriptions-Anmeldedaten Ihrer Organisation wurden abgelehnt. Wenden Sie sich an Ihren Administrator."},"translationFallback": {"unreachableTitle": "Übersetzung nicht verfügbar",@@ -2456,7 +2462,9 @@"openwhisprDesc": "Zuverlässige Ergebnisse. Keine Einrichtung nötig.","providersDesc": "Eigenen API-Schlüssel nutzen.","localDesc": "Modelle auf dem Gerät. Voll privat.",- "selfHostedDesc": "Eigener Server in Ihrem Netzwerk."+ "selfHostedDesc": "Eigener Server in Ihrem Netzwerk.",+ "enterprise": "Unternehmens-Cloud",+ "enterpriseDesc": "Audio wird an die eigene Cloud Ihrer Organisation gesendet."},"openwhisprCloud": "OpenWhispr Cloud","openwhisprCloudDescription": "Zuverlässige Ergebnisse. Keine Einrichtung nötig.",@@ -2481,6 +2489,10 @@"switchedSelfHosted": {"title": "Selbst gehostet","description": "Verwendung Ihres eigenen Servers."+ },+ "switchedEnterprise": {+ "title": "Unternehmens-Cloud ausgewählt",+ "description": "Diktate verwenden jetzt die von Ihrer Organisation verwaltete Transkription."}},"gpuDevice": {@@ -2538,7 +2550,8 @@"info": "Audio, das von einem Segment ins nächste übertragen wird, um abrupte Schnitte beim Zusammenfügen zu vermeiden."}}- }+ },+ "meetingEnterpriseOnly": "Ihre Organisation erlaubt nur Unternehmens-Cloud-Transkription, die Besprechungsaufnahmen noch nicht abdeckt."},"intelligence": {"gpuDevice": {diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex c5eb62d33..34b2bde89 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -201,7 +201,10 @@"skip": "Skip","policyAiProcessingRestricted": "AI processing is restricted by your organization.","policyAgentRestricted": "AI agent use is restricted by your organization.",- "policyTranscriptionRestricted": "Transcription is restricted by your organization."+ "policyTranscriptionRestricted": "Transcription is restricted by your organization.",+ "managedConfigLoading": "Checking your organization's managed setup. Try again in a moment.",+ "managedConfigUnavailable": "Managed enterprise access is unavailable. Sign in again or contact your administrator.",+ "managedPolicyConflict": "Managed access is blocked by your workspace policy. Contact your administrator."},"onboarding": {"rehaul": {@@ -903,7 +906,10 @@"chunkLoss": "A network problem lost too much of the recording. Re-transcribe it from History.","agentReasoningFailed": "Your voice assistant couldn't process the command — the raw transcript was inserted instead.","screenContextSkipped": "The screenshot couldn't be sent, so your command ran without screen context.",- "customEndpointInvalid": "Your custom transcription endpoint is not configured or its URL is invalid. Update it in Settings → Speech to Text."+ "customEndpointInvalid": "Your custom transcription endpoint is not configured or its URL is invalid. Update it in Settings → Speech to Text.",+ "managedTranscriptionUnavailable": "Managed transcription is not available right now. Try again in a moment.",+ "managedRouteInvalid": "Managed transcription couldn't start due to a configuration mismatch. Try again or contact your administrator.",+ "managedAuthRejected": "Your organization's managed transcription credentials were rejected. Contact your administrator."},"translationFallback": {"unreachableTitle": "Translation unavailable",@@ -2456,7 +2462,9 @@"openwhisprDesc": "Reliable accuracy. No setup needed.","providersDesc": "Bring your own API key.","localDesc": "On-device models. Fully private.",- "selfHostedDesc": "Your own server on your network."+ "selfHostedDesc": "Your own server on your network.",+ "enterprise": "Enterprise cloud",+ "enterpriseDesc": "Audio goes to your organization's own cloud."},"openwhisprCloud": "OpenWhispr Cloud","openwhisprCloudDescription": "Reliable accuracy. No setup needed.",@@ -2481,6 +2489,10 @@"switchedSelfHosted": {"title": "Self-Hosted","description": "Using your own server."+ },+ "switchedEnterprise": {+ "title": "Enterprise cloud selected",+ "description": "Dictation now uses the transcription deployment your organization manages."}},"gpuDevice": {@@ -2538,7 +2550,8 @@"info": "Audio carried from each segment into the next to avoid abrupt cuts when concatenating."}}- }+ },+ "meetingEnterpriseOnly": "Your organization only allows enterprise cloud transcription, which does not cover meeting recording yet."},"intelligence": {"gpuDevice": {diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 3cdca944c..e912da894 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -201,7 +201,10 @@"skip": "Omitir","policyAiProcessingRestricted": "El procesamiento con IA está restringido por tu organización.","policyAgentRestricted": "El uso del agente de IA está restringido por tu organización.",- "policyTranscriptionRestricted": "La transcripción está restringida por tu organización."+ "policyTranscriptionRestricted": "La transcripción está restringida por tu organización.",+ "managedConfigLoading": "Comprobando la configuración gestionada de tu organización. Inténtalo de nuevo en un momento.",+ "managedConfigUnavailable": "El acceso empresarial gestionado no está disponible. Vuelve a iniciar sesión o contacta a tu administrador.",+ "managedPolicyConflict": "El acceso gestionado está bloqueado por la política de tu espacio de trabajo. Contacta a tu administrador."},"onboarding": {"rehaul": {@@ -903,7 +906,10 @@"chunkLoss": "Un problema de red hizo que se perdiera demasiada parte de la grabación. Vuelve a transcribirla desde el historial.","agentReasoningFailed": "Tu asistente de voz no pudo procesar el comando; se insertó la transcripción sin procesar.","screenContextSkipped": "No se pudo enviar la captura, así que tu comando se ejecutó sin contexto de pantalla.",- "customEndpointInvalid": "Tu endpoint de transcripción personalizado no está configurado o su URL no es válida. Actualízalo en Ajustes → Voz a texto."+ "customEndpointInvalid": "Tu endpoint de transcripción personalizado no está configurado o su URL no es válida. Actualízalo en Ajustes → Voz a texto.",+ "managedTranscriptionUnavailable": "La transcripción gestionada no está disponible en este momento. Inténtalo de nuevo en un momento.",+ "managedRouteInvalid": "La transcripción gestionada no pudo iniciarse debido a una discrepancia de configuración. Inténtalo de nuevo o contacta a tu administrador.",+ "managedAuthRejected": "Las credenciales de transcripción gestionada de tu organización fueron rechazadas. Contacta a tu administrador."},"translationFallback": {"unreachableTitle": "Traducción no disponible",@@ -2215,7 +2221,9 @@"openwhisprDesc": "Resultados fiables. Sin configuración.","providersDesc": "Usa tu propia clave API.","localDesc": "Modelos en el dispositivo. Privado.",- "selfHostedDesc": "Tu servidor en tu red."+ "selfHostedDesc": "Tu servidor en tu red.",+ "enterprise": "Nube empresarial",+ "enterpriseDesc": "El audio se envía a la nube propia de tu organización."},"openwhisprCloud": "OpenWhispr Cloud","openwhisprCloudDescription": "Resultados fiables. Sin configuración.",@@ -2240,6 +2248,10 @@"switchedSelfHosted": {"title": "Autoalojado","description": "Usando tu propio servidor."+ },+ "switchedEnterprise": {+ "title": "Nube empresarial seleccionada",+ "description": "El dictado ahora usa la transcripción gestionada por tu organización."}},"gpuDevice": {@@ -2297,7 +2309,8 @@"info": "Audio que se extiende de un segmento al siguiente para evitar cortes bruscos al concatenarlos."}}- }+ },+ "meetingEnterpriseOnly": "Tu organización solo permite la transcripción en nube empresarial, que aún no cubre la grabación de reuniones."},"intelligence": {"gpuDevice": {diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex efcaf51bb..325d7f69f 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -201,7 +201,10 @@"skip": "Passer","policyAiProcessingRestricted": "Le traitement par IA est restreint par votre organisation.","policyAgentRestricted": "L’utilisation de l’agent IA est restreinte par votre organisation.",- "policyTranscriptionRestricted": "La transcription est restreinte par votre organisation."+ "policyTranscriptionRestricted": "La transcription est restreinte par votre organisation.",+ "managedConfigLoading": "Vérification de la configuration gérée de votre organisation en cours. Réessayez dans un instant.",+ "managedConfigUnavailable": "L'accès d'entreprise géré est indisponible. Reconnectez-vous ou contactez votre administrateur.",+ "managedPolicyConflict": "L'accès géré est bloqué par la politique de votre espace de travail. Contactez votre administrateur."},"onboarding": {"rehaul": {@@ -903,7 +906,10 @@"chunkLoss": "Un problème réseau a fait perdre une trop grande partie de l'enregistrement. Retranscrivez-le depuis l'historique.","agentReasoningFailed": "Votre assistant vocal n'a pas pu traiter la commande ; la transcription brute a été insérée à la place.","screenContextSkipped": "La capture n'a pas pu être envoyée ; votre commande a été exécutée sans contexte d'écran.",- "customEndpointInvalid": "Votre point de terminaison de transcription personnalisé n'est pas configuré ou son URL est invalide. Mettez-le à jour dans Réglages → Parole en texte."+ "customEndpointInvalid": "Votre point de terminaison de transcription personnalisé n'est pas configuré ou son URL est invalide. Mettez-le à jour dans Réglages → Parole en texte.",+ "managedTranscriptionUnavailable": "La transcription gérée n'est pas disponible pour le moment. Réessayez dans un instant.",+ "managedRouteInvalid": "La transcription gérée n'a pas pu démarrer en raison d'une incohérence de configuration. Réessayez ou contactez votre administrateur.",+ "managedAuthRejected": "Les identifiants de transcription gérée de votre organisation ont été refusés. Contactez votre administrateur."},"translationFallback": {"unreachableTitle": "Traduction indisponible",@@ -2456,7 +2462,9 @@"openwhisprDesc": "Résultats fiables. Aucune configuration requise.","providersDesc": "Utilisez votre propre clé API.","localDesc": "Modèles sur l'appareil. 100 % privé.",- "selfHostedDesc": "Votre serveur sur votre réseau."+ "selfHostedDesc": "Votre serveur sur votre réseau.",+ "enterprise": "Cloud d'entreprise",+ "enterpriseDesc": "L'audio est envoyé vers le cloud de votre organisation."},"openwhisprCloud": "OpenWhispr Cloud","openwhisprCloudDescription": "Résultats fiables. Aucune configuration requise.",@@ -2481,6 +2489,10 @@"switchedSelfHosted": {"title": "Auto-hébergé","description": "Utilisation de votre propre serveur."+ },+ "switchedEnterprise": {+ "title": "Cloud d'entreprise sélectionné",+ "description": "La dictée utilise désormais la transcription gérée par votre organisation."}},"gpuDevice": {@@ -2538,7 +2550,8 @@"info": "Audio prolongé d'un segment au suivant pour éviter les coupures brusques lors de la concaténation."}}- }+ },+ "meetingEnterpriseOnly": "Votre organisation n'autorise que la transcription cloud d'entreprise, qui ne couvre pas encore l'enregistrement des réunions."},"intelligence": {"gpuDevice": {diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 3940efef1..1ef3aa308 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -201,7 +201,10 @@"skip": "Salta","policyAiProcessingRestricted": "L’elaborazione con IA è limitata dalla tua organizzazione.","policyAgentRestricted": "L’uso dell’agente IA è limitato dalla tua organizzazione.",- "policyTranscriptionRestricted": "La trascrizione è limitata dalla tua organizzazione."+ "policyTranscriptionRestricted": "La trascrizione è limitata dalla tua organizzazione.",+ "managedConfigLoading": "Verifica della configurazione gestita della tua organizzazione in corso. Riprova tra un momento.",+ "managedConfigUnavailable": "L'accesso aziendale gestito non è disponibile. Accedi di nuovo o contatta l'amministratore.",+ "managedPolicyConflict": "L'accesso gestito è bloccato dai criteri del tuo spazio di lavoro. Contatta l'amministratore."},"onboarding": {"rehaul": {@@ -903,7 +906,10 @@"chunkLoss": "Un problema di rete ha fatto perdere troppa parte della registrazione. Ritrascrivila dalla cronologia.","agentReasoningFailed": "L'assistente vocale non è riuscito a elaborare il comando; è stata inserita la trascrizione grezza.","screenContextSkipped": "Non è stato possibile inviare lo screenshot, quindi il comando è stato eseguito senza contesto dello schermo.",- "customEndpointInvalid": "L'endpoint di trascrizione personalizzato non è configurato o il suo URL non è valido. Aggiornalo in Impostazioni → Da voce a testo."+ "customEndpointInvalid": "L'endpoint di trascrizione personalizzato non è configurato o il suo URL non è valido. Aggiornalo in Impostazioni → Da voce a testo.",+ "managedTranscriptionUnavailable": "La trascrizione gestita non è disponibile al momento. Riprova tra un momento.",+ "managedRouteInvalid": "La trascrizione gestita non è potuta partire per un'incoerenza di configurazione. Riprova o contatta l'amministratore.",+ "managedAuthRejected": "Le credenziali di trascrizione gestita della tua organizzazione sono state rifiutate. Contatta l'amministratore."},"translationFallback": {"unreachableTitle": "Traduzione non disponibile",@@ -2167,7 +2173,9 @@"openwhisprDesc": "Risultati affidabili. Nessuna configurazione necessaria.","providersDesc": "Usa la tua chiave API.","localDesc": "Modelli sul dispositivo. Totalmente privato.",- "selfHostedDesc": "Il tuo server nella tua rete."+ "selfHostedDesc": "Il tuo server nella tua rete.",+ "enterprise": "Cloud aziendale",+ "enterpriseDesc": "L'audio viene inviato al cloud della tua organizzazione."},"openwhisprCloud": "OpenWhispr Cloud","openwhisprCloudDescription": "Risultati affidabili. Nessuna configurazione necessaria.",@@ -2192,6 +2200,10 @@"switchedSelfHosted": {"title": "Self-hosted","description": "Utilizzo del tuo server."+ },+ "switchedEnterprise": {+ "title": "Cloud aziendale selezionato",+ "description": "La dettatura ora usa la trascrizione gestita dalla tua organizzazione."}},"gpuDevice": {@@ -2249,7 +2261,8 @@"info": "Audio esteso da un segmento al successivo per evitare tagli netti nella concatenazione."}}- }+ },+ "meetingEnterpriseOnly": "La tua organizzazione consente solo la trascrizione su cloud aziendale, che non copre ancora la registrazione delle riunioni."},"intelligence": {"gpuDevice": {diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex 8108412eb..349f13b6a 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -201,7 +201,10 @@"skip": "スキップ","policyAiProcessingRestricted": "AI処理は組織によって制限されています。","policyAgentRestricted": "AIエージェントの使用は組織によって制限されています。",- "policyTranscriptionRestricted": "文字起こしは組織によって制限されています。"+ "policyTranscriptionRestricted": "文字起こしは組織によって制限されています。",+ "managedConfigLoading": "組織のマネージド設定を確認しています。しばらくしてからもう一度お試しください。",+ "managedConfigUnavailable": "マネージド エンタープライズ アクセスを利用できません。再度サインインするか、管理者にお問い合わせください。",+ "managedPolicyConflict": "ワークスペースのポリシーによりマネージド アクセスがブロックされています。管理者にお問い合わせください。"},"onboarding": {"rehaul": {@@ -903,7 +906,10 @@"chunkLoss": "ネットワークの問題で録音の大部分が失われました。履歴から再文字起こししてください。","agentReasoningFailed": "音声アシスタントがコマンドを処理できなかったため、未処理の文字起こしを挿入しました。","screenContextSkipped": "スクリーンショットを送信できなかったため、画面コンテキストなしでコマンドを実行しました。",- "customEndpointInvalid": "カスタム文字起こしエンドポイントが未設定か、URLが無効です。設定 → 音声テキスト変換 から更新してください。"+ "customEndpointInvalid": "カスタム文字起こしエンドポイントが未設定か、URLが無効です。設定 → 音声テキスト変換 から更新してください。",+ "managedTranscriptionUnavailable": "マネージド文字起こしは現在利用できません。しばらくしてからもう一度お試しください。",+ "managedRouteInvalid": "設定の不一致により、マネージド文字起こしを開始できませんでした。もう一度お試しいただくか、管理者にお問い合わせください。",+ "managedAuthRejected": "組織のマネージド文字起こしの認証情報が拒否されました。管理者にお問い合わせください。"},"translationFallback": {"unreachableTitle": "翻訳を利用できません",@@ -2167,7 +2173,9 @@"openwhisprDesc": "信頼できる精度。設定不要。","providersDesc": "自分のAPIキーを使用。","localDesc": "端末上のモデル。完全プライベート。",- "selfHostedDesc": "自前サーバーをネットワーク上に。"+ "selfHostedDesc": "自前サーバーをネットワーク上に。",+ "enterprise": "エンタープライズクラウド",+ "enterpriseDesc": "音声は組織自身のクラウドに送信されます。"},"openwhisprCloud": "OpenWhispr Cloud","openwhisprCloudDescription": "信頼できる精度。設定不要。",@@ -2192,6 +2200,10 @@"switchedSelfHosted": {"title": "セルフホスト","description": "独自のサーバーを使用します。"+ },+ "switchedEnterprise": {+ "title": "エンタープライズクラウドを選択しました",+ "description": "音声入力は組織が管理する文字起こしを使用します。"}},"gpuDevice": {@@ -2249,7 +2261,8 @@"info": "区間を連結するときに途切れないよう、次の区間に延長する音声の長さです。"}}- }+ },+ "meetingEnterpriseOnly": "組織はエンタープライズクラウドの文字起こしのみを許可しており、会議の録音にはまだ対応していません。"},"intelligence": {"gpuDevice": {diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex 319df3221..c7130642e 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -180,7 +180,10 @@"skip": "Pular","policyAiProcessingRestricted": "O processamento de IA está restrito pela sua organização.","policyAgentRestricted": "O uso do agente de IA está restrito pela sua organização.",- "policyTranscriptionRestricted": "A transcrição está restrita pela sua organização."+ "policyTranscriptionRestricted": "A transcrição está restrita pela sua organização.",+ "managedConfigLoading": "Verificando a configuração gerenciada da sua organização. Tente novamente em instantes.",+ "managedConfigUnavailable": "O acesso empresarial gerenciado está indisponível. Entre novamente ou entre em contato com o administrador.",+ "managedPolicyConflict": "O acesso gerenciado está bloqueado pela política do seu espaço de trabalho. Entre em contato com o administrador."},"onboarding": {"rehaul": {@@ -882,7 +885,10 @@"chunkLoss": "Um problema de rede fez perder grande parte da gravação. Retranscreva-a a partir do histórico.","agentReasoningFailed": "Seu assistente de voz não conseguiu processar o comando; a transcrição bruta foi inserida no lugar.","screenContextSkipped": "Não foi possível enviar a captura, então seu comando foi executado sem contexto de tela.",- "customEndpointInvalid": "Seu endpoint de transcrição personalizado não está configurado ou a URL é inválida. Atualize-o em Configurações → Fala para texto."+ "customEndpointInvalid": "Seu endpoint de transcrição personalizado não está configurado ou a URL é inválida. Atualize-o em Configurações → Fala para texto.",+ "managedTranscriptionUnavailable": "A transcrição gerenciada não está disponível no momento. Tente novamente em instantes.",+ "managedRouteInvalid": "A transcrição gerenciada não pôde ser iniciada devido a uma incompatibilidade de configuração. Tente novamente ou entre em contato com o administrador.",+ "managedAuthRejected": "As credenciais de transcrição gerenciada da sua organização foram rejeitadas. Entre em contato com o administrador."},"translationFallback": {"unreachableTitle": "Tradução indisponível",@@ -2146,7 +2152,9 @@"openwhisprDesc": "Resultados confiáveis. Sem configuração.","providersDesc": "Use sua própria chave API.","localDesc": "Modelos no dispositivo. Privado.",- "selfHostedDesc": "Seu servidor na sua rede."+ "selfHostedDesc": "Seu servidor na sua rede.",+ "enterprise": "Nuvem corporativa",+ "enterpriseDesc": "O áudio vai para a nuvem da sua organização."},"openwhisprCloud": "OpenWhispr Cloud","openwhisprCloudDescription": "Resultados confiáveis. Sem configuração.",@@ -2171,6 +2179,10 @@"switchedSelfHosted": {"title": "Auto-hospedado","description": "Usando seu próprio servidor."+ },+ "switchedEnterprise": {+ "title": "Nuvem corporativa selecionada",+ "description": "A ditado agora usa a transcrição gerida pela sua organização."}},"gpuDevice": {@@ -2228,7 +2240,8 @@"info": "Áudio estendido de um segmento para o próximo, evitando cortes bruscos na concatenação."}}- }+ },+ "meetingEnterpriseOnly": "A sua organização só permite transcrição em nuvem corporativa, que ainda não abrange a gravação de reuniões."},"intelligence": {"gpuDevice": {diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 0b6cb4fa6..9326320c8 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -201,7 +201,10 @@"skip": "Пропустить","policyAiProcessingRestricted": "Обработка ИИ ограничена вашей организацией.","policyAgentRestricted": "Использование ИИ-агента ограничено вашей организацией.",- "policyTranscriptionRestricted": "Транскрипция ограничена вашей организацией."+ "policyTranscriptionRestricted": "Транскрипция ограничена вашей организацией.",+ "managedConfigLoading": "Проверяется управляемая настройка вашей организации. Повторите попытку через некоторое время.",+ "managedConfigUnavailable": "Управляемый корпоративный доступ недоступен. Войдите снова или обратитесь к администратору.",+ "managedPolicyConflict": "Управляемый доступ заблокирован политикой вашего рабочего пространства. Обратитесь к администратору."},"onboarding": {"rehaul": {@@ -903,7 +906,10 @@"chunkLoss": "Из-за проблемы с сетью потеряна значительная часть записи. Повторите расшифровку из истории.","agentReasoningFailed": "Голосовой помощник не смог обработать команду — вместо этого вставлена необработанная расшифровка.","screenContextSkipped": "Снимок экрана не удалось отправить, поэтому команда выполнена без контекста экрана.",- "customEndpointInvalid": "Пользовательская конечная точка транскрипции не настроена или её URL недействителен. Обновите её в Настройках → Речь в текст."+ "customEndpointInvalid": "Пользовательская конечная точка транскрипции не настроена или её URL недействителен. Обновите её в Настройках → Речь в текст.",+ "managedTranscriptionUnavailable": "Управляемая транскрипция сейчас недоступна. Повторите попытку через некоторое время.",+ "managedRouteInvalid": "Не удалось запустить управляемую транскрипцию из-за несоответствия конфигурации. Повторите попытку или обратитесь к администратору.",+ "managedAuthRejected": "Учётные данные управляемой транскрипции вашей организации отклонены. Обратитесь к администратору."},"translationFallback": {"unreachableTitle": "Перевод недоступен",@@ -2173,7 +2179,9 @@"openwhisprDesc": "Надёжные результаты. Без настройки.","providersDesc": "Используйте свой API-ключ.","localDesc": "Модели на устройстве. Полная приватность.",- "selfHostedDesc": "Свой сервер в вашей сети."+ "selfHostedDesc": "Свой сервер в вашей сети.",+ "enterprise": "Корпоративное облако",+ "enterpriseDesc": "Аудио отправляется в собственное облако вашей организации."},"openwhisprCloud": "OpenWhispr Cloud","openwhisprCloudDescription": "Надёжные результаты. Без настройки.",@@ -2198,6 +2206,10 @@"switchedSelfHosted": {"title": "Свой сервер","description": "Используется ваш собственный сервер."+ },+ "switchedEnterprise": {+ "title": "Выбрано корпоративное облако",+ "description": "Диктовка теперь использует транскрипцию, управляемую вашей организацией."}},"gpuDevice": {@@ -2255,7 +2267,8 @@"info": "Звук, продлеваемый из одного сегмента в следующий, чтобы избежать резких обрывов при склейке."}}- }+ },+ "meetingEnterpriseOnly": "Ваша организация разрешает только корпоративную облачную транскрипцию, которая пока не поддерживает запись встреч."},"intelligence": {"gpuDevice": {diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 5c140a755..32cd4bddf 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -201,7 +201,10 @@"skip": "跳过","policyAiProcessingRestricted": "AI 处理已被您的组织限制。","policyAgentRestricted": "AI 智能体的使用已被您的组织限制。",- "policyTranscriptionRestricted": "转录已被您的组织限制。"+ "policyTranscriptionRestricted": "转录已被您的组织限制。",+ "managedConfigLoading": "正在检查您组织的托管设置。请稍候再试。",+ "managedConfigUnavailable": "托管企业访问不可用。请重新登录或联系管理员。",+ "managedPolicyConflict": "托管访问已被您工作区的策略阻止。请联系管理员。"},"onboarding": {"rehaul": {@@ -903,7 +906,10 @@"chunkLoss": "网络问题导致录音大部分丢失。请从历史记录中重新转录。","agentReasoningFailed": "语音助手无法处理该命令,已改为插入原始转录文本。","screenContextSkipped": "截图无法发送,因此已在没有屏幕上下文的情况下执行你的命令。",- "customEndpointInvalid": "自定义转写端点未配置或其 URL 无效。请在“设置 → 语音转文字”中更新。"+ "customEndpointInvalid": "自定义转写端点未配置或其 URL 无效。请在“设置 → 语音转文字”中更新。",+ "managedTranscriptionUnavailable": "托管转录目前不可用。请稍候再试。",+ "managedRouteInvalid": "由于配置不匹配,托管转录无法启动。请重试或联系管理员。",+ "managedAuthRejected": "您组织的托管转录凭证被拒绝。请联系管理员。"},"translationFallback": {"unreachableTitle": "翻译不可用",@@ -2167,7 +2173,9 @@"openwhisprDesc": "准确可靠,无需设置。","providersDesc": "使用你自己的 API Key。","localDesc": "设备端模型,完全私密。",- "selfHostedDesc": "你的服务器,在你的网络上。"+ "selfHostedDesc": "你的服务器,在你的网络上。",+ "enterprise": "企业云",+ "enterpriseDesc": "音频将发送到贵组织自己的云。"},"openwhisprCloud": "OpenWhispr Cloud","openwhisprCloudDescription": "准确可靠,无需设置。",@@ -2192,6 +2200,10 @@"switchedSelfHosted": {"title": "自托管","description": "使用你自己的服务器。"+ },+ "switchedEnterprise": {+ "title": "已选择企业云",+ "description": "听写现在使用贵组织管理的转录部署。"}},"gpuDevice": {@@ -2249,7 +2261,8 @@"info": "将每个片段延伸到下一个片段的音频量,避免拼接时出现突兀的截断。"}}- }+ },+ "meetingEnterpriseOnly": "贵组织仅允许企业云转录,暂不支持会议录音。"},"intelligence": {"gpuDevice": {diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex dc0e80199..9b0354ace 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -201,7 +201,10 @@"skip": "略過","policyAiProcessingRestricted": "AI 處理已被您的組織限制。","policyAgentRestricted": "AI 代理的使用已被您的組織限制。",- "policyTranscriptionRestricted": "轉錄已被您的組織限制。"+ "policyTranscriptionRestricted": "轉錄已被您的組織限制。",+ "managedConfigLoading": "正在檢查您組織的託管設定。請稍候再試。",+ "managedConfigUnavailable": "託管企業存取無法使用。請重新登入或聯絡管理員。",+ "managedPolicyConflict": "託管存取已被您工作區的政策封鎖。請聯絡管理員。"},"onboarding": {"rehaul": {@@ -903,7 +906,10 @@"chunkLoss": "網路問題導致錄音大部分遺失。請從歷史記錄中重新轉錄。","agentReasoningFailed": "語音助理無法處理該指令,已改為插入原始逐字稿。","screenContextSkipped": "截圖無法傳送,因此已在沒有螢幕內容的情況下執行你的指令。",- "customEndpointInvalid": "自訂轉錄端點未設定或其 URL 無效。請在「設定 → 語音轉文字」中更新。"+ "customEndpointInvalid": "自訂轉錄端點未設定或其 URL 無效。請在「設定 → 語音轉文字」中更新。",+ "managedTranscriptionUnavailable": "託管轉錄目前無法使用。請稍候再試。",+ "managedRouteInvalid": "由於設定不符,託管轉錄無法啟動。請重試或聯絡管理員。",+ "managedAuthRejected": "您組織的託管轉錄憑證遭拒。請聯絡管理員。"},"translationFallback": {"unreachableTitle": "翻譯無法使用",@@ -2167,7 +2173,9 @@"openwhisprDesc": "準確可靠,無需設定。","providersDesc": "使用你自己的 API Key。","localDesc": "裝置端模型,完全私密。",- "selfHostedDesc": "你的伺服器,在你的網路上。"+ "selfHostedDesc": "你的伺服器,在你的網路上。",+ "enterprise": "企業雲端",+ "enterpriseDesc": "音訊會傳送到貴組織自己的雲端。"},"openwhisprCloud": "OpenWhispr Cloud","openwhisprCloudDescription": "準確可靠,無需設定。",@@ -2192,6 +2200,10 @@"switchedSelfHosted": {"title": "自架主機","description": "使用你自己的伺服器。"+ },+ "switchedEnterprise": {+ "title": "已選擇企業雲端",+ "description": "聽寫現在使用貴組織管理的轉錄部署。"}},"gpuDevice": {@@ -2249,7 +2261,8 @@"info": "將每個片段延伸到下一個片段的音訊量,避免拼接時出現突兀截斷。"}}- }+ },+ "meetingEnterpriseOnly": "貴組織僅允許企業雲端轉錄,尚不支援會議錄音。"},"intelligence": {"gpuDevice": {diff --git a/src/services/EnterpriseIdentityService.ts b/src/services/EnterpriseIdentityService.tsindex b3f6a17b2..fef4d566b 100644--- a/src/services/EnterpriseIdentityService.ts+++ b/src/services/EnterpriseIdentityService.ts@@ -1,4 +1,4 @@-import type { ManagedEnterpriseConfig } from "../types/enterpriseIdentity";+import type { ManagedEnterpriseConfig, ManagedEnterpriseScope } from "../types/enterpriseIdentity";export interface ManagedEnterpriseConfigResult {success: boolean;@@ -10,6 +10,7 @@ export interface ManagedEnterpriseConfigResult {code?: string;error?: string;enforcementRequired?: boolean;+ enforcedScopes?: ManagedEnterpriseScope[];}export async function getManagedEnterpriseConfig(@@ -27,7 +28,15 @@ export async function getManagedEnterpriseConfig(error: "Managed enterprise AI requires a newer version of OpenWhispr.",};}- return request(accountId, workspaceId, authGeneration, forceRefresh);+ // The IPC boundary type carries scope names as bare strings (see+ // src/types/electron.ts); the main process only ever populates them from+ // ManagedEnterpriseScope values (see managedScopesForConfig).+ return request(+ accountId,+ workspaceId,+ authGeneration,+ forceRefresh+ ) as Promise<ManagedEnterpriseConfigResult>;}export function clearManagedEnterpriseIdentity(): void {diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.tsindex a65fac8e3..795623ff7 100644--- a/src/services/ReasoningService.ts+++ b/src/services/ReasoningService.ts@@ -148,7 +148,12 @@ class ReasoningService extends BaseReasoningService {): { model: string; provider: P; config: T; isManaged: boolean } {const inferenceScope = config.inferenceScope || fallbackScope;const managed = getManagedScopeResolution(inferenceScope, getSettings().enterpriseSetupMode);- if (managed.kind === "error") throw new Error(managed.message);+ if (managed.kind === "error") {+ throw Object.assign(new Error(managed.message), {+ code: managed.code,+ messageKey: managed.messageKey,+ });+ }if (managed.kind !== "managed") {return { model, provider, config: { ...config, inferenceScope }, isManaged: false };}diff --git a/src/services/ai/enterpriseSettings.ts b/src/services/ai/enterpriseSettings.tsindex c15f5f126..4284fb7d4 100644--- a/src/services/ai/enterpriseSettings.ts+++ b/src/services/ai/enterpriseSettings.ts@@ -29,7 +29,10 @@ export function getEnterpriseCallSettings(const managedState = useEnterpriseIdentityStore.getState();const resolution = getManagedScopeResolution(inferenceScope, s.enterpriseSetupMode);if (resolution.kind === "error") {- throw Object.assign(new Error(resolution.message), { code: resolution.code });+ throw Object.assign(new Error(resolution.message), {+ code: resolution.code,+ messageKey: resolution.messageKey,+ });}const managedContext =resolution.kind === "managed" &&diff --git a/src/services/fileTranscription.ts b/src/services/fileTranscription.tsindex 1820e46cf..dfd778624 100644--- a/src/services/fileTranscription.ts+++ b/src/services/fileTranscription.ts@@ -1,5 +1,9 @@import { withSessionRefresh } from "../lib/auth";import { resolveTranscriptionRoute } from "../helpers/transcriptionRoute";+import {+ getManagedTranscriptionResolution,+ isManagedTranscriptionActive,+} from "./managedTranscription";import { getTranscriptionProviders } from "../models/ModelRegistry";import type { LocalTranscriptionProvider } from "../types/electron";@@ -8,6 +12,7 @@ export interface FileTranscriptionResult {text?: string;error?: string;code?: string;+ messageKey?: string;diarized?: boolean;// The transcript succeeded, but requested speaker labels could not be applied.diarizationWarning?: boolean;@@ -88,7 +93,19 @@ export async function transcribeFile(diarize: boolean,opts: { requestId?: string; timestamps?: boolean } = {}): Promise<FileTranscriptionResult> {- if (cfg.isOpenWhisprCloud) {+ // Managed enterprise STT outranks every personal lane, OpenWhispr Cloud and+ // local included: under managed_required no audio may leave the tenant.+ const managed = getManagedTranscriptionResolution();+ if (managed?.kind === "error") {+ return {+ success: false,+ error: managed.message,+ code: managed.code,+ messageKey: managed.messageKey,+ };+ }++ if (!managed && cfg.isOpenWhisprCloud) {return withSessionRefresh(async () => {const r = await window.electronAPI.transcribeAudioFileCloud!(filePath, opts);if (!r.success && r.code) {@@ -100,7 +117,7 @@ export async function transcribeFile(});}- if (cfg.useLocalWhisper) {+ if (!managed && cfg.useLocalWhisper) {const provider = cfg.localTranscriptionProvider as LocalTranscriptionProvider;return window.electronAPI.transcribeAudioFile(filePath, {provider,@@ -133,16 +150,23 @@ export async function transcribeFile(cortiTenant: cfg.cortiTenant,},providers: getTranscriptionProviders(),+ managed,request: { effectiveLanguage: cfg.language || undefined },});if (route.transport === "error") {- return { success: false, error: route.message, code: route.code };+ return {+ success: false,+ error: route.message,+ code: route.code,+ messageKey: route.messageKey,+ };}// Self-hosted fields make the handler route to the configured server// (fail-closed on misconfiguration) instead of stale BYOK settings.return window.electronAPI.transcribeAudioFileByok!({filePath,+ managed: managed?.kind === "managed" ? managed : undefined,apiKey: cfg.getApiKey(),baseUrl: cfg.cloudTranscriptionBaseUrl,model: cfg.cloudTranscriptionModel,@@ -165,6 +189,7 @@ export function shouldUseByokDiarize(cfg: FileTranscriptionConfig,diarizationEnabled: boolean): boolean {+ if (isManagedTranscriptionActive()) return false;return (diarizationEnabled &&!cfg.useLocalWhisper &&diff --git a/src/services/managedTranscription.ts b/src/services/managedTranscription.tsnew file mode 100644index 000000000..fdd6cd30d--- /dev/null+++ b/src/services/managedTranscription.ts@@ -0,0 +1,64 @@+import { getSettings } from "../stores/settingsStore";+import type { ManagedTranscriptionResolution } from "../helpers/transcriptionRoute";+import {+ getManagedScopeResolution,+ useEnterpriseIdentityStore,+} from "../stores/enterpriseIdentityStore";++/**+ * True when managed STT resolves for this user. Dictation gates OR this with+ * the personal-selection policy check: a policy that only allows the+ * enterprise mode blocks every personal setting, yet dictation must proceed+ * through the managed route.+ */+export function isManagedTranscriptionActive(): boolean {+ return getManagedTranscriptionResolution()?.kind === "managed";+}++/**+ * Managed enterprise STT outcome for the current user, as a+ * `TranscriptionRouteInput.managed` value. Undefined means no managed+ * transcription applies and personal routing proceeds; the context mirrors+ * `getEnterpriseCallSettings` so the main process can re-validate it.+ */+export function getManagedTranscriptionResolution(): ManagedTranscriptionResolution | undefined {+ const settings = getSettings();+ const state = useEnterpriseIdentityStore.getState();+ const resolution = getManagedScopeResolution(+ "transcription",+ settings.enterpriseTranscriptionSetupMode+ );+ if (resolution.kind === "error") {+ return {+ kind: "error",+ message: resolution.message,+ code: resolution.code,+ messageKey: resolution.messageKey,+ };+ }+ if (+ resolution.kind !== "managed" ||+ resolution.provider !== "azure" ||+ !state.config ||+ !state.accountId ||+ !state.workspaceId ||+ state.authGeneration == null+ ) {+ return undefined;+ }+ return {+ kind: "managed",+ provider: "azure",+ deployment: resolution.model,+ context: {+ accountId: state.accountId,+ workspaceId: state.workspaceId,+ authGeneration: state.authGeneration,+ setupMode: settings.enterpriseTranscriptionSetupMode,+ inferenceScope: "transcription",+ provider: "azure",+ generation: state.config.generation,+ providerVersion: resolution.record.version,+ },+ };+}diff --git a/src/stores/batchQueueStore.ts b/src/stores/batchQueueStore.tsindex b123a9e28..c7e07c0f4 100644--- a/src/stores/batchQueueStore.ts+++ b/src/stores/batchQueueStore.ts@@ -1,4 +1,5 @@import { create } from "zustand";+import i18n from "../i18n";import { transcribeFileWithSpeakers } from "../services/fileTranscription";import type { FileTranscriptionConfig, DiarizationSettings } from "../services/fileTranscription";import { DOWNLOAD_ERROR_KEYS, transcriptionErrorKey } from "../components/notes/shared";@@ -6,6 +7,7 @@ import { saveUploadNote, uploadTitleFallback } from "../services/uploadNotes";import { getSettings } from "./settingsStore";import { isTranscriptionContextAllowed } from "./policyRules";import { usePolicyStore } from "./policyStore";+import { isManagedTranscriptionActive } from "../services/managedTranscription";export type QueueItemStatus = "queued" | "downloading" | "transcribing" | "done" | "error";@@ -122,7 +124,11 @@ export function processBatchQueue(diarization: DiarizationSettings): void {if (useBatchQueueStore.getState().isProcessing) return;- if (!isTranscriptionContextAllowed(usePolicyStore.getState(), getSettings(), "upload")) return;+ if (+ !isManagedTranscriptionActive() &&+ !isTranscriptionContextAllowed(usePolicyStore.getState(), getSettings(), "upload")+ )+ return;const run = ++runId;useBatchQueueStore.setState({ isProcessing: true });@@ -213,6 +219,7 @@ export function processBatchQueue(status: "error",error:transcriptionErrorKey(transcriptionResult) ||+ (transcriptionResult.messageKey ? i18n.t(transcriptionResult.messageKey) : undefined) ||transcriptionResult.error ||"batchTranscriptionFailed",});diff --git a/src/stores/enterpriseIdentityStore.ts b/src/stores/enterpriseIdentityStore.tsindex 69bb10c05..eefa7d51a 100644--- a/src/stores/enterpriseIdentityStore.ts+++ b/src/stores/enterpriseIdentityStore.ts@@ -6,12 +6,15 @@ import {import type {EnterpriseSetupMode,ManagedEnterpriseConfig,+ ManagedEnterpriseScope,ManagedEnterpriseScopeResolution,} from "../types/enterpriseIdentity";-import type { InferenceScope } from "../config/inferenceScopes";import logger from "../utils/logger";-import { resolveManagedEnterpriseScope } from "../helpers/enterpriseManagedConfig.mjs";-import { isLlmSelectionAllowed } from "./policyRules";+import {+ resolveManagedEnterpriseScope,+ managedScopesForConfig,+} from "../helpers/enterpriseManagedConfig.mjs";+import { isLlmSelectionAllowed, isTranscriptionSelectionAllowed } from "./policyRules";import { usePolicyStore } from "./policyStore";interface EnterpriseIdentityState {@@ -21,7 +24,8 @@ interface EnterpriseIdentityState {status: "idle" | "loading" | "ready" | "error";config: ManagedEnterpriseConfig | null;error: string | null;- failClosed: boolean;+ managedScopes: ManagedEnterpriseScope[];+ enforcedScopes: ManagedEnterpriseScope[];refresh: (accountId: string,workspaceId: string,@@ -31,6 +35,51 @@ interface EnterpriseIdentityState {clear: () => void;}+type ScopeSummary = { managed: ManagedEnterpriseScope[]; enforced: ManagedEnterpriseScope[] };+const EMPTY_SCOPES: ScopeSummary = { managed: [], enforced: [] };++function scopeStorageKey(accountId: string | null, workspaceId: string | null): string | null {+ return accountId && workspaceId ? `managedEnterpriseScopes:${accountId}:${workspaceId}` : null;+}++function readPersistedScopes(accountId: string | null, workspaceId: string | null): ScopeSummary {+ const key = scopeStorageKey(accountId, workspaceId);+ if (!key || typeof localStorage === "undefined") return EMPTY_SCOPES;+ try {+ const parsed = JSON.parse(localStorage.getItem(key) ?? "null");+ return Array.isArray(parsed?.managed) && Array.isArray(parsed?.enforced)+ ? parsed+ : EMPTY_SCOPES;+ } catch {+ return EMPTY_SCOPES;+ }+}++function persistScopes(accountId: string, workspaceId: string, summary: ScopeSummary): void {+ const key = scopeStorageKey(accountId, workspaceId);+ if (!key || typeof localStorage === "undefined") return;+ try {+ localStorage.setItem(key, JSON.stringify(summary));+ } catch {+ // Storage is a cold-start hint only.+ }+}++function summarize(config: ManagedEnterpriseConfig | null): ScopeSummary {+ return managedScopesForConfig(config) as ScopeSummary;+}++/** Scopes that must fail closed when the config is gone: the main process's list, else the last known one. */+function enforcedScopesOnError(+ reported: unknown,+ enforcementRequired: boolean | undefined,+ lastKnown: ScopeSummary+): ManagedEnterpriseScope[] {+ if (Array.isArray(reported)) return reported as ManagedEnterpriseScope[];+ if (enforcementRequired === false) return [];+ return lastKnown.enforced;+}+let requestSequence = 0;let inFlightKey: string | null = null;let inFlightPromise: Promise<void> | null = null;@@ -43,7 +92,8 @@ export const useEnterpriseIdentityStore = create<EnterpriseIdentityState>((set,status: "idle",config: null,error: null,- failClosed: false,+ managedScopes: [],+ enforcedScopes: [],refresh: (accountId, workspaceId, authGeneration, forceRefresh = false) => {ensureLifecycleListeners();@@ -62,7 +112,8 @@ export const useEnterpriseIdentityStore = create<EnterpriseIdentityState>((set,status: sameIdentity && current.config ? "ready" : "loading",config: sameIdentity ? current.config : null,error: null,- failClosed: sameIdentity ? current.failClosed : false,+ managedScopes: sameIdentity ? current.managedScopes : [],+ enforcedScopes: sameIdentity ? current.enforcedScopes : [],});const promise = (async () => {@@ -82,14 +133,20 @@ export const useEnterpriseIdentityStore = create<EnterpriseIdentityState>((set,) {throw Object.assign(new Error(result.error || "Managed enterprise AI configuration is unavailable."),- { enforcementRequired: result.enforcementRequired }+ {+ enforcementRequired: result.enforcementRequired,+ enforcedScopes: result.enforcedScopes,+ });}+ const summary = summarize(result.config ?? null);+ persistScopes(accountId, workspaceId, summary);set({status: "ready",config: result.config ?? null,error: null,- failClosed: false,+ managedScopes: summary.managed,+ enforcedScopes: [],});} catch (error) {if (sequence !== requestSequence) return;@@ -97,21 +154,19 @@ export const useEnterpriseIdentityStore = create<EnterpriseIdentityState>((set,const enforcementRequired = (error as { enforcementRequired?: boolean }).enforcementRequired;logger.warn("Managed enterprise AI configuration unavailable", { error: message }, "auth");+ const lastKnown = current.config+ ? summarize(current.config)+ : readPersistedScopes(accountId, workspaceId);set({status: "error",config: null,error: message,- failClosed:- typeof enforcementRequired === "boolean"- ? enforcementRequired- : current.failClosed ||- Boolean(- current.config?.providers.some(- (record) =>- record.mode !== "disabled" &&- (record.mode === "managed_required" || !record.allowManualSetup)- )- ),+ managedScopes: lastKnown.managed,+ enforcedScopes: enforcedScopesOnError(+ (error as { enforcedScopes?: unknown }).enforcedScopes,+ enforcementRequired,+ lastKnown+ ),});} finally {if (inFlightKey === key) {@@ -137,7 +192,8 @@ export const useEnterpriseIdentityStore = create<EnterpriseIdentityState>((set,status: "idle",config: null,error: null,- failClosed: false,+ managedScopes: [],+ enforcedScopes: [],});},}));@@ -168,22 +224,33 @@ function ensureLifecycleListeners(): void {}const currentGeneration = state.config?.generation ?? -1;if (snapshot.config && snapshot.config.generation < currentGeneration) return;+ if (snapshot.config) {+ const summary = summarize(snapshot.config);+ if (state.accountId && state.workspaceId) {+ persistScopes(state.accountId, state.workspaceId, summary);+ }+ useEnterpriseIdentityStore.setState({+ status: "ready",+ config: snapshot.config,+ error: null,+ managedScopes: summary.managed,+ enforcedScopes: [],+ });+ return;+ }+ const lastKnown = state.config+ ? summarize(state.config)+ : readPersistedScopes(state.accountId, state.workspaceId);useEnterpriseIdentityStore.setState({- status: snapshot.config ? "ready" : "error",- config: snapshot.config,- error: snapshot.config ? null : snapshot.code,- failClosed: snapshot.config- ? false- : typeof snapshot.enforcementRequired === "boolean"- ? snapshot.enforcementRequired- : state.failClosed ||- Boolean(- state.config?.providers.some(- (record) =>- record.mode !== "disabled" &&- (record.mode === "managed_required" || !record.allowManualSetup)- )- ),+ status: "error",+ config: null,+ error: snapshot.code,+ managedScopes: lastKnown.managed,+ enforcedScopes: enforcedScopesOnError(+ snapshot.enforcedScopes,+ snapshot.enforcementRequired,+ lastKnown+ ),});});}@@ -191,23 +258,43 @@ function ensureLifecycleListeners(): void {// The vision override is the dictation agent's image lane; it has no managed// scope of its own (enterprise envelopes predate it), so managed resolution// follows the agent scope instead of failing as an unknown scope.-const MANAGED_SCOPE_ALIASES: Partial<Record<InferenceScope, InferenceScope>> = {+const MANAGED_SCOPE_ALIASES: Partial<Record<ManagedEnterpriseScope, ManagedEnterpriseScope>> = {dictationAgentVision: "dictationAgent",};+function isManagedSelectionAllowedByPolicy(+ scope: ManagedEnterpriseScope,+ provider: string+): boolean {+ const policy = usePolicyStore.getState();+ const selection = { mode: "enterprise" as const, provider };+ return scope === "transcription"+ ? isTranscriptionSelectionAllowed(policy, selection)+ : isLlmSelectionAllowed(policy, selection);+}+function resolveScope(config: ManagedEnterpriseConfig | null,- requestedScope: InferenceScope,+ requestedScope: ManagedEnterpriseScope,setupMode: EnterpriseSetupMode,- failClosed: boolean+ scopeHold: false | "unavailable" | "loading"): ManagedEnterpriseScopeResolution {const scope = MANAGED_SCOPE_ALIASES[requestedScope] ?? requestedScope;- if (!config && failClosed) {- return {- kind: "error",- code: "MANAGED_CONFIG_UNAVAILABLE",- message: "Managed enterprise access is unavailable. Sign in with company SSO or contact IT.",- };+ if (!config && scopeHold) {+ return scopeHold === "loading"+ ? {+ kind: "error",+ code: "MANAGED_CONFIG_LOADING",+ message: "Checking your organization's managed setup. Try again in a moment.",+ messageKey: "common.managedConfigLoading",+ }+ : {+ kind: "error",+ code: "MANAGED_CONFIG_UNAVAILABLE",+ message:+ "Managed enterprise access is unavailable. Sign in again or contact your IT administrator.",+ messageKey: "common.managedConfigUnavailable",+ };}const resolution = resolveManagedEnterpriseScope(config,@@ -216,10 +303,7 @@ function resolveScope() as ManagedEnterpriseScopeResolution;if (resolution.kind === "managed" &&- !isLlmSelectionAllowed(usePolicyStore.getState(), {- mode: "enterprise",- provider: resolution.provider,- })+ !isManagedSelectionAllowedByPolicy(scope, resolution.provider)) {const required = resolution.mode === "managed_required" || !resolution.allowManualSetup;logger.warn("Managed enterprise provider is blocked by workspace policy", {@@ -233,34 +317,68 @@ function resolveScope(code: "PROVIDER_POLICY_CONFLICT",message:"Managed access is blocked by your workspace policy. Contact your IT administrator.",+ messageKey: "common.managedPolicyConflict",}: { kind: "manual" };}return resolution;}+/**+ * Per-scope fail-closed decision. `"loading"` only while the first fetch for+ * this identity is still pending and the last-known config enforced the+ * scope; `"unavailable"` once the config is confirmed gone (error) and either+ * the main process reported this scope enforced or, in managed setup mode,+ * the scope was ever managed for this workspace. Otherwise `false`, so an+ * unrelated scope (e.g. transcription on an LLM-only workspace) never fails+ * closed just because another scope's config outage occurred.+ */+function scopeFailsClosed(+ state: Pick<+ EnterpriseIdentityState,+ "status" | "config" | "accountId" | "workspaceId" | "managedScopes" | "enforcedScopes"+ >,+ requestedScope: ManagedEnterpriseScope,+ setupMode: EnterpriseSetupMode+): false | "unavailable" | "loading" {+ const scope = MANAGED_SCOPE_ALIASES[requestedScope] ?? requestedScope;+ if ((state.status === "idle" || state.status === "loading") && !state.config) {+ // Covers both the very first fetch for an identity ("idle", right after+ // app start or a workspace switch, before refresh() has even been+ // called) and a retry after an error ("loading" with in-memory+ // enforcement carried forward). Prefer that in-memory enforcement; fall+ // back to the persisted cold-start hint only when nothing was carried+ // forward yet. After clear() there is no accountId/workspaceId, so the+ // hint lookup finds nothing and a signed-out user is never held.+ const enforced = state.enforcedScopes.length+ ? state.enforcedScopes+ : readPersistedScopes(state.accountId, state.workspaceId).enforced;+ return enforced.includes(scope) ? "loading" : false;+ }+ if (state.enforcedScopes.includes(scope)) return "unavailable";+ if (setupMode === "managed" && state.status === "error" && state.managedScopes.includes(scope)) {+ return "unavailable";+ }+ return false;+}+/** Imperative reads (services, stores). Components should use useManagedScopeResolution. */export function getManagedScopeResolution(- scope: InferenceScope,+ scope: ManagedEnterpriseScope,setupMode: EnterpriseSetupMode): ManagedEnterpriseScopeResolution {const state = useEnterpriseIdentityStore.getState();- return resolveScope(- state.config,- scope,- setupMode,- state.failClosed || (setupMode === "managed" && state.status === "error")- );+ return resolveScope(state.config, scope, setupMode, scopeFailsClosed(state, scope, setupMode));}/** Subscribes to the managed config so the UI re-renders when an administrator changes it. */export function useManagedScopeResolution(- scope: InferenceScope,+ scope: ManagedEnterpriseScope,setupMode: EnterpriseSetupMode): ManagedEnterpriseScopeResolution {const config = useEnterpriseIdentityStore((state) => state.config);- const failClosed = useEnterpriseIdentityStore(- (state) => state.failClosed || (setupMode === "managed" && state.status === "error")+ const scopeHold = useEnterpriseIdentityStore((state) =>+ scopeFailsClosed(state, scope, setupMode));- return resolveScope(config, scope, setupMode, failClosed);+ return resolveScope(config, scope, setupMode, scopeHold);}diff --git a/src/stores/policyRules.ts b/src/stores/policyRules.tsindex f947f6bde..ca18411f3 100644--- a/src/stores/policyRules.ts+++ b/src/stores/policyRules.ts@@ -103,6 +103,33 @@ export function isEnterpriseProviderAllowed();}+/**+ * Whether an enterprise cloud may run managed transcription. The field is+ * absent on servers that predate it; absent means none.+ */+export function isTranscriptionEnterpriseProviderAllowed(+ state: PolicyDecisionSnapshot,+ providerId: string+): boolean {+ return managedPolicyDecision(state, (policy) =>+ (policy.transcription.allowedEnterpriseProviders ?? []).includes(providerId)+ );+}++/**+ * Whether the "Enterprise cloud" transcription tile should ever be shown as+ * a selectable option. Unlike every other mode, "enterprise" can only ever+ * resolve for a managed org — resolveEffectivePolicySelection requires a+ * managed policy with a matching allowedEnterpriseProviders entry. Offering+ * the tile to an unmanaged/idle user would let them pick a mode with no+ * personal configuration surface and no managed resolution, which then+ * fails every dictation and upload closed via the transcription route's+ * fail-closed guard.+ */+export function isEnterpriseTranscriptionOfferable(state: PolicyDecisionSnapshot): boolean {+ return state.status === "managed";+}+/** Whether the AI agent (dictation, voice, and chat) is allowed. */export function isAgentAllowed(state: PolicyDecisionSnapshot): boolean {return managedPolicyDecision(state, (policy) => policy.features.agentEnabled);@@ -205,13 +232,13 @@ export function resolveEffectivePolicySelection(policy[scope].allowedByokProviders.includes(provider));const allowedEnterpriseProviders = (catalog.enterpriseProviders ?? []).filter((provider) =>- policy.llm.allowedEnterpriseProviders.includes(provider)+ (policy[scope].allowedEnterpriseProviders ?? []).includes(provider));const modeIsUsable = (mode: InferenceMode): boolean => {if (!catalog.modes.includes(mode)) return false;if (!policy[scope].allowedModes.includes(mode)) return false;if (mode === "providers") return allowedByokProviders.length > 0;- if (mode === "enterprise") return scope === "llm" && allowedEnterpriseProviders.length > 0;+ if (mode === "enterprise") return allowedEnterpriseProviders.length > 0;return true;};@@ -263,8 +290,13 @@ export function isTranscriptionSelectionAllowed(selection: TranscriptionSelection): boolean {if (!isModeAllowedByPolicy(state, "transcription", selection.mode)) return false;- if (selection.mode !== "providers") return true;- return isProviderAllowedByPolicy(state, "transcription", selection.provider);+ if (selection.mode === "providers") {+ return isProviderAllowedByPolicy(state, "transcription", selection.provider);+ }+ if (selection.mode === "enterprise") {+ return isTranscriptionEnterpriseProviderAllowed(state, selection.provider);+ }+ return true;}export type TranscriptionPolicyContext = "dictation" | "meeting" | "upload";@@ -394,13 +426,10 @@ function policyModeHasAvailableProvider(: policy[scope].allowedByokProviders.length > 0;}if (mode === "enterprise") {- const selectableProviders = providerCatalog?.enterpriseProviders ?? ["bedrock"];- return (- scope === "llm" &&- selectableProviders.some((provider) =>- policy.llm.allowedEnterpriseProviders.includes(provider)- )- );+ const allowed = policy[scope].allowedEnterpriseProviders ?? [];+ const selectable =+ providerCatalog?.enterpriseProviders ?? (scope === "llm" ? ["bedrock"] : ["azure"]);+ return selectable.some((provider) => allowed.includes(provider));}return true;}diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex db5adb041..a122aadf1 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -79,9 +79,13 @@ export const LLM_POLICY_PROVIDER_IDS = [// Azure and Vertex remain intentionally unavailable in the desktop picker.export const LLM_ENTERPRISE_POLICY_PROVIDER_IDS = ["bedrock"] as const;+// Managed transcription is Azure-only in this phase.+export const TRANSCRIPTION_ENTERPRISE_POLICY_PROVIDER_IDS = ["azure"] as const;+const TRANSCRIPTION_POLICY_CATALOG = {- modes: ["openwhispr", "providers", "local", "self-hosted"] as const,+ modes: ["openwhispr", "providers", "local", "self-hosted", "enterprise"] as const,byokProviders: TRANSCRIPTION_POLICY_PROVIDER_IDS,+ enterpriseProviders: TRANSCRIPTION_ENTERPRISE_POLICY_PROVIDER_IDS,};const MEETING_TRANSCRIPTION_POLICY_CATALOG = {@@ -906,6 +910,7 @@ export interface SettingsState// Enterprise providersenterpriseSetupMode: EnterpriseSetupMode;+ enterpriseTranscriptionSetupMode: EnterpriseSetupMode;bedrockAuthMode: string;bedrockRegion: string;bedrockProfile: string;@@ -922,6 +927,7 @@ export interface SettingsStatevertexApiKey: string;setBedrockAuthMode: (value: string) => void;setEnterpriseSetupMode: (value: EnterpriseSetupMode) => void;+ setEnterpriseTranscriptionSetupMode: (value: EnterpriseSetupMode) => void;setBedrockRegion: (value: string) => void;setBedrockProfile: (value: string) => void;setBedrockAccessKeyId: (key: string) => void;@@ -1314,6 +1320,11 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({if (v === "auto" || v === "managed" || v === "manual") return v;return "auto" as EnterpriseSetupMode;})(),+ enterpriseTranscriptionSetupMode: (() => {+ const v = readString("enterpriseTranscriptionSetupMode", "auto");+ if (v === "auto" || v === "managed" || v === "manual") return v;+ return "auto" as EnterpriseSetupMode;+ })(),bedrockAuthMode: readString("bedrockAuthMode", "sso"),bedrockRegion: readString("bedrockRegion", "us-east-1"),bedrockProfile: readString("bedrockProfile", ""),@@ -1955,6 +1966,9 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({setEnterpriseSetupMode: createStringSetter("enterpriseSetupMode") as (value: EnterpriseSetupMode) => void,+ setEnterpriseTranscriptionSetupMode: createStringSetter("enterpriseTranscriptionSetupMode") as (+ value: EnterpriseSetupMode+ ) => void,setBedrockAuthMode: (value: string) => {if (isBrowser) localStorage.setItem("bedrockAuthMode", value);set({ bedrockAuthMode: value });@@ -2789,6 +2803,11 @@ export function selectPolicyEffectiveSettings(// as user authorization to send content there.writable[keys.baseUrl] = "";}+ } else if (selection.mode === "enterprise") {+ // The managed deployment/endpoint is resolved separately by+ // enterpriseIdentityStore; the provider id here only needs to satisfy+ // the policy gate (isTranscriptionContextAllowed).+ writable[keys.provider] = selection.provider;}}diff --git a/src/stores/workspaceStore.ts b/src/stores/workspaceStore.tsindex 87154cfea..67b482099 100644--- a/src/stores/workspaceStore.ts+++ b/src/stores/workspaceStore.ts@@ -20,7 +20,8 @@ interface WorkspaceState {refreshMembers: (workspaceId: string) => Promise<void>;}-const ACTIVE_WORKSPACE_KEY = "activeWorkspaceId";+// Shared by every window of this origin; the dictation window mirrors it (lib/accountScopeMirror).+export const ACTIVE_WORKSPACE_KEY = "activeWorkspaceId";function readActiveWorkspaceId(): string | null {if (typeof window === "undefined") return null;diff --git a/src/types/electron.ts b/src/types/electron.tsindex 79433f2fd..168f8f6eb 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -2,7 +2,10 @@ import type { ModelDefinition } from "../models/ModelRegistry";import type { TinfoilCatalogModel } from "../models/tinfoilModels";import type { UsageResponse } from "../lib/usageStore";import type { OrgPolicy } from "./policy";-import type { ManagedEnterpriseConfig } from "./enterpriseIdentity";+import type {+ ManagedEnterpriseConfig,+ ManagedEnterpriseRequestContext,+} from "./enterpriseIdentity";import type { CalendarAvailabilityRequest, CalendarAvailabilityResult } from "./calendar";export type LocalTranscriptionProvider = "whisper" | "nvidia" | "cohere";@@ -132,6 +135,12 @@ export interface AuthTokenMutationResult extends AuthTokenState {code?: string;}+/** The validated account scope the main process holds, as seen by any window. */+export interface ActiveAccountScope {+ accountId: string;+ authGeneration: number;+}+export interface TranscriptionItem {id: number;text: string;@@ -1212,12 +1221,19 @@ declare global {remoteTranscriptionType?: SelfHostedType;remoteTranscriptionUrl?: string;remoteTranscriptionModel?: string;+ managed?: {+ kind: "managed";+ provider: "azure";+ deployment: string;+ context: ManagedEnterpriseRequestContext;+ };}) => Promise<{success: boolean;transcription?: TranscriptionItem;error?: string;code?: TranscriptionErrorCode;+ messageKey?: string;}>;updateTranscriptionText: (id: number,@@ -1343,6 +1359,10 @@ declare global {accountId: string | null,expectedAuthGeneration?: number) => Promise<{ success: boolean; code?: string; error?: string }>;+ getActiveAccountScope?: () => Promise<ActiveAccountScope | null>;+ onActiveAccountScopeChanged?: (+ callback: (scope: ActiveAccountScope | null) => void+ ) => () => void;deleteAccountData?: (accountId: string,expectedAuthGeneration: number@@ -2013,6 +2033,7 @@ declare global {code?: string;error?: string;enforcementRequired?: boolean;+ enforcedScopes?: string[];}>;onManagedEnterpriseConfigChanged?: (callback: (snapshot: {@@ -2022,9 +2043,18 @@ declare global {config: ManagedEnterpriseConfig | null;code: string | null;enforcementRequired?: boolean;+ enforcedScopes?: string[];}) => void) => () => void;clearManagedEnterpriseIdentity?: () => Promise<void>;+ managedTranscribe?: (data: {+ audioBuffer: ArrayBuffer;+ fileName: string;+ mimeType: string;+ language?: string;+ prompt?: string;+ managed: { provider: "azure"; context: ManagedEnterpriseRequestContext };+ }) => Promise<{ text?: string; error?: string; code?: string; messageKey?: string }>;// Dictation key persistence (file-based for reliable startup)getDictationKey?: () => Promise<string | null>;@@ -2307,6 +2337,12 @@ declare global {transcriptionMode?: string;remoteTranscriptionUrl?: string;remoteTranscriptionModel?: string;+ managed?: {+ kind: "managed";+ provider: "azure";+ deployment: string;+ context: ManagedEnterpriseRequestContext;+ };}) => Promise<{success: boolean;text?: string;diff --git a/src/types/enterpriseIdentity.ts b/src/types/enterpriseIdentity.tsindex 61e33585d..c3cecaabf 100644--- a/src/types/enterpriseIdentity.ts+++ b/src/types/enterpriseIdentity.ts@@ -4,12 +4,17 @@ export type ManagedEnterpriseProvider = "bedrock" | "azure";export type ManagedEnterpriseProviderMode = "disabled" | "managed_default" | "managed_required";export type EnterpriseSetupMode = "auto" | "managed" | "manual";+/** The managed speech-to-text scope; resolved from the Azure `transcription` config section. */+export type ManagedTranscriptionScope = "transcription";+export type ManagedEnterpriseScope = InferenceScope | ManagedTranscriptionScope;+export interface ManagedEnterpriseProviderRecord {provider: ManagedEnterpriseProvider;mode: ManagedEnterpriseProviderMode;allowManualSetup: boolean;config: {- scopeDefaults: Partial<Record<InferenceScope, string>>;+ /** Present when the text-processing section is configured. */+ scopeDefaults?: Partial<Record<InferenceScope, string>>;roleArn?: string;region?: string;allowedModels?: string[];@@ -18,6 +23,11 @@ export interface ManagedEnterpriseProviderRecord {endpoint?: string;apiVersion?: string;allowedDeployments?: string[];+ /** Azure-only managed speech-to-text section. */+ transcription?: {+ allowedDeployments: string[];+ defaultDeployment: string;+ };};version: number;updatedAt: string;@@ -49,14 +59,14 @@ export type ManagedEnterpriseScopeResolution =allowManualSetup: boolean;record: ManagedEnterpriseProviderRecord;}- | { kind: "error"; code: string; message: string };+ | { kind: "error"; code: string; message: string; messageKey?: string };export interface ManagedEnterpriseRequestContext {accountId: string;workspaceId: string;authGeneration: number;setupMode: EnterpriseSetupMode;- inferenceScope: InferenceScope;+ inferenceScope: ManagedEnterpriseScope;provider: ManagedEnterpriseProvider;generation: number;providerVersion: number;diff --git a/src/types/policy.ts b/src/types/policy.tsindex 15faebbef..51d7c7c2c 100644--- a/src/types/policy.ts+++ b/src/types/policy.ts@@ -16,6 +16,8 @@ export interface OrgPolicy {transcription: {allowedModes: InferenceMode[];allowedByokProviders: string[];+ /** Absent on servers that predate the field; absent means none. */+ allowedEnterpriseProviders?: string[];};llm: {allowedModes: InferenceMode[];diff --git a/src/utils/urlUtils.ts b/src/utils/urlUtils.tsindex 2feeff306..4dd63984b 100644--- a/src/utils/urlUtils.ts+++ b/src/utils/urlUtils.ts@@ -114,3 +114,27 @@ export function buildAzureTranscriptionUrl(return null;}}++// Workload-identity (managed) Azure STT. Only the deployments route serves a+// transcription deployment: `/openai/v1/audio/transcriptions?api-version=preview`+// answers 404 DeploymentNotFound, and the deployments route rejects the+// v1-surface aliases ("v1", "preview") outright — so those aliases are+// translated to the dated version that is known to serve audio. Dated versions+// pass through unchanged.+export function buildManagedAzureTranscriptionUrl(+ endpoint: string,+ deployment: string,+ apiVersion: string+): string | null {+ let origin: string;+ try {+ origin = new URL(endpoint).origin;+ } catch {+ return null;+ }+ const version =+ apiVersion === "v1" || apiVersion === "preview"+ ? DEFAULT_AZURE_TRANSCRIPTION_API_VERSION+ : apiVersion;+ return buildAzureTranscriptionUrl(origin, deployment, version);+}diff --git a/test/helpers/accountScopeBinding.test.js b/test/helpers/accountScopeBinding.test.jsindex 9fb0c8a1e..b3303dfbb 100644--- a/test/helpers/accountScopeBinding.test.js+++ b/test/helpers/accountScopeBinding.test.js@@ -130,3 +130,19 @@ test("clear removes the binding and read tolerates absence and corruption", (t)assert.equal(binding.read(), null);binding.clear();});++test("resolveActiveAccountScope pairs the restorable account with the current credential generation", () => {+ const valid = { version: 1, accountId: "account-a", tokenHash: sha256("token-a") };+ assert.deepEqual(+ binding.resolveActiveAccountScope({ token: "token-a", generation: 3, binding: valid }),+ { accountId: "account-a", authGeneration: 3 }+ );+ assert.equal(+ binding.resolveActiveAccountScope({ token: "rotated-token", generation: 4, binding: valid }),+ null+ );+ assert.equal(+ binding.resolveActiveAccountScope({ token: null, generation: 4, binding: null }),+ null+ );+});diff --git a/test/helpers/accountScopeIpc.test.js b/test/helpers/accountScopeIpc.test.jsnew file mode 100644index 000000000..540452e3a--- /dev/null+++ b/test/helpers/accountScopeIpc.test.js@@ -0,0 +1,150 @@+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 Module = require("node:module");++const handlersModulePath = require.resolve("../../src/helpers/ipcHandlers");+const originalLoad = Module._load;++// Registers the real handler closures against a fake `this` (the scaffolding+// from agentDictationPillIpc.test.js) with the bearer state under test control+// and the binding file in a temporary userData directory, so the scope+// handlers run against the real accountScopeBinding.+const handlers = new Map();+const broadcasts = [];+const userDataDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "account-scope-ipc-"));+let tokenState = { token: null, generation: 0 };++const electronStub = {+ app: {+ getPath: () => userDataDirectory,+ getName: () => "test",+ getVersion: () => "0.0.0",+ isPackaged: false,+ on: () => {},+ requestSingleInstanceLock: () => true,+ },+ ipcMain: {+ handle: (channel, fn) => handlers.set(channel, fn),+ on: () => {},+ removeHandler: () => {},+ },+ net: {+ fetch: async () => ({+ ok: true,+ status: 200,+ json: async () => ({}),+ text: async () => "{}",+ }),+ },+ BrowserWindow: class BrowserWindow {+ static getAllWindows() {+ return [];+ }+ static fromWebContents() {+ return null;+ }+ },+ shell: {},+ dialog: {},+ screen: { getPrimaryDisplay: () => ({ workAreaSize: { width: 0, height: 0 } }) },+ systemPreferences: { getMediaAccessStatus: () => "granted" },+ session: { fromPartition: () => ({}) },+ clipboard: {},+ nativeImage: {},+ globalShortcut: {},+ utilityProcess: {},+ MessageChannelMain: class {},+};++Module._load = function loadWithMocks(request, parent, isMain) {+ if (request === "electron") return electronStub;+ if (parent?.filename === handlersModulePath) {+ if (request === "./tokenStore") {+ return {+ get: () => tokenState.token,+ getState: () => ({ ...tokenState }),+ subscribe: () => () => {},+ };+ }+ if (request === "./windowBroadcast") {+ return { broadcastToWindows: (channel, data) => broadcasts.push([channel, data]) };+ }+ }+ return originalLoad.call(this, request, parent, isMain);+};++function anything() {+ return new Proxy(function () {}, {+ get: (target, property) => {+ if (property === Symbol.toPrimitive || property === "toString") return () => "";+ if (property === "then") return undefined;+ return anything();+ },+ apply: () => anything(),+ });+}++function buildFakeThis() {+ const target = { sessionId: "test-session" };+ return new Proxy(target, {+ get: (value, property) => (property in value ? value[property] : anything()),+ });+}++test.before(() => {+ delete require.cache[handlersModulePath];+ const IPCHandlers = require(handlersModulePath);+ const Ctor = IPCHandlers.default || IPCHandlers;+ Ctor.prototype.setupHandlers.call(buildFakeThis());+});++test.after(() => {+ Module._load = originalLoad;+ fs.rmSync(userDataDirectory, { recursive: true, force: true });+});++const getScope = () => handlers.get("get-active-account-scope")();+const setScope = (accountId, generation) =>+ handlers.get("set-active-account-scope")({}, accountId, generation);++test("no scope is readable before a session has been validated", async () => {+ tokenState = { token: "token-a", generation: 1 };+ assert.equal(await getScope(), null);+});++test("a validated scope is readable back and broadcast to every window", async () => {+ tokenState = { token: "token-a", generation: 1 };+ broadcasts.length = 0;+ assert.deepEqual(await setScope("account-a", 1), { success: true });+ assert.deepEqual(await getScope(), { accountId: "account-a", authGeneration: 1 });+ assert.deepEqual(broadcasts, [+ ["active-account-scope-changed", { accountId: "account-a", authGeneration: 1 }],+ ]);+});++test("a rotated bearer hides the scope until the session is validated again", async () => {+ tokenState = { token: "token-b", generation: 2 };+ assert.equal(await getScope(), null);+ await setScope("account-a", 2);+ assert.deepEqual(await getScope(), { accountId: "account-a", authGeneration: 2 });+});++test("a rejected scope request changes nothing and broadcasts nothing", async () => {+ tokenState = { token: "token-b", generation: 3 };+ broadcasts.length = 0;+ const result = await setScope("account-b", 2);+ assert.equal(result.success, false);+ assert.equal(result.code, "AUTH_CONTEXT_CHANGED");+ assert.deepEqual(broadcasts, []);+});++test("a validated sign-out clears the scope and broadcasts the clearing", async () => {+ tokenState = { token: null, generation: 4 };+ broadcasts.length = 0;+ assert.deepEqual(await setScope(null, 4), { success: true });+ assert.equal(await getScope(), null);+ assert.deepEqual(broadcasts, [["active-account-scope-changed", null]]);+});diff --git a/test/helpers/accountScopeRestoreContract.test.js b/test/helpers/accountScopeRestoreContract.test.jsindex ea54629a2..3dfc19d6d 100644--- a/test/helpers/accountScopeRestoreContract.test.js+++ b/test/helpers/accountScopeRestoreContract.test.js@@ -46,3 +46,17 @@ test("boot restores the validated scope before any main-process consumer construassert.ok(bootWindow[1].includes("resolveBootAccountScope"));assert.ok(bootWindow[1].includes("databaseManager.setActiveAccountId(bootAccountId)"));});++test("clearing the bearer token broadcasts the cleared account scope to every window", () => {+ const source = read("src/helpers/ipcHandlers.js");+ const subscription = source.match(+ /tokenStore\.subscribe\(\(\{ generation, token \}\) => \{([\s\S]*?)\n {4}\}\);/+ );+ assert.ok(subscription, "token subscription is present");+ const cleared = subscription[1].match(/if \(!token\) \{([\s\S]*?)\n {6}\}/);+ assert.ok(cleared, "the no-token branch is present");+ assert.ok(+ cleared[1].includes('broadcastToWindows("active-account-scope-changed", null)'),+ "the no-token branch broadcasts the cleared scope"+ );+});diff --git a/test/helpers/bedrockEnterpriseIpc.test.js b/test/helpers/bedrockEnterpriseIpc.test.jsindex dc42f6460..7eba3065b 100644--- a/test/helpers/bedrockEnterpriseIpc.test.js+++ b/test/helpers/bedrockEnterpriseIpc.test.js@@ -197,6 +197,30 @@ test.beforeEach(() => {resolveManagedRuntime = async () => ({ managed: false });});+test("Check connection asks for at least 16 output tokens, the Azure Responses API minimum", async () => {+ // Live 2026-09-07: Azure rejected the probe with "Invalid 'max_output_tokens':+ // integer below minimum value. Expected a value >= 16, but got 10 instead."+ const probes = [+ ["bedrock", { model: "anthropic.claude-haiku", bedrockRegion: "eu-west-1" }],+ ["azure", { model: "gpt-4.1-mini", azureEndpoint: "https://acme.openai.azure.com" }],+ ];+ for (const [provider, config] of probes) {+ const result = await handlers.get("test-enterprise-connection")(+ { sender: sender(3) },+ provider,+ config+ );+ assert.deepEqual(result, { success: true }, provider);+ }+ assert.equal(generateCalls.length, probes.length);+ for (const call of generateCalls) {+ assert.ok(+ call.maxOutputTokens >= 16,+ `maxOutputTokens ${call.maxOutputTokens} is below Azure's minimum of 16`+ );+ }+});+test("Check connection uses the Bedrock retry policy and disables nested AI SDK retries", async () => {let attempts = 0;generateBehavior = async () => {diff --git a/test/helpers/enterpriseAiProviders.test.js b/test/helpers/enterpriseAiProviders.test.jsindex 6675335d2..ca3ffbfb0 100644--- a/test/helpers/enterpriseAiProviders.test.js+++ b/test/helpers/enterpriseAiProviders.test.js@@ -30,7 +30,6 @@ test("builds the Azure SDK base below the public resource origin", () => {test("rejects unsupported managed Azure endpoint forms", () => {for (const endpoint of [- "https://example.services.ai.azure.com","https://example.openai.azure.us","https://example.openai.azure.com/openai","https://example.openai.azure.com?api-key=secret",diff --git a/test/helpers/enterpriseAiProvidersAzureHosts.test.js b/test/helpers/enterpriseAiProvidersAzureHosts.test.jsnew file mode 100644index 000000000..0d91f444b--- /dev/null+++ b/test/helpers/enterpriseAiProvidersAzureHosts.test.js@@ -0,0 +1,106 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const {+ getEnterpriseAIModel,+ toAzureOpenAIBaseUrl,+} = require("../../src/helpers/enterpriseAiProviders.js");+const { AZURE_HOST_SUFFIXES } = require("../../src/helpers/enterpriseManagedConfig.mjs");++// @ai-sdk/azure appends `/v1` and `?api-version=` itself only when the base+// URL's hostname ends in `.openai.azure.com`; for every other host it uses the+// base URL verbatim. The two shapes are asserted separately so they can never+// silently converge on one template again.+const SDK_VERSIONED_SUFFIXES = [".openai.azure.com"];+const VERBATIM_SUFFIXES = [".cognitiveservices.azure.com", ".services.ai.azure.com"];++const prompt = [{ role: "user", content: [{ type: "text", text: "Hello" }] }];++test("every allowlisted Azure host suffix is classified into exactly one base-URL shape", () => {+ assert.deepEqual(+ [...SDK_VERSIONED_SUFFIXES, ...VERBATIM_SUFFIXES].sort(),+ [...AZURE_HOST_SUFFIXES].sort()+ );+});++test("Azure OpenAI resources keep the SDK-managed base and never gain a /v1 of their own", () => {+ for (const suffix of SDK_VERSIONED_SUFFIXES) {+ for (const endpoint of [`https://acme${suffix}`, `https://acme${suffix}/`]) {+ assert.equal(toAzureOpenAIBaseUrl(endpoint), `https://acme${suffix}/openai`, endpoint);+ }+ }+});++test("AI Services and Foundry resources carry the /v1 segment the SDK will not add", () => {+ for (const suffix of VERBATIM_SUFFIXES) {+ for (const endpoint of [`https://acme${suffix}`, `https://acme${suffix}/`]) {+ assert.equal(toAzureOpenAIBaseUrl(endpoint), `https://acme${suffix}/openai/v1`, endpoint);+ }+ }+});++test("managed Azure LLM rejects path- or query-qualified endpoints on every host class", () => {+ for (const suffix of AZURE_HOST_SUFFIXES) {+ for (const endpoint of [+ `https://acme${suffix}/openai`,+ `https://acme${suffix}/openai/v1`,+ `https://acme${suffix}?api-version=v1`,+ ]) {+ assert.throws(() => toAzureOpenAIBaseUrl(endpoint), /public Azure resource origin/, endpoint);+ }+ }+});++test("managed Azure LLM still rejects spoofed hosts", () => {+ for (const endpoint of [+ "https://acme.openai.azure.us",+ "https://services.ai.azure.com",+ "http://acme.openai.azure.com",+ "https://user:[email protected]",+ "https://evil.com/acme.openai.azure.com",+ ]) {+ assert.throws(() => toAzureOpenAIBaseUrl(endpoint), /public Azure resource origin/, endpoint);+ }+});++test("the pinned Azure SDK builds one request shape per host class", async (t) => {+ const originalFetch = global.fetch;+ t.after(() => {+ global.fetch = originalFetch;+ });+ let request;+ global.fetch = async (url, init) => {+ request = {+ url: String(url),+ headers: Object.fromEntries(new Headers(init.headers)),+ };+ return new Response("{}", {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ };++ for (const [endpoint, expectedUrl] of [+ [+ "https://acme.openai.azure.com",+ "https://acme.openai.azure.com/openai/v1/responses?api-version=v1",+ ],+ [+ "https://acme.cognitiveservices.azure.com",+ "https://acme.cognitiveservices.azure.com/openai/v1/responses",+ ],+ [+ "https://acme.services.ai.azure.com",+ "https://acme.services.ai.azure.com/openai/v1/responses",+ ],+ ]) {+ const model = await getEnterpriseAIModel("azure", "deployment-a", "", {+ azureEndpoint: endpoint,+ azureApiVersion: "v1",+ managedTokenProvider: async () => "temporary-bearer-token",+ });+ await assert.rejects(model.doGenerate({ prompt }));+ assert.equal(request.url, expectedUrl, endpoint);+ assert.equal(request.headers.authorization, "Bearer temporary-bearer-token", endpoint);+ }+});diff --git a/test/helpers/enterpriseIdentityManager.test.js b/test/helpers/enterpriseIdentityManager.test.jsindex a964fc73b..fe02dfb20 100644--- a/test/helpers/enterpriseIdentityManager.test.js+++ b/test/helpers/enterpriseIdentityManager.test.js@@ -334,3 +334,35 @@ test("Bedrock exchanges the workspace assertion for short-lived web identity creclientConfig: { region: "us-west-2" },});});++test("assertion requests carry the inference scope being exercised", async (t) => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-enterprise-scope-"));+ t.after(() => fs.rmSync(tempDir, { recursive: true, force: true }));+ const bodies = [];+ const config = managedConfig();+ config.providers[0].config.transcription = {+ allowedDeployments: ["gpt-4o-transcribe"],+ defaultDeployment: "gpt-4o-transcribe",+ };+ const proxyFetch = async (url, init) => {+ if (url.includes("/enterprise-providers/azure/assertion")) {+ bodies.push(JSON.parse(init.body));+ return jsonResponse({ data: { assertion: "signed" } });+ }+ if (url.startsWith("https://login.microsoftonline.com/")) {+ return jsonResponse({ access_token: "entra", expires_in: 3600 });+ }+ return jsonResponse({ data: config });+ };+ const manager = createEnterpriseIdentityManager({+ cachePath: path.join(tempDir, "cache.json"),+ getApiUrl: () => "https://api.example.com",+ getAppVersion: () => "1.10.0",+ proxyFetch,+ tokenStore: { getState: () => ({ generation: 4, token: "openwhispr-session" }) },+ });+ const resolved = await manager.resolveProvider(request({ inferenceScope: "transcription" }));+ assert.equal(resolved.managed, true);+ await resolved.tokenProvider();+ assert.deepEqual(bodies, [{ inferenceScope: "transcription" }]);+});diff --git a/test/helpers/enterpriseManagedConfig.test.js b/test/helpers/enterpriseManagedConfig.test.jsindex 3436f4b46..dd1b7bded 100644--- a/test/helpers/enterpriseManagedConfig.test.js+++ b/test/helpers/enterpriseManagedConfig.test.js@@ -4,6 +4,7 @@ const assert = require("node:assert/strict");const {resolveManagedEnterpriseScope,validateManagedEnterpriseEnvelope,+ managedScopesForConfig,} = require("../../src/helpers/enterpriseManagedConfig.mjs");const scopes = {@@ -145,7 +146,7 @@ test("an ambiguous cached provider switch fails closed", () => {assert.equal(result.code, "MANAGED_CONFIG_AMBIGUOUS");});-test("rejects sovereign, Foundry, and path-qualified Azure endpoints", () => {+test("accepts Azure resource and Foundry endpoints, rejects sovereign and path-qualified ones", () => {const makeAzure = (endpoint) =>provider({provider: "azure",@@ -160,15 +161,16 @@ test("rejects sovereign, Foundry, and path-qualified Azure endpoints", () => {),},});- assert.ok(- validateManagedEnterpriseEnvelope(- envelope([makeAzure("https://example.openai.azure.com")]),- "workspace-a"- )- );for (const endpoint of [- "https://example.openai.azure.us",+ "https://example.openai.azure.com","https://example.services.ai.azure.com",+ "https://example.cognitiveservices.azure.com",+ ]) {+ assert.ok(validateManagedEnterpriseEnvelope(envelope([makeAzure(endpoint)]), "workspace-a"));+ }+ for (const endpoint of [+ "https://example.openai.azure.us",+ "https://services.ai.azure.com","https://example.openai.azure.com/openai",]) {assert.equal(@@ -196,3 +198,94 @@ test("accepts dated Azure versions from previously issued managed envelopes", ()azure.config.apiVersion = "latest";assert.equal(validateManagedEnterpriseEnvelope(envelope([azure]), "workspace-a"), null);});++const azureBase = {+ tenantId: "11111111-1111-4111-8111-111111111111",+ clientId: "22222222-2222-4222-8222-222222222222",+ endpoint: "https://example.services.ai.azure.com",+ apiVersion: "v1",+};++function azureProvider(config, overrides = {}) {+ return provider({ provider: "azure", config: { ...azureBase, ...config }, ...overrides });+}++test("Azure sections are independent but at least one is required", () => {+ const transcription = {+ allowedDeployments: ["gpt-4o-transcribe"],+ defaultDeployment: "gpt-4o-transcribe",+ };+ assert.ok(+ validateManagedEnterpriseEnvelope(envelope([azureProvider({ transcription })]), "workspace-a")+ );+ assert.ok(+ validateManagedEnterpriseEnvelope(+ envelope([+ azureProvider({+ allowedDeployments: ["gpt-4.1"],+ scopeDefaults: Object.fromEntries(Object.keys(scopes).map((scope) => [scope, "gpt-4.1"])),+ transcription,+ }),+ ]),+ "workspace-a"+ )+ );+ // Neither section, a partial text section, and an out-of-list default all fail.+ for (const config of [+ {},+ { allowedDeployments: ["gpt-4.1"] },+ { transcription: { ...transcription, defaultDeployment: "unapproved" } },+ ]) {+ assert.equal(+ validateManagedEnterpriseEnvelope(envelope([azureProvider(config)]), "workspace-a"),+ null+ );+ }+});++test("the transcription scope resolves from the Azure transcription section only", () => {+ const transcription = {+ allowedDeployments: ["gpt-4o-transcribe"],+ defaultDeployment: "gpt-4o-transcribe",+ };+ const sttOnly = envelope([azureProvider({ transcription })]);+ const resolved = resolveManagedEnterpriseScope(sttOnly, "transcription");+ assert.equal(resolved.kind, "managed");+ assert.equal(resolved.provider, "azure");+ assert.equal(resolved.model, "gpt-4o-transcribe");+ // The LLM scopes stay manual on an STT-only record.+ assert.equal(resolveManagedEnterpriseScope(sttOnly, "dictationCleanup").kind, "manual");+ // A text-only workspace (bedrock) has no managed transcription.+ assert.equal(resolveManagedEnterpriseScope(envelope(), "transcription").kind, "manual");+ // A user opt-out is honored unless the provider is enforced.+ assert.equal(resolveManagedEnterpriseScope(sttOnly, "transcription", "manual").kind, "manual");+ const enforced = envelope([azureProvider({ transcription }, { mode: "managed_required" })]);+ assert.equal(resolveManagedEnterpriseScope(enforced, "transcription", "manual").kind, "managed");+});++test("managedScopesForConfig lists the scopes each active record carries, split by enforcement", () => {+ const transcription = {+ allowedDeployments: ["gpt-4o-transcribe"],+ defaultDeployment: "gpt-4o-transcribe",+ };+ const llmRequired = envelope([provider({ mode: "managed_required", allowManualSetup: false })]);+ assert.deepEqual(managedScopesForConfig(llmRequired), {+ managed: Object.keys(scopes),+ enforced: Object.keys(scopes),+ });+ const sttDefault = envelope([azureProvider({ transcription })]);+ assert.deepEqual(managedScopesForConfig(sttDefault), {+ managed: ["transcription"],+ enforced: [],+ });+ const sttLocked = envelope([azureProvider({ transcription }, { allowManualSetup: false })]);+ assert.deepEqual(managedScopesForConfig(sttLocked), {+ managed: ["transcription"],+ enforced: ["transcription"],+ });+ assert.deepEqual(managedScopesForConfig(null), { managed: [], enforced: [] });+ assert.deepEqual(managedScopesForConfig(envelope([provider({ mode: "disabled" })])), {+ managed: [],+ enforced: [],+ });+});diff --git a/test/helpers/managedTranscriptionExecutor.test.js b/test/helpers/managedTranscriptionExecutor.test.jsnew file mode 100644index 000000000..63cd7870c--- /dev/null+++ b/test/helpers/managedTranscriptionExecutor.test.js@@ -0,0 +1,133 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const {+ createManagedTranscriptionExecutor,+} = require("../../src/helpers/managedTranscriptionExecutor.js");++const context = {+ accountId: "account-a",+ workspaceId: "workspace-a",+ authGeneration: 1,+ setupMode: "auto",+ inferenceScope: "transcription",+ provider: "azure",+ generation: 3,+ providerVersion: 2,+};+const route = {+ transport: "managed",+ provider: "azure",+ deployment: "renderer-guess",+ context,+ language: "de",+};++function runtime(apiVersion = "v1") {+ return {+ provider: "azure",+ model: "gpt-4o-transcribe",+ apiKey: "",+ enterprise: {+ azureEndpoint: "https://acme.services.ai.azure.com",+ azureApiVersion: apiVersion,+ managedTokenProvider: async () => "entra-token",+ },+ };+}++async function buildUrl(endpoint, deployment, apiVersion) {+ const { buildManagedAzureTranscriptionUrl } = await import("../../src/utils/urlUtils.ts");+ return buildManagedAzureTranscriptionUrl(endpoint, deployment, apiVersion);+}++function executor({ fetch, apiVersion, resolve } = {}) {+ return createManagedTranscriptionExecutor({+ resolveEnterpriseRuntime: resolve ?? (async () => runtime(apiVersion)),+ proxyFetch: fetch,+ buildUrl,+ });+}++const input = {+ audioBuffer: Buffer.from("audio"),+ fileName: "audio.webm",+ contentType: "audio/webm",+ prompt: "Möbius",+};++test("posts multipart audio to the workspace deployment with an Entra bearer", async () => {+ const calls = [];+ const run = executor({+ fetch: async (url, init) => {+ calls.push({ url, init });+ return new Response(JSON.stringify({ text: "hallo welt" }), { status: 200 });+ },+ });+ assert.equal(await run({}, route, input), "hallo welt");+ assert.equal(calls.length, 1);+ assert.equal(+ calls[0].url,+ "https://acme.services.ai.azure.com/openai/deployments/gpt-4o-transcribe/audio/transcriptions?api-version=2025-03-01-preview"+ );+ assert.equal(calls[0].init.headers.Authorization, "Bearer entra-token");+ const body = calls[0].init.body;+ assert.equal(body.get("model"), "gpt-4o-transcribe"); // workspace default, not the renderer's value+ assert.equal(body.get("response_format"), "json");+ assert.equal(body.get("language"), "de");+ assert.equal(body.get("prompt"), "Möbius");+ assert.equal(body.get("file").name, "audio.webm");+ assert.ok(calls[0].init.signal instanceof AbortSignal);+});++test("sends .opus uploads under an .ogg filename, the container Azure recognises", async () => {+ // Proven live 2026-09-07: identical Ogg-Opus bytes are rejected as "Unsupported+ // file format opus" under a .opus name and transcribed under a .ogg name.+ const calls = [];+ const run = executor({+ fetch: async (_url, init) => {+ calls.push(init);+ return new Response(JSON.stringify({ text: "ok" }), { status: 200 });+ },+ });+ await run({}, route, { ...input, fileName: "ow-url-123.opus", contentType: "audio/ogg" });+ const file = calls[0].body.get("file");+ assert.equal(file.name, "ow-url-123.ogg");+ assert.equal(file.type, "audio/ogg");+});++test("maps Azure failures to coded errors", async () => {+ for (const [status, code] of [+ [429, "PROVIDER_RATE_LIMITED"],+ [503, "SERVER_ERROR"],+ [401, "MANAGED_AUTH_REJECTED"],+ ]) {+ const run = executor({ fetch: async () => new Response("nope", { status }) });+ await assert.rejects(run({}, route, input), (error) => error.code === code, String(status));+ }+});++test("rejects routes that are not a managed transcription route", async () => {+ const run = executor({ fetch: async () => new Response("{}", { status: 200 }) });+ await assert.rejects(+ run({}, { ...route, context: { ...context, inferenceScope: "dictationCleanup" } }, input),+ (error) => error.code === "MANAGED_ROUTE_INVALID"+ );+});++test("propagates MANAGED_CONFIG_CHANGED from runtime revalidation", async () => {+ const run = executor({+ fetch: async () => new Response("{}", { status: 200 }),+ resolve: async () => {+ throw Object.assign(new Error("changed"), { code: "MANAGED_CONFIG_CHANGED" });+ },+ });+ await assert.rejects(run({}, route, input), (error) => error.code === "MANAGED_CONFIG_CHANGED");+});++test("an empty transcript is reported as no speech", async () => {+ const run = executor({+ fetch: async () => new Response(JSON.stringify({ text: " " }), { status: 200 }),+ });+ await assert.rejects(run({}, route, input), (error) => error.code === "NO_SPEECH_DETECTED");+});diff --git a/test/helpers/policyEffectiveSettings.test.js b/test/helpers/policyEffectiveSettings.test.jsindex bff81aaa2..c288ea55b 100644--- a/test/helpers/policyEffectiveSettings.test.js+++ b/test/helpers/policyEffectiveSettings.test.js@@ -274,3 +274,46 @@ test("a managed screen-context denial forces the effective setting off without tusePolicyStore.setState({ status: "unmanaged", managed: false, policy: null });assert.equal(getSettings().voiceAgentScreenContext, true);});++test("an enterprise-only transcription policy resolves for dictation and upload", async (t) => {+ installBrowserGlobals(t, {+ initialStorage: {+ _providerSettingsMigrated: "1",+ uploadTranscriptionMigrated: "true",+ transcriptionMode: "providers",+ useLocalWhisper: "false",+ },+ });+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-policy-effective-transcription-enterprise-test-",+ });+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");+ const { getSettings, useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");+ const { isTranscriptionContextAllowed } = await vite.ssrLoadModule("/stores/policyRules.ts");++ usePolicyStore.setState({+ status: "managed",+ managed: true,+ policy: {+ ...managedPolicy,+ transcription: {+ allowedModes: ["enterprise"],+ allowedByokProviders: [],+ allowedEnterpriseProviders: ["azure"],+ },+ },+ appVersion: "1.10.0",+ });++ const effective = getSettings();+ assert.equal(effective.transcriptionMode, "enterprise");+ assert.equal(effective.useLocalWhisper, false);+ assert.equal(effective.uploadTranscriptionMode, "enterprise");+ assert.equal(+ isTranscriptionContextAllowed(usePolicyStore.getState(), effective, "dictation"),+ true+ );+ assert.equal(isTranscriptionContextAllowed(usePolicyStore.getState(), effective, "upload"), true);+ // Raw preferences are untouched.+ assert.equal(useSettingsStore.getState().transcriptionMode, "providers");+});diff --git a/test/helpers/policyRules.test.js b/test/helpers/policyRules.test.jsindex 42747c655..748e8e035 100644--- a/test/helpers/policyRules.test.js+++ b/test/helpers/policyRules.test.js@@ -831,3 +831,84 @@ test("missing required models is a pure set difference over disk truth", async ();assert.deepEqual(missingRequiredLocalModels(["base"], ["base"]), []);});++test("enterprise transcription resolves through the transcription policy section", async () => {+ const { resolveEffectivePolicySelection, filterModeOptionsByPolicy } = await load();+ const enterpriseOnly = {+ status: "managed",+ appVersion: "1.10.0",+ policy: {+ ...policy,+ transcription: { allowedModes: ["enterprise"], allowedByokProviders: [], allowedEnterpriseProviders: ["azure"] },+ },+ };+ const catalog = { modes: ["openwhispr", "providers", "local", "self-hosted", "enterprise"], byokProviders: ["openai"], enterpriseProviders: ["azure"] };+ assert.deepEqual(+ resolveEffectivePolicySelection(enterpriseOnly, "transcription", { mode: "openwhispr", provider: "" }, catalog),+ { mode: "enterprise", provider: "azure" }+ );+ const options = filterModeOptionsByPolicy(catalog.modes.map((id) => ({ id })), "transcription", enterpriseOnly, catalog);+ assert.deepEqual(options.map((o) => o.id), ["enterprise"]);+ // The meeting catalog has no enterprise lane, so meetings stay unresolvable (documented).+ const meetingCatalog = { modes: ["openwhispr", "providers", "local"], byokProviders: ["openai"] };+ assert.equal(resolveEffectivePolicySelection(enterpriseOnly, "transcription", { mode: "local", provider: "" }, meetingCatalog), null);+});++// Mirrors what TranscriptionSection/UploadTranscriptionPanel do: the+// "enterprise" tile is only appended to the raw option list when the policy+// snapshot is managed, before that list is ever handed to+// filterModeOptionsByPolicy. Selecting it with no managed org behind it+// writes a mode with no personal configuration surface and no managed+// resolution, which then fails every dictation/upload closed.+test("the enterprise transcription tile is offered only to a managed policy snapshot", async () => {+ const { isEnterpriseTranscriptionOfferable, filterModeOptionsByPolicy } = await load();+ const baseOptions = [{ id: "openwhispr" }, { id: "providers" }, { id: "local" }, { id: "self-hosted" }];+ const enterpriseOption = { id: "enterprise" };+ const catalog = { byokProviders: ["openai"], enterpriseProviders: ["azure"] };+ const buildOptions = (state) => [+ ...baseOptions,+ ...(isEnterpriseTranscriptionOfferable(state) ? [enterpriseOption] : []),+ ];++ const idle = { status: "idle", policy: null, appVersion: null };+ const unmanaged = { status: "unmanaged", policy: null, appVersion: "1.10.0" };+ const managedEnterpriseAzure = {+ status: "managed",+ appVersion: "1.10.0",+ policy: {+ ...policy,+ transcription: {+ allowedModes: ["openwhispr", "providers", "local", "self-hosted", "enterprise"],+ allowedByokProviders: ["openai"],+ allowedEnterpriseProviders: ["azure"],+ },+ },+ };++ assert.equal(isEnterpriseTranscriptionOfferable(idle), false);+ assert.equal(isEnterpriseTranscriptionOfferable(unmanaged), false);+ assert.equal(isEnterpriseTranscriptionOfferable(managedEnterpriseAzure), true);++ for (const state of [idle, unmanaged]) {+ const options = filterModeOptionsByPolicy(buildOptions(state), "transcription", state, catalog);+ assert.deepEqual(+ options.map((o) => o.id),+ ["openwhispr", "providers", "local", "self-hosted"],+ state.status+ );+ }++ const managedOptions = filterModeOptionsByPolicy(+ buildOptions(managedEnterpriseAzure),+ "transcription",+ managedEnterpriseAzure,+ catalog+ );+ assert.deepEqual(managedOptions.map((o) => o.id), [+ "openwhispr",+ "providers",+ "local",+ "self-hosted",+ "enterprise",+ ]);+});diff --git a/test/helpers/policyValidation.test.js b/test/helpers/policyValidation.test.jsindex 48d684524..3d03ecc37 100644--- a/test/helpers/policyValidation.test.js+++ b/test/helpers/policyValidation.test.js@@ -122,13 +122,17 @@ test("rejects unknown modes and providers", () => {const cases = [["transcription.allowedModes",- (policy) => policy.transcription.allowedModes.push("enterprise"),+ (policy) => policy.transcription.allowedModes.push("future-mode"),],["llm.allowedModes", (policy) => policy.llm.allowedModes.push("future-mode")],["transcription.allowedByokProviders",(policy) => policy.transcription.allowedByokProviders.push("future-stt"),],+ [+ "transcription.allowedEnterpriseProviders",+ (policy) => (policy.transcription.allowedEnterpriseProviders = ["bedrock"]),+ ],["llm.allowedByokProviders", (policy) => policy.llm.allowedByokProviders.push("future-llm")],["llm.allowedEnterpriseProviders",@@ -143,6 +147,18 @@ test("rejects unknown modes and providers", () => {}});+test("enterprise transcription is additive within policy v1", () => {+ const withEnterprise = validPolicy();+ withEnterprise.transcription.allowedModes.push("enterprise");+ withEnterprise.transcription.allowedEnterpriseProviders = ["azure"];+ assert.equal(isValidPolicyShape(withEnterprise), true);++ // Absent on older servers; absent means none.+ const withoutField = validPolicy();+ delete withoutField.transcription.allowedEnterpriseProviders;+ assert.equal(isValidPolicyShape(withoutField), true);+});+test("rejects a missing or non-object policy", () => {assert.equal(isValidPolicyShape(undefined), false);assert.equal(isValidPolicyShape(null), false);diff --git a/test/helpers/transcriptionRoute.test.js b/test/helpers/transcriptionRoute.test.jsindex 7e780ecbf..41ef49b92 100644--- a/test/helpers/transcriptionRoute.test.js+++ b/test/helpers/transcriptionRoute.test.js@@ -285,3 +285,93 @@ test("request overrides win: explicit model and effective language", async () =>assert.equal(route.model, "whisper-large-v3");assert.equal(route.language, "ja");});++const MANAGED_STT = {+ kind: "managed",+ provider: "azure",+ deployment: "gpt-4o-transcribe",+ context: {+ accountId: "account-a",+ workspaceId: "workspace-a",+ authGeneration: 1,+ setupMode: "auto",+ inferenceScope: "transcription",+ provider: "azure",+ generation: 3,+ providerVersion: 2,+ },+};++test("a managed resolution outranks every personal setting", async () => {+ const route = await resolve(+ {+ transcriptionMode: "self-hosted",+ remoteTranscriptionUrl: "http://192.168.1.5:11434/v1",+ useLocalWhisper: true,+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionBaseUrl: "https://example.test/v1",+ preferredLanguage: "de-DE",+ },+ { managed: MANAGED_STT }+ );+ assert.equal(route.transport, "managed");+ assert.equal(route.provider, "azure");+ assert.equal(route.deployment, "gpt-4o-transcribe");+ assert.equal(route.context, MANAGED_STT.context);+ assert.equal(route.language, "de");+ // Routes never carry secrets — the context is identity metadata only.+ assert.equal("auth" in route, false);+});++test("a managed resolution bypasses the personal-selection policy floor", async () => {+ const enterpriseOnly = structuredClone(MANAGED_OPENAI_ONLY);+ enterpriseOnly.policy.transcription.allowedModes = ["enterprise"];+ enterpriseOnly.policy.transcription.allowedByokProviders = [];+ enterpriseOnly.policy.transcription.allowedEnterpriseProviders = ["azure"];+ const route = await resolve(+ { cloudTranscriptionProvider: "openai" },+ { policy: enterpriseOnly, managed: MANAGED_STT }+ );+ assert.equal(route.transport, "managed");+ // Without the managed resolution the same settings fail closed.+ const blocked = await resolve(+ { cloudTranscriptionProvider: "openai" },+ { policy: enterpriseOnly }+ );+ assert.equal(blocked.transport, "error");+ assert.equal(blocked.code, "POLICY_RESTRICTED");+});++test("a managed resolution error becomes an error route", async () => {+ const route = await resolve(+ { cloudTranscriptionProvider: "openai" },+ {+ managed: {+ kind: "error",+ message: "Managed access unavailable",+ code: "MANAGED_CONFIG_UNAVAILABLE",+ },+ }+ );+ assert.equal(route.transport, "error");+ assert.equal(route.code, "MANAGED_CONFIG_UNAVAILABLE");+});++test("an enterprise transcription mode without a managed resolution fails closed", async () => {+ const route = await resolve({+ transcriptionMode: "enterprise",+ cloudTranscriptionProvider: "openai",+ });+ assert.equal(route.transport, "error");+ assert.equal(route.code, "MANAGED_CONFIG_UNAVAILABLE");+});++test("an enterprise transcription mode WITH a managed resolution takes the managed transport, not the fail-closed guard", async () => {+ const route = await resolve(+ { transcriptionMode: "enterprise", cloudTranscriptionProvider: "openai" },+ { managed: MANAGED_STT }+ );+ assert.equal(route.transport, "managed");+ assert.equal(route.provider, "azure");+ assert.equal(route.deployment, "gpt-4o-transcribe");+});diff --git a/test/lib/accountScopeMirror.test.js b/test/lib/accountScopeMirror.test.jsnew file mode 100644index 000000000..275c1b730--- /dev/null+++ b/test/lib/accountScopeMirror.test.js@@ -0,0 +1,229 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++// The dictation window cannot resolve a session (sandboxed, web security+// enforced), so the managed identity there is hydrated from the main+// process's validated account scope instead. These tests drive that mirror+// with the same probe the live verification uses: isManagedTranscriptionActive.+const azureSttRequired = {+ workspaceId: "workspace-a",+ version: 1,+ generation: 1,+ identity: {+ issuer: "https://api.example.com/enterprise-identity",+ jwksUri: "https://api.example.com/enterprise-identity/jwks.json",+ subject: "workspace:workspace-a",+ audiences: { bedrock: "sts.amazonaws.com", azure: "api://AzureADTokenExchange" },+ },+ providers: [+ {+ provider: "azure",+ mode: "managed_required",+ allowManualSetup: false,+ config: {+ tenantId: "11111111-1111-4111-8111-111111111111",+ clientId: "22222222-2222-4222-8222-222222222222",+ endpoint: "https://example.openai.azure.com",+ apiVersion: "preview",+ transcription: {+ allowedDeployments: ["gpt-4o-transcribe"],+ defaultDeployment: "gpt-4o-transcribe",+ },+ },+ version: 1,+ updatedAt: "2026-08-10T00:00:00.000Z",+ },+ ],+};+const policy = {+ version: 1,+ transcription: {+ allowedModes: ["enterprise", "local"],+ allowedByokProviders: [],+ allowedEnterpriseProviders: ["azure"],+ },+ llm: { allowedModes: ["openwhispr"], allowedByokProviders: [], allowedEnterpriseProviders: [] },+ features: { agentEnabled: true, webSearchEnabled: false },+ sharing: { externalLinkSharing: "disabled" },+ dataRetention: {+ audioRetentionMaxDays: null,+ localHistoryMode: "user_choice",+ cloudBackupAllowed: false,+ },+ minAppVersion: null,+};++function windowEvents() {+ const listeners = new Map();+ return {+ add: (type, listener) => listeners.set(type, [...(listeners.get(type) ?? []), listener]),+ remove: (type, listener) =>+ listeners.set(+ type,+ (listeners.get(type) ?? []).filter((candidate) => candidate !== listener)+ ),+ dispatch: (type, event) => (listeners.get(type) ?? []).forEach((listener) => listener(event)),+ count: (type) => (listeners.get(type) ?? []).length,+ };+}++async function waitFor(check, label) {+ for (let attempt = 0; attempt < 100; attempt += 1) {+ if (check()) return;+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+ assert.fail(`timed out waiting for ${label}`);+}++async function boot(t, { scope = null, activeWorkspaceId = null, readScope } = {}) {+ // Registered before installBrowserGlobals so the mirror detaches while `window` still exists.+ let stop = () => {};+ t.after(() => stop());+ const events = windowEvents();+ const calls = { policy: [], config: [] };+ let onScopeChanged = null;+ const electronAPI = {+ getAppVersion: async () => ({ version: "1.10.0" }),+ getActiveAccountScope: readScope ?? (async () => scope),+ onActiveAccountScopeChanged: (callback) => {+ onScopeChanged = callback;+ return () => {+ onScopeChanged = null;+ };+ },+ getWorkspacePolicy: async (accountId, authGeneration) => {+ calls.policy.push([accountId, authGeneration]);+ return {+ success: true,+ revision: calls.policy.length,+ accountId,+ authGeneration,+ managed: true,+ policy,+ };+ },+ getManagedEnterpriseConfig: async (accountId, workspaceId, authGeneration) => {+ calls.config.push([accountId, workspaceId, authGeneration]);+ return {+ success: true,+ status: "network",+ accountId,+ workspaceId,+ authGeneration,+ config: azureSttRequired,+ };+ },+ clearManagedEnterpriseIdentity: async () => {},+ };+ const { storage } = installBrowserGlobals(t, {+ initialStorage: activeWorkspaceId ? { activeWorkspaceId } : {},+ window: { electronAPI, addEventListener: events.add, removeEventListener: events.remove },+ });+ const vite = await createRendererServer(t, { cachePrefix: "openwhispr-account-scope-mirror-" });+ const { mirrorActiveAccountScope } = await vite.ssrLoadModule("/lib/accountScopeMirror.ts");+ const managed = await vite.ssrLoadModule("/services/managedTranscription.ts");+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");+ const { useEnterpriseIdentityStore } = await vite.ssrLoadModule(+ "/stores/enterpriseIdentityStore.ts"+ );+ stop = mirrorActiveAccountScope();+ return {+ managed,+ usePolicyStore,+ useEnterpriseIdentityStore,+ calls,+ events,+ stop,+ broadcast: (next) => onScopeChanged?.(next),+ listeningForBroadcasts: () => onScopeChanged !== null,+ // Browser semantics: the other window's write has landed before the event fires here.+ setActiveWorkspace: (id) => {+ storage.setItem("activeWorkspaceId", id);+ events.dispatch("storage", { key: "activeWorkspaceId", newValue: id });+ },+ };+}++test("a window without a session hydrates managed transcription from the main process scope", async (t) => {+ const { managed, calls, broadcast, usePolicyStore, useEnterpriseIdentityStore } = await boot(t, {+ scope: { accountId: "account-a", authGeneration: 1 },+ activeWorkspaceId: "workspace-a",+ });+ await waitFor(() => managed.isManagedTranscriptionActive(), "managed transcription");+ const resolution = managed.getManagedTranscriptionResolution();+ assert.equal(resolution.kind, "managed");+ assert.equal(resolution.provider, "azure");+ assert.equal(resolution.deployment, "gpt-4o-transcribe");+ assert.deepEqual(+ [+ resolution.context.accountId,+ resolution.context.workspaceId,+ resolution.context.authGeneration,+ ],+ ["account-a", "workspace-a", 1]+ );+ assert.deepEqual(calls.policy, [["account-a", 1]]);+ assert.deepEqual(calls.config, [["account-a", "workspace-a", 1]]);++ await t.test("a new credential generation re-resolves policy and identity", async () => {+ broadcast({ accountId: "account-a", authGeneration: 2 });+ await waitFor(+ () => managed.getManagedTranscriptionResolution()?.context?.authGeneration === 2,+ "generation 2"+ );+ assert.deepEqual(calls.policy.at(-1), ["account-a", 2]);+ assert.deepEqual(calls.config.at(-1), ["account-a", "workspace-a", 2]);+ assert.equal(managed.isManagedTranscriptionActive(), true);+ });++ await t.test("a cleared scope (sign-out) clears the mirrored identity at once", () => {+ broadcast(null);+ assert.equal(managed.isManagedTranscriptionActive(), false);+ assert.equal(managed.getManagedTranscriptionResolution(), undefined);+ assert.equal(usePolicyStore.getState().status, "idle");+ assert.equal(useEnterpriseIdentityStore.getState().status, "idle");+ assert.equal(useEnterpriseIdentityStore.getState().accountId, null);+ });+});++test("a scope validated after boot arrives by broadcast and the workspace by storage", async (t) => {+ const { managed, calls, broadcast, setActiveWorkspace, usePolicyStore } = await boot(t);+ await new Promise((resolve) => setTimeout(resolve, 20));+ assert.equal(managed.isManagedTranscriptionActive(), false);+ assert.deepEqual(calls.policy, []);++ broadcast({ accountId: "account-a", authGeneration: 1 });+ await waitFor(() => usePolicyStore.getState().status === "managed", "policy");+ // No active workspace is known yet, so nothing can be managed.+ assert.equal(managed.isManagedTranscriptionActive(), false);+ assert.deepEqual(calls.config, []);++ setActiveWorkspace("workspace-a");+ await waitFor(() => managed.isManagedTranscriptionActive(), "managed transcription");+ assert.deepEqual(calls.config, [["account-a", "workspace-a", 1]]);+});++test("a broadcast that lands while the boot read is in flight is not overwritten by it", async (t) => {+ let resolveRead;+ const { managed, broadcast } = await boot(t, {+ activeWorkspaceId: "workspace-a",+ readScope: () => new Promise((resolve) => (resolveRead = resolve)),+ });+ broadcast({ accountId: "account-a", authGeneration: 1 });+ await waitFor(() => managed.isManagedTranscriptionActive(), "managed transcription");+ resolveRead(null);+ await new Promise((resolve) => setTimeout(resolve, 20));+ assert.equal(managed.isManagedTranscriptionActive(), true);+});++test("stopping the mirror detaches both the broadcast and the storage listener", async (t) => {+ const { stop, events, listeningForBroadcasts } = await boot(t, {+ activeWorkspaceId: "workspace-a",+ });+ assert.equal(events.count("storage"), 1);+ assert.equal(listeningForBroadcasts(), true);+ stop();+ assert.equal(events.count("storage"), 0);+ assert.equal(listeningForBroadcasts(), false);+});diff --git a/test/services/fileTranscriptionManaged.test.js b/test/services/fileTranscriptionManaged.test.jsnew file mode 100644index 000000000..a7f3ef337--- /dev/null+++ b/test/services/fileTranscriptionManaged.test.js@@ -0,0 +1,142 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++const identity = {+ issuer: "https://api.example.com/enterprise-identity",+ jwksUri: "https://api.example.com/enterprise-identity/jwks.json",+ subject: "workspace:workspace-a",+ audiences: { bedrock: "sts.amazonaws.com", azure: "api://AzureADTokenExchange" },+};+const sttDefault = {+ workspaceId: "workspace-a",+ version: 1,+ generation: 1,+ identity,+ providers: [+ {+ provider: "azure",+ mode: "managed_default",+ allowManualSetup: true,+ config: {+ tenantId: "11111111-1111-4111-8111-111111111111",+ clientId: "22222222-2222-4222-8222-222222222222",+ endpoint: "https://example.openai.azure.com",+ apiVersion: "preview",+ transcription: {+ allowedDeployments: ["gpt-4o-transcribe"],+ defaultDeployment: "gpt-4o-transcribe",+ },+ },+ version: 1,+ updatedAt: "2026-08-10T00:00:00.000Z",+ },+ ],+};+const policy = {+ version: 1,+ transcription: {+ allowedModes: ["enterprise", "openwhispr", "local"],+ allowedByokProviders: [],+ allowedEnterpriseProviders: ["azure"],+ },+ llm: { allowedModes: ["openwhispr"], allowedByokProviders: [], allowedEnterpriseProviders: [] },+ features: { agentEnabled: true, webSearchEnabled: false },+ sharing: { externalLinkSharing: "disabled" },+ dataRetention: {+ audioRetentionMaxDays: null,+ localHistoryMode: "user_choice",+ cloudBackupAllowed: false,+ },+ minAppVersion: null,+};+const cfg = (overrides) => ({+ useLocalWhisper: false,+ localTranscriptionProvider: "whisper",+ whisperModel: "base",+ parakeetModel: "p",+ cohereModel: "c",+ isOpenWhisprCloud: false,+ getApiKey: () => "",+ cloudTranscriptionProvider: "openai",+ cloudTranscriptionBaseUrl: "",+ cloudTranscriptionModel: "whisper-1",+ language: "en",+ transcriptionMode: "providers",+ ...overrides,+});++test("managed transcription outranks OpenWhispr Cloud and local Whisper on the upload lane", async (t) => {+ const { window } = installBrowserGlobals(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-file-managed-",+ mockModules: { "/lib/auth": "export const withSessionRefresh = (fn) => fn();" },+ });+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");+ const { useEnterpriseIdentityStore } = await vite.ssrLoadModule(+ "/stores/enterpriseIdentityStore.ts"+ );+ const { transcribeFile } = await vite.ssrLoadModule("/services/fileTranscription.ts");+ usePolicyStore.setState({ status: "managed", appVersion: "1.10.0", policy });+ useEnterpriseIdentityStore.setState({+ accountId: "account-a",+ workspaceId: "workspace-a",+ authGeneration: 1,+ status: "ready",+ config: sttDefault,+ error: null,+ managedScopes: ["transcription"],+ enforcedScopes: [],+ });++ const calls = { cloud: 0, local: 0, byok: [] };+ window.electronAPI.transcribeAudioFileCloud = async () => {+ calls.cloud += 1;+ return { success: true, text: "cloud" };+ };+ window.electronAPI.transcribeAudioFile = async () => {+ calls.local += 1;+ return { success: true, text: "local" };+ };+ window.electronAPI.transcribeAudioFileByok = async (args) => {+ calls.byok.push(args);+ return { success: true, text: "managed" };+ };++ for (const config of [+ cfg({ isOpenWhisprCloud: true }),+ cfg({ useLocalWhisper: true }),+ cfg({}),+ ]) {+ const result = await transcribeFile("/tmp/a.wav", config, true);+ assert.equal(result.text, "managed");+ }+ assert.equal(calls.cloud, 0);+ assert.equal(calls.local, 0);+ assert.equal(calls.byok.length, 3);+ for (const args of calls.byok) {+ assert.equal(args.managed.kind, "managed");+ assert.equal(args.managed.deployment, "gpt-4o-transcribe");+ }++ // A managed resolution error (config confirmed gone, scope enforced) must+ // fail closed: no cloud, no local, and no BYOK call either — the error+ // short-circuit in transcribeFile is load-bearing, not just redundant with+ // the `!managed &&` guards below it.+ useEnterpriseIdentityStore.setState({+ accountId: "account-a",+ workspaceId: "workspace-a",+ authGeneration: 1,+ status: "error",+ config: null,+ error: "offline",+ managedScopes: ["transcription"],+ enforcedScopes: ["transcription"],+ });+ const errorResult = await transcribeFile("/tmp/a.wav", cfg({ isOpenWhisprCloud: true }), true);+ assert.equal(errorResult.success, false);+ assert.equal(errorResult.code, "MANAGED_CONFIG_UNAVAILABLE");+ assert.equal(calls.cloud, 0);+ assert.equal(calls.local, 0);+ assert.equal(calls.byok.length, 3);+});diff --git a/test/services/managedEnterpriseRouting.test.js b/test/services/managedEnterpriseRouting.test.jsindex d562b2ba5..df5f5fc88 100644--- a/test/services/managedEnterpriseRouting.test.js+++ b/test/services/managedEnterpriseRouting.test.js@@ -170,7 +170,8 @@ test("enterprise call settings cannot omit or bypass a resolved managed route",status: "ready",config: managedBedrockConfig(),error: null,- failClosed: false,+ managedScopes: SCOPES,+ enforcedScopes: [],});const settings = getEnterpriseCallSettings("azure", "dictationCleanup");@@ -181,7 +182,8 @@ test("enterprise call settings cannot omit or bypass a resolved managed route",status: "error",config: null,error: "Company SSO is required",- failClosed: true,+ managedScopes: SCOPES,+ enforcedScopes: SCOPES,});assert.throws(() => getEnterpriseCallSettings("azure", "dictationCleanup"),@@ -235,7 +237,8 @@ test("required managed access fails closed when workspace policy forbids it", asstatus: "error",config: null,error: "Sign in with company SSO",- failClosed: true,+ managedScopes: SCOPES,+ enforcedScopes: SCOPES,});const unavailable = resolvedMode();assert.equal(unavailable.mode, "enterprise");diff --git a/test/stores/enterpriseIdentityStoreEnforcement.test.js b/test/stores/enterpriseIdentityStoreEnforcement.test.jsnew file mode 100644index 000000000..577386506--- /dev/null+++ b/test/stores/enterpriseIdentityStoreEnforcement.test.js@@ -0,0 +1,337 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++const SCOPES = [+ "dictationCleanup",+ "dictationAgent",+ "noteFormatting",+ "chatIntelligence",+ "dictationTranslation",+];+const identity = {+ issuer: "https://api.example.com/enterprise-identity",+ jwksUri: "https://api.example.com/enterprise-identity/jwks.json",+ subject: "workspace:workspace-a",+ audiences: { bedrock: "sts.amazonaws.com", azure: "api://AzureADTokenExchange" },+};+const bedrockRequired = {+ workspaceId: "workspace-a",+ version: 1,+ generation: 1,+ identity,+ providers: [+ {+ provider: "bedrock",+ mode: "managed_required",+ allowManualSetup: false,+ config: {+ roleArn: "arn:aws:iam::123456789012:role/OpenWhispr",+ region: "us-east-1",+ allowedModels: ["m"],+ scopeDefaults: Object.fromEntries(SCOPES.map((s) => [s, "m"])),+ },+ version: 1,+ updatedAt: "2026-08-10T00:00:00.000Z",+ },+ ],+};+const azureSttRequired = {+ workspaceId: "workspace-a",+ version: 1,+ generation: 1,+ identity,+ providers: [+ {+ provider: "azure",+ mode: "managed_required",+ allowManualSetup: false,+ config: {+ tenantId: "11111111-1111-4111-8111-111111111111",+ clientId: "22222222-2222-4222-8222-222222222222",+ endpoint: "https://example.openai.azure.com",+ apiVersion: "preview",+ transcription: {+ allowedDeployments: ["gpt-4o-transcribe"],+ defaultDeployment: "gpt-4o-transcribe",+ },+ },+ version: 1,+ updatedAt: "2026-08-10T00:00:00.000Z",+ },+ ],+};+const policy = {+ version: 1,+ transcription: {+ allowedModes: ["enterprise", "local"],+ allowedByokProviders: [],+ allowedEnterpriseProviders: ["azure"],+ },+ llm: {+ allowedModes: ["enterprise", "local"],+ allowedByokProviders: [],+ allowedEnterpriseProviders: ["bedrock"],+ },+ features: { agentEnabled: true, webSearchEnabled: false },+ sharing: { externalLinkSharing: "disabled" },+ dataRetention: {+ audioRetentionMaxDays: null,+ localHistoryMode: "user_choice",+ cloudBackupAllowed: false,+ },+ minAppVersion: null,+};++async function boot(t, { electronAPI = {}, initialStorage = {} } = {}) {+ installBrowserGlobals(t, { initialStorage, window: { electronAPI } });+ const vite = await createRendererServer(t, { cachePrefix: "openwhispr-identity-enforcement-" });+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");+ const { useEnterpriseIdentityStore, getManagedScopeResolution } = await vite.ssrLoadModule(+ "/stores/enterpriseIdentityStore.ts"+ );+ usePolicyStore.setState({ status: "managed", appVersion: "1.10.0", policy });+ return { useEnterpriseIdentityStore, getManagedScopeResolution };+}++test("an LLM-only enforced workspace never fails transcription closed on a config outage", async (t) => {+ let call = 0;+ const { useEnterpriseIdentityStore, getManagedScopeResolution } = await boot(t, {+ electronAPI: {+ getManagedEnterpriseConfig: async (accountId, workspaceId, authGeneration) => {+ call += 1;+ if (call === 1)+ return {+ success: true,+ status: "network",+ accountId,+ workspaceId,+ authGeneration,+ config: bedrockRequired,+ };+ return {+ success: false,+ status: "error",+ accountId,+ workspaceId,+ authGeneration,+ code: "AUTH_EXPIRED",+ error: "expired",+ enforcementRequired: true,+ enforcedScopes: SCOPES,+ };+ },+ },+ });+ await useEnterpriseIdentityStore.getState().refresh("account-a", "workspace-a", 1);+ assert.equal(getManagedScopeResolution("transcription", "auto").kind, "manual");+ await useEnterpriseIdentityStore.getState().refresh("account-a", "workspace-a", 1, true);+ assert.equal(useEnterpriseIdentityStore.getState().status, "error");+ assert.equal(getManagedScopeResolution("transcription", "auto").kind, "manual");+ assert.equal(+ getManagedScopeResolution("dictationCleanup", "auto").code,+ "MANAGED_CONFIG_UNAVAILABLE"+ );+});++test("an STT-only enforced workspace fails only transcription closed", async (t) => {+ const { useEnterpriseIdentityStore, getManagedScopeResolution } = await boot(t);+ useEnterpriseIdentityStore.setState({+ accountId: "account-a",+ workspaceId: "workspace-a",+ authGeneration: 1,+ status: "error",+ config: null,+ error: "offline",+ managedScopes: ["transcription"],+ enforcedScopes: ["transcription"],+ });+ assert.equal(+ getManagedScopeResolution("transcription", "auto").code,+ "MANAGED_CONFIG_UNAVAILABLE"+ );+ assert.equal(getManagedScopeResolution("dictationCleanup", "auto").kind, "manual");+});++test("the first fetch holds only scopes the last-known config enforced", async (t) => {+ const { useEnterpriseIdentityStore, getManagedScopeResolution } = await boot(t, {+ initialStorage: {+ "managedEnterpriseScopes:account-a:workspace-a": JSON.stringify({+ managed: ["transcription"],+ enforced: ["transcription"],+ }),+ },+ electronAPI: { getManagedEnterpriseConfig: () => new Promise(() => {}) },+ });+ void useEnterpriseIdentityStore.getState().refresh("account-a", "workspace-a", 1);+ assert.equal(useEnterpriseIdentityStore.getState().status, "loading");+ assert.equal(getManagedScopeResolution("transcription", "auto").code, "MANAGED_CONFIG_LOADING");+ assert.equal(getManagedScopeResolution("dictationCleanup", "auto").kind, "manual");+});++test("a successful fetch persists the scope summary for the next cold start", async (t) => {+ const { useEnterpriseIdentityStore } = await boot(t, {+ electronAPI: {+ getManagedEnterpriseConfig: async (a, w, g) => ({+ success: true,+ status: "network",+ accountId: a,+ workspaceId: w,+ authGeneration: g,+ config: azureSttRequired,+ }),+ },+ });+ await useEnterpriseIdentityStore.getState().refresh("account-a", "workspace-a", 1);+ assert.deepEqual(+ JSON.parse(globalThis.localStorage.getItem("managedEnterpriseScopes:account-a:workspace-a")),+ { managed: ["transcription"], enforced: ["transcription"] }+ );+ assert.deepEqual(useEnterpriseIdentityStore.getState().enforcedScopes, []);+ assert.deepEqual(useEnterpriseIdentityStore.getState().managedScopes, ["transcription"]);+});++test("a retry after an error holds the scopes carried in memory even with no persisted hint", async (t) => {+ let call = 0;+ const { useEnterpriseIdentityStore, getManagedScopeResolution } = await boot(t, {+ electronAPI: {+ getManagedEnterpriseConfig: (accountId, workspaceId, authGeneration) => {+ call += 1;+ if (call === 1) {+ return Promise.resolve({+ success: false,+ status: "error",+ accountId,+ workspaceId,+ authGeneration,+ code: "AUTH_EXPIRED",+ error: "expired",+ enforcementRequired: true,+ enforcedScopes: SCOPES,+ });+ }+ // The retry: never resolves, so the store stays in "loading" for the+ // duration of the assertions below.+ return new Promise(() => {});+ },+ },+ });++ // First fetch fails; nothing has ever been persisted for this identity.+ await useEnterpriseIdentityStore.getState().refresh("account-a", "workspace-a", 1);+ assert.equal(useEnterpriseIdentityStore.getState().status, "error");+ assert.deepEqual(useEnterpriseIdentityStore.getState().enforcedScopes, SCOPES);+ assert.equal(+ globalThis.localStorage.getItem("managedEnterpriseScopes:account-a:workspace-a"),+ null+ );++ // A retry for the same identity carries the in-memory enforcedScopes+ // forward into the "loading" window — it must not fail open just because+ // there is no persisted hint to fall back on.+ void useEnterpriseIdentityStore.getState().refresh("account-a", "workspace-a", 1);+ assert.equal(useEnterpriseIdentityStore.getState().status, "loading");+ assert.equal(useEnterpriseIdentityStore.getState().config, null);+ assert.equal(+ getManagedScopeResolution("dictationCleanup", "auto").code,+ "MANAGED_CONFIG_LOADING"+ );+ assert.equal(getManagedScopeResolution("transcription", "auto").kind, "manual");+});++test("the transcription opt-out is independent of the LLM setup mode", async (t) => {+ installBrowserGlobals(t, { initialStorage: { enterpriseSetupMode: "manual" } });+ const vite = await createRendererServer(t, { cachePrefix: "openwhispr-stt-setup-mode-" });+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");+ const { useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");+ const { useEnterpriseIdentityStore } = await vite.ssrLoadModule(+ "/stores/enterpriseIdentityStore.ts"+ );+ const { getManagedTranscriptionResolution } = await vite.ssrLoadModule(+ "/services/managedTranscription.ts"+ );+ usePolicyStore.setState({ status: "managed", appVersion: "1.10.0", policy });+ const sttDefault = structuredClone(azureSttRequired);+ sttDefault.providers[0].mode = "managed_default";+ sttDefault.providers[0].allowManualSetup = true;+ useEnterpriseIdentityStore.setState({+ accountId: "account-a",+ workspaceId: "workspace-a",+ authGeneration: 1,+ status: "ready",+ config: sttDefault,+ error: null,+ managedScopes: ["transcription"],+ enforcedScopes: [],+ });+ assert.equal(useSettingsStore.getState().enterpriseSetupMode, "manual");+ assert.equal(useSettingsStore.getState().enterpriseTranscriptionSetupMode, "auto");+ assert.equal(getManagedTranscriptionResolution()?.kind, "managed");+ useSettingsStore.getState().setEnterpriseTranscriptionSetupMode("manual");+ assert.equal(getManagedTranscriptionResolution(), undefined);+ assert.equal(useSettingsStore.getState().enterpriseSetupMode, "manual");+});++test("a cold start (status idle, no config yet) holds only the scopes a persisted hint enforces", async (t) => {+ const { useEnterpriseIdentityStore, getManagedScopeResolution } = await boot(t, {+ initialStorage: {+ "managedEnterpriseScopes:account-a:workspace-a": JSON.stringify({+ managed: ["transcription"],+ enforced: ["transcription"],+ }),+ },+ });+ // The window between app start (or a workspace switch) and the first+ // refresh() call resolving: the store's initial status is "idle", not+ // "loading", but the identity is already known (e.g. restored from a+ // prior session) and no config has arrived yet.+ useEnterpriseIdentityStore.setState({+ accountId: "account-a",+ workspaceId: "workspace-a",+ authGeneration: 1,+ });+ assert.equal(useEnterpriseIdentityStore.getState().status, "idle");+ assert.equal(useEnterpriseIdentityStore.getState().config, null);+ assert.equal(getManagedScopeResolution("transcription", "auto").code, "MANAGED_CONFIG_LOADING");+ assert.equal(getManagedScopeResolution("dictationCleanup", "auto").kind, "manual");+});++test("clear() never strands a signed-out user under a stale persisted hint", async (t) => {+ const { useEnterpriseIdentityStore, getManagedScopeResolution } = await boot(t, {+ initialStorage: {+ "managedEnterpriseScopes:account-a:workspace-a": JSON.stringify({+ managed: ["transcription"],+ enforced: ["transcription"],+ }),+ },+ electronAPI: {+ getManagedEnterpriseConfig: async (a, w, g) => ({+ success: true,+ status: "network",+ accountId: a,+ workspaceId: w,+ authGeneration: g,+ config: azureSttRequired,+ }),+ },+ });+ await useEnterpriseIdentityStore.getState().refresh("account-a", "workspace-a", 1);+ assert.equal(+ getManagedScopeResolution("transcription", "auto").kind,+ "managed",+ "sanity check: the workspace really does enforce transcription while signed in"+ );++ useEnterpriseIdentityStore.getState().clear();++ const state = useEnterpriseIdentityStore.getState();+ assert.equal(state.status, "idle");+ assert.equal(state.accountId, null);+ assert.equal(state.workspaceId, null);+ assert.equal(state.config, null);+ // No accountId/workspaceId means the persisted hint for account-a/workspace-a+ // can't be looked up, so a signed-out user is never held for someone else's+ // (or their own former) organization's enforcement.+ assert.equal(getManagedScopeResolution("transcription", "auto").kind, "manual");+ assert.equal(getManagedScopeResolution("dictationCleanup", "auto").kind, "manual");+});diff --git a/test/utils/managedAzureTranscriptionUrl.test.js b/test/utils/managedAzureTranscriptionUrl.test.jsnew file mode 100644index 000000000..60abc19a1--- /dev/null+++ b/test/utils/managedAzureTranscriptionUrl.test.js@@ -0,0 +1,49 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/utils/urlUtils.ts");++test("v1 and preview aliases use the deployments route with the dated transcription version", async () => {+ const { buildManagedAzureTranscriptionUrl } = await load();+ for (const apiVersion of ["v1", "preview"]) {+ assert.equal(+ buildManagedAzureTranscriptionUrl(+ "https://acme.services.ai.azure.com",+ "gpt-4o-transcribe",+ apiVersion+ ),+ "https://acme.services.ai.azure.com/openai/deployments/gpt-4o-transcribe/audio/transcriptions?api-version=2025-03-01-preview",+ apiVersion+ );+ }+});++test("dated versions pass through unchanged on the deployments route", async () => {+ const { buildManagedAzureTranscriptionUrl } = await load();+ assert.equal(+ buildManagedAzureTranscriptionUrl(+ "https://acme.openai.azure.com/",+ "gpt-4o-transcribe",+ "2025-03-01-preview"+ ),+ "https://acme.openai.azure.com/openai/deployments/gpt-4o-transcribe/audio/transcriptions?api-version=2025-03-01-preview"+ );+});++test("a dated version never lands on the /openai/v1/ route", async () => {+ const { buildManagedAzureTranscriptionUrl } = await load();+ for (const apiVersion of ["2025-03-01-preview", "2024-10-21"]) {+ const url = buildManagedAzureTranscriptionUrl(+ "https://acme.services.ai.azure.com",+ "gpt-4o-transcribe",+ apiVersion+ );+ assert.doesNotMatch(url, /\/openai\/v1\//, apiVersion);+ assert.match(url, /\/openai\/deployments\/gpt-4o-transcribe\//, apiVersion);+ }+});++test("an unparsable endpoint yields null", async () => {+ const { buildManagedAzureTranscriptionUrl } = await load();+ assert.equal(buildManagedAzureTranscriptionUrl("not a url", "d", "v1"), null);+});