Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(enterprise): honor existing provider setup and managed route precedence
Gabriel Stein7ed358d3a085
diff --git a/src/components/AuthenticationStep.tsx b/src/components/AuthenticationStep.tsxindex 35da2cc6d..179250fc9 100644--- a/src/components/AuthenticationStep.tsx+++ b/src/components/AuthenticationStep.tsx@@ -166,13 +166,10 @@ export default function AuthenticationStep({[t]);- const handleSSOSignIn = useCallback(async () => {- if (!email.trim()) {- setError(t("auth.sso.emailRequired"));- return;- }- await startSSOSignIn(email);- }, [email, startSSOSignIn, t]);+ const handleSSOSignIn = useCallback(+ () => startSSOSignIn(email),+ [email, startSSOSignIn]+ );const handleEmailContinue = useCallback(async () => {if (!email.trim() || !authClient) return;@@ -406,18 +403,12 @@ export default function AuthenticationStep({<div className="pb-1 text-center"><p className="mb-2 text-sm leading-tight text-muted-foreground/70">{email}</p><p className="text-lg font-semibold leading-tight tracking-tight text-foreground">- {t("auth.sso.companySignInTitle", { defaultValue: "Use your company sign-in" })}+ {t("auth.sso.companySignInTitle")}</p><p className="mt-1 text-xs leading-snug text-muted-foreground">{ssoDiscovery.required- ? t("auth.sso.requiredDescription", {- defaultValue: "{{domain}} requires SSO for OpenWhispr.",- domain: ssoDiscovery.domain,- })- : t("auth.sso.availableDescription", {- defaultValue: "Your {{domain}} account is ready for company SSO.",- domain: ssoDiscovery.domain,- })}+ ? t("auth.sso.requiredDescription", { domain: ssoDiscovery.domain })+ : t("auth.sso.availableDescription", { domain: ssoDiscovery.domain })}</p></div>@@ -449,7 +440,7 @@ export default function AuthenticationStep({setAuthMode(ssoDiscovery.exists ? "sign-in" : "sign-up");}}>- {t("auth.sso.useEmailInstead", { defaultValue: "Use email and password instead" })}+ {t("auth.sso.useEmailInstead")}</Button>)}diff --git a/src/components/settings/InferenceConfigEditor.tsx b/src/components/settings/InferenceConfigEditor.tsxindex f78719bea..d4e353240 100644--- a/src/components/settings/InferenceConfigEditor.tsx+++ b/src/components/settings/InferenceConfigEditor.tsx@@ -16,11 +16,13 @@ import OpenAICompatiblePanel from "../OpenAICompatiblePanel";import { Toggle } from "../ui/toggle";import type { InferenceMode } from "../../types/electron";import type { InferenceScope } from "../../config/inferenceScopes";-import { isProviderValidForMode, getCloudModel, getLocalModel } from "../../models/ModelRegistry";import {- useEnterpriseIdentityStore,- getManagedScopeResolution,-} from "../../stores/enterpriseIdentityStore";+ isProviderValidForMode,+ getCloudModel,+ getLocalModel,+ enterpriseProviderName,+} from "../../models/ModelRegistry";+import { useManagedScopeResolution } from "../../stores/enterpriseIdentityStore";import TestConnectionButton from "../TestConnectionButton";import { getEnterpriseCallSettings } from "../../services/ai/enterpriseSettings";import { Button } from "../ui/button";@@ -51,9 +53,8 @@ export default function InferenceConfigEditor({ scope, onModeChange }: Inferenceconst isSignedIn = useSettingsStore((s) => s.isSignedIn);const enterpriseSetupMode = useSettingsStore((s) => s.enterpriseSetupMode);const setEnterpriseSetupMode = useSettingsStore((s) => s.setEnterpriseSetupMode);- useEnterpriseIdentityStore(useShallow((s) => [s.status, s.config, s.error]));- const managed = getManagedScopeResolution(scope, enterpriseSetupMode);- const managedAvailable = getManagedScopeResolution(scope, "managed");+ const managed = useManagedScopeResolution(scope, enterpriseSetupMode);+ const managedAvailable = useManagedScopeResolution(scope, "managed");const prefix = MODE_LABEL_PREFIX[scope];const { modes, isModeAllowed } = usePolicyModeOptions<InferenceModeOption>(@@ -163,7 +164,9 @@ export default function InferenceConfigEditor({ scope, onModeChange }: Inference<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">Managed enterprise AI needs attention</p>+ <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></div></div>@@ -172,7 +175,6 @@ export default function InferenceConfigEditor({ scope, onModeChange }: Inference}if (managed.kind === "managed") {- const providerName = managed.provider === "bedrock" ? "Amazon Bedrock" : "Azure OpenAI";return (<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">@@ -180,13 +182,15 @@ export default function InferenceConfigEditor({ scope, onModeChange }: Inference<ShieldCheck className="h-4 w-4" /></div><div className="min-w-0 flex-1">- <p className="text-sm font-medium">Managed by your organization</p>+ <p className="text-sm font-medium">+ {t("settingsPage.aiModels.managedEnterprise.title")}+ </p><p className="mt-0.5 text-xs text-muted-foreground">- {providerName} · <span className="font-mono">{managed.model}</span>+ {enterpriseProviderName(managed.provider)} ·{" "}+ <span className="font-mono">{managed.model}</span></p><p className="mt-1 text-xs text-muted-foreground">- Sign-in supplies short-lived access automatically. No cloud keys or CLI setup are- required.+ {t("settingsPage.aiModels.managedEnterprise.description")}</p></div></div>@@ -205,7 +209,7 @@ export default function InferenceConfigEditor({ scope, onModeChange }: Inferencesize="sm"onClick={() => setEnterpriseSetupMode("manual")}>- Use personal setup+ {t("settingsPage.aiModels.managedEnterprise.usePersonalSetup")}</Button>)}</div>@@ -218,10 +222,13 @@ export default function InferenceConfigEditor({ scope, onModeChange }: Inference{enterpriseSetupMode === "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">Organization setup available</p>+ <p className="text-sm font-medium">+ {t("settingsPage.aiModels.managedEnterprise.availableTitle")}+ </p><p className="text-xs text-muted-foreground">- Use {managedAvailable.provider === "bedrock" ? "Amazon Bedrock" : "Azure OpenAI"}- without managing credentials.+ {t("settingsPage.aiModels.managedEnterprise.availableDescription", {+ provider: enterpriseProviderName(managedAvailable.provider),+ })}</p></div><Button@@ -231,7 +238,7 @@ export default function InferenceConfigEditor({ scope, onModeChange }: InferenceclassName="shrink-0"onClick={() => setEnterpriseSetupMode("managed")}>- Use managed+ {t("settingsPage.aiModels.managedEnterprise.useManaged")}</Button></div>)}diff --git a/src/helpers/enterpriseIdentityManager.js b/src/helpers/enterpriseIdentityManager.jsindex bbf12ef34..97e4da06c 100644--- a/src/helpers/enterpriseIdentityManager.js+++ b/src/helpers/enterpriseIdentityManager.js@@ -200,12 +200,12 @@ function createEnterpriseIdentityManager({return { config, status: "network" };}- async function resolveConfig(identity, forceRefresh = false) {+ async function resolveConfig(identity) {const current = configs.get(identity.cacheKey);- if (!forceRefresh && current && now() - current.refreshedAt < CONFIG_REFRESH_MS) {+ if (current && now() - current.refreshedAt < CONFIG_REFRESH_MS) {return { config: current.config, status: "current" };}- if (!forceRefresh && configRequests.has(identity.cacheKey)) {+ if (configRequests.has(identity.cacheKey)) {return configRequests.get(identity.cacheKey);}const pending = fetchConfig(identity)diff --git a/src/helpers/enterpriseManagedConfig.mjs b/src/helpers/enterpriseManagedConfig.mjsindex be4e4ee62..98b2c6a7a 100644--- a/src/helpers/enterpriseManagedConfig.mjs+++ b/src/helpers/enterpriseManagedConfig.mjs@@ -127,14 +127,13 @@ function resolveManagedEnterpriseScope(envelope, scope, setupMode = "auto") {);const candidates = enforced.length ? enforced : setupMode === "manual" ? [] : configured;if (!candidates.length) return { kind: "manual" };- if (candidates.length > 1) {- return resolutionError(- "MANAGED_PROVIDER_AMBIGUOUS",- "Your organization configured more than one managed provider for this feature. Contact your IT administrator."- );- }- const record = candidates[0];+ // The API allows one active provider per workspace, so more than one candidate only means a+ // cached envelope from before a switch. Take the newest rather than stranding the user: the+ // next config refresh reconciles it.+ const record = candidates.reduce((newest, candidate) =>+ candidate.updatedAt > newest.updatedAt ? candidate : newest+ );return {kind: "managed",provider: record.provider,diff --git a/src/helpers/enterpriseProviderErrors.js b/src/helpers/enterpriseProviderErrors.jsindex 28ca51f0a..5b12c7d89 100644--- a/src/helpers/enterpriseProviderErrors.js+++ b/src/helpers/enterpriseProviderErrors.js@@ -33,7 +33,6 @@ function mapManagedIdentityError(error, provider) {"PROVIDER_NOT_ALLOWED","PROVIDER_NOT_CONFIGURED","WORKSPACE_SUBSCRIPTION_REQUIRED",- "MANAGED_PROVIDER_AMBIGUOUS","MANAGED_CONFIG_INVALID",].includes(code)) {diff --git a/src/hooks/useAuth.ts b/src/hooks/useAuth.tsindex 6ef0e9f2f..e9763d0ea 100644--- a/src/hooks/useAuth.ts+++ b/src/hooks/useAuth.ts@@ -59,13 +59,8 @@ async function loadAccountDependencies() {}async function refreshManagedEnterpriseIdentity(accountId: string, authGeneration: number) {- const { useWorkspaceStore } = await import("../stores/workspaceStore");- const workspaceId = useWorkspaceStore.getState().activeWorkspaceId;- if (!workspaceId) {- useEnterpriseIdentityStore.getState().clear();- return;- }- await useEnterpriseIdentityStore.getState().refresh(accountId, workspaceId, authGeneration);+ const { refreshManagedEnterpriseIdentity: refresh } = await import("../stores/workspaceStore");+ refresh(accountId, authGeneration);}export function useAuth() {diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 2d586916b..5d491940d 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -796,7 +796,11 @@"sso": {"continueWithSSO": "Mit SSO anmelden","emailRequired": "Geben Sie Ihre geschäftliche E-Mail-Adresse ein, um SSO zu verwenden.",- "failed": "Single Sign-on fehlgeschlagen. Bitte versuchen Sie es erneut."+ "failed": "Single Sign-on fehlgeschlagen. Bitte versuchen Sie es erneut.",+ "companySignInTitle": "Unternehmensanmeldung verwenden",+ "requiredDescription": "{{domain}} erfordert SSO für OpenWhispr.",+ "availableDescription": "Ihr {{domain}}-Konto ist für das Unternehmens-SSO bereit.",+ "useEmailInstead": "Stattdessen E-Mail und Passwort verwenden"},"social": {"completeInBrowser": "Anmeldung im Browser abschließen",@@ -1735,6 +1739,15 @@"title": "Enterprise","description": "Verwendet das Cloud-Konto Ihrer Organisation."}+ },+ "managedEnterprise": {+ "errorTitle": "Verwaltete Unternehmens-KI erfordert Aufmerksamkeit",+ "title": "Von Ihrer Organisation verwaltet",+ "description": "Die Anmeldung stellt automatisch kurzlebigen Zugriff bereit. Cloud-Schlüssel oder CLI-Einrichtung sind nicht erforderlich.",+ "usePersonalSetup": "Persönliche Einrichtung verwenden",+ "availableTitle": "Einrichtung der Organisation verfügbar",+ "availableDescription": "{{provider}} ohne Verwaltung von Anmeldedaten nutzen.",+ "useManaged": "Verwaltet nutzen"}},"developer": {diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex da7ccaabf..2d469c310 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -796,7 +796,11 @@"sso": {"continueWithSSO": "Sign in with SSO","emailRequired": "Enter your work email to use SSO.",- "failed": "Single sign-on failed. Please try again."+ "failed": "Single sign-on failed. Please try again.",+ "companySignInTitle": "Use your company sign-in",+ "requiredDescription": "{{domain}} requires SSO for OpenWhispr.",+ "availableDescription": "Your {{domain}} account is ready for company SSO.",+ "useEmailInstead": "Use email and password instead"},"social": {"completeInBrowser": "Complete sign-in in your browser",@@ -1735,6 +1739,15 @@"title": "Enterprise","description": "Using your organization's cloud account."}+ },+ "managedEnterprise": {+ "errorTitle": "Managed enterprise AI needs attention",+ "title": "Managed by your organization",+ "description": "Sign-in supplies short-lived access automatically. No cloud keys or CLI setup are required.",+ "usePersonalSetup": "Use personal setup",+ "availableTitle": "Organization setup available",+ "availableDescription": "Use {{provider}} without managing credentials.",+ "useManaged": "Use managed"}},"developer": {diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 3e4e8a275..ff99f23e8 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -796,7 +796,11 @@"sso": {"continueWithSSO": "Iniciar sesión con SSO","emailRequired": "Introduce tu correo del trabajo para usar SSO.",- "failed": "Error al iniciar sesión con SSO. Inténtalo de nuevo."+ "failed": "Error al iniciar sesión con SSO. Inténtalo de nuevo.",+ "companySignInTitle": "Usa el inicio de sesión de tu empresa",+ "requiredDescription": "{{domain}} requiere SSO para OpenWhispr.",+ "availableDescription": "Tu cuenta de {{domain}} está lista para el SSO de la empresa.",+ "useEmailInstead": "Usar correo y contraseña en su lugar"},"social": {"completeInBrowser": "Completa el inicio de sesión en tu navegador",@@ -1505,6 +1509,15 @@"title": "Empresarial","description": "Usando la cuenta en la nube de tu organización."}+ },+ "managedEnterprise": {+ "errorTitle": "La IA empresarial gestionada requiere atención",+ "title": "Gestionado por tu organización",+ "description": "El inicio de sesión concede acceso temporal automáticamente. No hacen falta claves de nube ni configurar la CLI.",+ "usePersonalSetup": "Usar configuración personal",+ "availableTitle": "Configuración de la organización disponible",+ "availableDescription": "Usa {{provider}} sin gestionar credenciales.",+ "useManaged": "Usar gestionado"}},"developer": {diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex c4e7d5d5f..41ef0ac84 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -796,7 +796,11 @@"sso": {"continueWithSSO": "Se connecter avec le SSO","emailRequired": "Saisissez votre e-mail professionnel pour utiliser le SSO.",- "failed": "Échec de l’authentification unique. Veuillez réessayer."+ "failed": "Échec de l’authentification unique. Veuillez réessayer.",+ "companySignInTitle": "Utiliser la connexion de votre entreprise",+ "requiredDescription": "{{domain}} exige le SSO pour OpenWhispr.",+ "availableDescription": "Votre compte {{domain}} est prêt pour le SSO de l'entreprise.",+ "useEmailInstead": "Utiliser plutôt l'e-mail et le mot de passe"},"social": {"completeInBrowser": "Terminez la connexion dans votre navigateur",@@ -1735,6 +1739,15 @@"title": "Enterprise","description": "Utilise le compte cloud de votre organisation."}+ },+ "managedEnterprise": {+ "errorTitle": "L'IA d'entreprise gérée nécessite votre attention",+ "title": "Géré par votre organisation",+ "description": "La connexion fournit automatiquement un accès de courte durée. Aucune clé cloud ni configuration CLI n'est nécessaire.",+ "usePersonalSetup": "Utiliser la configuration personnelle",+ "availableTitle": "Configuration de l'organisation disponible",+ "availableDescription": "Utilisez {{provider}} sans gérer d'identifiants.",+ "useManaged": "Utiliser la version gérée"}},"developer": {diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex c51a6e51a..2542881e0 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -797,7 +797,11 @@"sso": {"continueWithSSO": "Accedi con SSO","emailRequired": "Inserisci la tua email di lavoro per usare l’SSO.",- "failed": "Accesso SSO non riuscito. Riprova."+ "failed": "Accesso SSO non riuscito. Riprova.",+ "companySignInTitle": "Usa l'accesso aziendale",+ "requiredDescription": "{{domain}} richiede l'SSO per OpenWhispr.",+ "availableDescription": "Il tuo account {{domain}} è pronto per l'SSO aziendale.",+ "useEmailInstead": "Usa invece e-mail e password"},"social": {"completeInBrowser": "Completa l'accesso nel browser",@@ -1457,6 +1461,15 @@"title": "Enterprise","description": "Usa l'account cloud della tua organizzazione."}+ },+ "managedEnterprise": {+ "errorTitle": "L'IA aziendale gestita richiede attenzione",+ "title": "Gestito dalla tua organizzazione",+ "description": "L'accesso fornisce automaticamente credenziali di breve durata. Non servono chiavi cloud né configurazione della CLI.",+ "usePersonalSetup": "Usa la configurazione personale",+ "availableTitle": "Configurazione dell'organizzazione disponibile",+ "availableDescription": "Usa {{provider}} senza gestire credenziali.",+ "useManaged": "Usa la versione gestita"}},"developer": {diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex 53cb259fc..d9232c7fd 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -797,7 +797,11 @@"sso": {"continueWithSSO": "SSO でサインイン","emailRequired": "SSO を使用するには勤務先のメールアドレスを入力してください。",- "failed": "シングルサインオンに失敗しました。もう一度お試しください。"+ "failed": "シングルサインオンに失敗しました。もう一度お試しください。",+ "companySignInTitle": "会社のサインインを使用",+ "requiredDescription": "{{domain}} では OpenWhispr に SSO が必須です。",+ "availableDescription": "{{domain}} のアカウントは会社の SSO に対応しています。",+ "useEmailInstead": "メールアドレスとパスワードを使用"},"social": {"completeInBrowser": "ブラウザでサインインを完了してください",@@ -1457,6 +1461,15 @@"title": "エンタープライズ","description": "組織のクラウドアカウントを使用しています。"}+ },+ "managedEnterprise": {+ "errorTitle": "マネージド エンタープライズ AI に対応が必要です",+ "title": "組織によって管理されています",+ "description": "サインインすると短期間のアクセスが自動的に付与されます。クラウドキーや CLI の設定は不要です。",+ "usePersonalSetup": "個人の設定を使用",+ "availableTitle": "組織の設定が利用できます",+ "availableDescription": "認証情報を管理せずに {{provider}} を使用できます。",+ "useManaged": "マネージドを使用"}},"developer": {diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex 94c0c7c25..06b7d5809 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -776,7 +776,11 @@"sso": {"continueWithSSO": "Entrar com SSO","emailRequired": "Insira seu e-mail corporativo para usar o SSO.",- "failed": "Falha no logon único. Tente novamente."+ "failed": "Falha no logon único. Tente novamente.",+ "companySignInTitle": "Usar o login da sua empresa",+ "requiredDescription": "{{domain}} exige SSO para o OpenWhispr.",+ "availableDescription": "A sua conta {{domain}} está pronta para o SSO da empresa.",+ "useEmailInstead": "Usar e-mail e senha em vez disso"},"social": {"completeInBrowser": "Conclua o login no navegador",@@ -1436,6 +1440,15 @@"title": "Corporativo","description": "Usando a conta de nuvem da sua organização."}+ },+ "managedEnterprise": {+ "errorTitle": "A IA empresarial gerenciada precisa de atenção",+ "title": "Gerenciado pela sua organização",+ "description": "O login fornece acesso de curta duração automaticamente. Não são necessárias chaves de nuvem nem configuração da CLI.",+ "usePersonalSetup": "Usar configuração pessoal",+ "availableTitle": "Configuração da organização disponível",+ "availableDescription": "Use {{provider}} sem gerenciar credenciais.",+ "useManaged": "Usar gerenciado"}},"developer": {diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 7466b0a3f..775cdab63 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -796,7 +796,11 @@"sso": {"continueWithSSO": "Войти через SSO","emailRequired": "Введите рабочий адрес электронной почты для использования SSO.",- "failed": "Не удалось выполнить единый вход. Повторите попытку."+ "failed": "Не удалось выполнить единый вход. Повторите попытку.",+ "companySignInTitle": "Войти через корпоративную учётную запись",+ "requiredDescription": "{{domain}} требует SSO для OpenWhispr.",+ "availableDescription": "Ваша учётная запись {{domain}} готова к корпоративному SSO.",+ "useEmailInstead": "Использовать эл. почту и пароль"},"social": {"completeInBrowser": "Завершите вход в браузере",@@ -1463,6 +1467,15 @@"title": "Корпоративный","description": "Используется облачный аккаунт вашей организации."}+ },+ "managedEnterprise": {+ "errorTitle": "Управляемый корпоративный ИИ требует внимания",+ "title": "Управляется вашей организацией",+ "description": "Вход автоматически выдаёт краткосрочный доступ. Облачные ключи и настройка CLI не нужны.",+ "usePersonalSetup": "Использовать личную настройку",+ "availableTitle": "Доступна настройка организации",+ "availableDescription": "Используйте {{provider}} без управления учётными данными.",+ "useManaged": "Использовать управляемый"}},"developer": {diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex b6c71a0a1..bb7648451 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -796,7 +796,11 @@"sso": {"continueWithSSO": "使用 SSO 登录","emailRequired": "输入您的工作邮箱以使用 SSO。",- "failed": "单点登录失败,请重试。"+ "failed": "单点登录失败,请重试。",+ "companySignInTitle": "使用公司登录",+ "requiredDescription": "{{domain}} 要求通过 SSO 登录 OpenWhispr。",+ "availableDescription": "您的 {{domain}} 账户已可使用公司 SSO。",+ "useEmailInstead": "改用邮箱和密码"},"social": {"completeInBrowser": "在浏览器中完成登录",@@ -1457,6 +1461,15 @@"title": "企业级","description": "正在使用你组织的云账号。"}+ },+ "managedEnterprise": {+ "errorTitle": "托管企业 AI 需要处理",+ "title": "由您的组织管理",+ "description": "登录后会自动获取短期访问权限,无需云密钥或 CLI 配置。",+ "usePersonalSetup": "使用个人配置",+ "availableTitle": "可使用组织配置",+ "availableDescription": "使用 {{provider}},无需管理凭据。",+ "useManaged": "使用托管配置"}},"developer": {diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex cf85d62ec..b9fe249d7 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -796,7 +796,11 @@"sso": {"continueWithSSO": "使用 SSO 登入","emailRequired": "輸入您的工作電子郵件以使用 SSO。",- "failed": "單一登入失敗,請再試一次。"+ "failed": "單一登入失敗,請再試一次。",+ "companySignInTitle": "使用公司登入",+ "requiredDescription": "{{domain}} 要求透過 SSO 登入 OpenWhispr。",+ "availableDescription": "您的 {{domain}} 帳戶已可使用公司 SSO。",+ "useEmailInstead": "改用電子郵件和密碼"},"social": {"completeInBrowser": "請在瀏覽器中完成登入",@@ -1457,6 +1461,15 @@"title": "企業級","description": "正在使用你組織的雲端帳號。"}+ },+ "managedEnterprise": {+ "errorTitle": "託管企業 AI 需要處理",+ "title": "由您的組織管理",+ "description": "登入後會自動取得短期存取權限,無需雲端金鑰或 CLI 設定。",+ "usePersonalSetup": "使用個人設定",+ "availableTitle": "可使用組織設定",+ "availableDescription": "使用 {{provider}},無需管理憑證。",+ "useManaged": "使用託管設定"}},"developer": {diff --git a/src/models/ModelRegistry.ts b/src/models/ModelRegistry.tsindex 130dc9fea..164a91c98 100644--- a/src/models/ModelRegistry.ts+++ b/src/models/ModelRegistry.ts@@ -242,6 +242,10 @@ export function isEnterpriseProvider(value: unknown): value is EnterpriseProvidereturn typeof value === "string" && (ENTERPRISE_PROVIDERS as readonly string[]).includes(value);}+export function enterpriseProviderName(provider: EnterpriseProvider): string {+ return modelRegistry.getEnterpriseProviders().find((p) => p.id === provider)?.name ?? provider;+}+export function toReasoningModel(m: CloudModelDefinition): ReasoningModel {return {value: m.id,diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.tsindex 3d09876c2..835b68879 100644--- a/src/services/ReasoningService.ts+++ b/src/services/ReasoningService.ts@@ -18,6 +18,7 @@ import { streamText, stepCountIs } from "ai";import { getAIModel } from "./ai/providers";import { createEnterpriseChatModel } from "./ai/enterpriseChatModel";import { getManagedScopeResolution } from "../stores/enterpriseIdentityStore";+import type { InferenceScope } from "../config/inferenceScopes";import { PROVIDER_REGISTRY, type ProviderContext } from "./ai/inferenceProviders";import { getConfiguredOpenAIBase } from "./ai/openaiBase";import { applyThinkingSuppression } from "./ai/thinkingSuppression";@@ -113,6 +114,35 @@ class ReasoningService extends BaseReasoningService {return settings.cleanupMode === "self-hosted" && !!settings.cleanupRemoteUrl;}+ // Managed enterprise access owns the route. Manual self-hosted and BYOK overrides are+ // dropped so a leftover endpoint or key can never outrank the administrator's provider.+ private resolveManagedScope<T extends ReasoningConfig, P extends string | undefined>(+ model: string,+ provider: P,+ config: T,+ fallbackScope: InferenceScope+ ): { 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 !== "managed") {+ return { model, provider, config: { ...config, inferenceScope }, isManaged: false };+ }+ return {+ model: managed.model,+ provider: managed.provider as P,+ config: {+ ...config,+ inferenceScope,+ provider: managed.provider,+ lanUrl: undefined,+ baseUrl: undefined,+ customApiKey: undefined,+ },+ isManaged: true,+ };+ }+private async getApiKey(provider:"openai" | "anthropic" | "gemini" | "groq" | "tinfoil" | "custom" | "openrouter" | "corti"@@ -364,15 +394,10 @@ class ReasoningService extends BaseReasoningService {agentName: string | null = null,config: ReasoningConfig = {}): Promise<string> {- const inferenceScope = config.inferenceScope || "dictationCleanup";- const managed = getManagedScopeResolution(inferenceScope, getSettings().enterpriseSetupMode);- if (managed.kind === "error") throw new Error(managed.message);- if (managed.kind === "managed") {- model = managed.model;- config = { ...config, provider: managed.provider, inferenceScope };- }+ const managed = this.resolveManagedScope(model, config.provider, config, "dictationCleanup");+ ({ model, config } = managed);const trimmedModel = model?.trim?.() || "";- const isLanCleanup = !!config.lanUrl || this.isLanCleanupMode();+ const isLanCleanup = !managed.isManaged && (!!config.lanUrl || this.isLanCleanupMode());const providerId = isLanCleanup? "lan": resolveInferenceProvider(config.provider, trimmedModel);@@ -641,14 +666,12 @@ class ReasoningService extends BaseReasoningService {config: ReasoningConfig & { systemPrompt: string },tools?: Record<string, import("ai").Tool>): AsyncGenerator<AgentStreamChunk, void, unknown> {- const inferenceScope = config.inferenceScope || "chatIntelligence";- const managed = getManagedScopeResolution(inferenceScope, getSettings().enterpriseSetupMode);- if (managed.kind === "error") throw new Error(managed.message);- if (managed.kind === "managed") {- provider = managed.provider;- model = managed.model;- config = { ...config, inferenceScope };- }+ ({ model, provider, config } = this.resolveManagedScope(+ model,+ provider,+ config,+ "chatIntelligence"+ ));const route = resolveChatRoute({provider,lanUrl: config.lanUrl,@@ -710,7 +733,7 @@ class ReasoningService extends BaseReasoningService {const openrouterDisableThinking = provider === "openrouter" && config.disableThinking === true;// Resolving a Tinfoil model refreshes the registry, so read model config after it.const aiModel = isEnterprise- ? createEnterpriseChatModel(provider as EnterpriseProvider, model, inferenceScope)+ ? createEnterpriseChatModel(provider as EnterpriseProvider, model, config.inferenceScope): await getAIModel(aiProvider, model, apiKey, baseURL, {disableThinking: openrouterDisableThinking,});@@ -968,6 +991,16 @@ class ReasoningService extends BaseReasoningService {async isAvailable(): Promise<boolean> {try {+ const settings = getSettings();+ // Mirrors processText's precedence: managed access outranks every manual route.+ if (+ getManagedScopeResolution("dictationCleanup", settings.enterpriseSetupMode).kind ===+ "managed"+ ) {+ logger.logReasoning("API_KEY_CHECK", { managedEnterprise: true });+ return true;+ }+if (isCloudCleanupMode()) {logger.logReasoning("API_KEY_CHECK", { cloudCleanupMode: true });return true;@@ -978,12 +1011,6 @@ class ReasoningService extends BaseReasoningService {return true;}- const settings = getSettings();- const managedCleanup = getManagedScopeResolution(- "dictationCleanup",- settings.enterpriseSetupMode- );- if (managedCleanup.kind === "managed") return true;if (settings.cleanupProvider === "custom" && settings.cleanupCloudBaseUrl?.trim()) {logger.logReasoning("API_KEY_CHECK", {customProvider: true,diff --git a/src/stores/enterpriseIdentityStore.ts b/src/stores/enterpriseIdentityStore.tsindex b90b1a4d5..5a7fcdbe8 100644--- a/src/stores/enterpriseIdentityStore.ts+++ b/src/stores/enterpriseIdentityStore.ts@@ -11,6 +11,8 @@ import type {import type { InferenceScope } from "../config/inferenceScopes";import logger from "../utils/logger";import { resolveManagedEnterpriseScope } from "../helpers/enterpriseManagedConfig.mjs";+import { isLlmSelectionAllowed } from "./policyRules";+import { usePolicyStore } from "./policyStore";interface EnterpriseIdentityState {accountId: string | null;@@ -103,13 +105,52 @@ export const useEnterpriseIdentityStore = create<EnterpriseIdentityState>((set,},}));-export function getManagedScopeResolution(+function resolveScope(+ config: ManagedEnterpriseConfig | null,scope: InferenceScope,setupMode: EnterpriseSetupMode): ManagedEnterpriseScopeResolution {- return resolveManagedEnterpriseScope(- useEnterpriseIdentityStore.getState().config,+ const resolution = resolveManagedEnterpriseScope(+ config,scope,setupMode) as ManagedEnterpriseScopeResolution;+ // Managed access and the provider allowlist are separate admin pages, so a workspace can end up+ // pointing at a provider its own policy forbids. Leave the employee on their own configuration+ // rather than failing every request on policy; policy still governs whatever they fall back to.+ if (+ resolution.kind === "managed" &&+ !isLlmSelectionAllowed(usePolicyStore.getState(), {+ mode: "enterprise",+ provider: resolution.provider,+ })+ ) {+ logger.warn(+ "Managed enterprise provider is blocked by workspace policy; using local configuration",+ { provider: resolution.provider, scope },+ "auth"+ );+ return { kind: "manual" };+ }+ return resolution;+}++/** Imperative reads (services, stores). Components should use useManagedScopeResolution. */+export function getManagedScopeResolution(+ scope: InferenceScope,+ setupMode: EnterpriseSetupMode+): ManagedEnterpriseScopeResolution {+ return resolveScope(useEnterpriseIdentityStore.getState().config, scope, setupMode);+}++/** Subscribes to the managed config so the UI re-renders when an administrator changes it. */+export function useManagedScopeResolution(+ scope: InferenceScope,+ setupMode: EnterpriseSetupMode+): ManagedEnterpriseScopeResolution {+ return resolveScope(+ useEnterpriseIdentityStore((state) => state.config),+ scope,+ setupMode+ );}diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex aa990e7aa..df133c486 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -1014,11 +1014,11 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({cleanupCustomApiKey: "",// Enterprise providers- enterpriseSetupMode: (["auto", "managed", "manual"].includes(- readString("enterpriseSetupMode", "auto")- )- ? readString("enterpriseSetupMode", "auto")- : "auto") as EnterpriseSetupMode,+ enterpriseSetupMode: (() => {+ const v = readString("enterpriseSetupMode", "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", ""),@@ -2337,14 +2337,20 @@ export async function initializeSettings(): Promise<void> {});if (!localStorage.getItem("enterpriseSetupMode")) {- const hasLegacyEnterpriseSetup = Boolean(- useSettingsStore.getState().bedrockProfile.trim() ||- (bedrockAccessKeyId && bedrockSecretAccessKey) ||- azureApiKey- );- const enterpriseSetupMode: EnterpriseSetupMode = hasLegacyEnterpriseSetup- ? "manual"- : "auto";+ // One-time migration. "Managed by default" is meant to equip employees who never chose a+ // provider — not to move someone who deliberately set up local, self-hosted, BYOK, or+ // enterprise inference. Anyone with an existing choice starts on "manual" and opts in.+ const hasChosenProvider =+ Object.values(INFERENCE_SCOPES).some((scope) => {+ const stored = localStorage.getItem(scope.storeKeys.mode as string);+ return Boolean(stored) && stored !== "openwhispr";+ }) ||+ Boolean(+ useSettingsStore.getState().bedrockProfile.trim() ||+ (bedrockAccessKeyId && bedrockSecretAccessKey) ||+ azureApiKey+ );+ const enterpriseSetupMode: EnterpriseSetupMode = hasChosenProvider ? "manual" : "auto";localStorage.setItem("enterpriseSetupMode", enterpriseSetupMode);useSettingsStore.setState({ enterpriseSetupMode });}diff --git a/src/stores/workspaceStore.ts b/src/stores/workspaceStore.tsindex be1294a4f..87154cfea 100644--- a/src/stores/workspaceStore.ts+++ b/src/stores/workspaceStore.ts@@ -37,21 +37,34 @@ let refreshPromise: Promise<void> | null = null;let membersRequestSeq = 0;let accountGeneration = 0;-function refreshManagedEnterpriseIdentity(workspaceId: string | null): void {+/**+ * Managed enterprise config is keyed by account + workspace + auth generation, so it has to be+ * re-resolved whenever any of the three changes. Callers that already know the account identity+ * pass it in; the active workspace comes from this store.+ */+export function refreshManagedEnterpriseIdentity(+ accountId: string | null,+ authGeneration: number | null,+ workspaceId: string | null = useWorkspaceStore.getState().activeWorkspaceId+): void {const enterprise = useEnterpriseIdentityStore.getState();- const policy = usePolicyStore.getState();- if (!workspaceId || !policy.accountId || policy.authGeneration == null) {+ if (!workspaceId || !accountId || authGeneration == null) {enterprise.clear();return;}if (enterprise.workspaceId !== workspaceId ||- enterprise.accountId !== policy.accountId ||- enterprise.authGeneration !== policy.authGeneration+ enterprise.accountId !== accountId ||+ enterprise.authGeneration !== authGeneration) {enterprise.clear();}- void enterprise.refresh(policy.accountId, workspaceId, policy.authGeneration);+ void enterprise.refresh(accountId, workspaceId, authGeneration);+}++function refreshForWorkspace(workspaceId: string | null): void {+ const { accountId, authGeneration } = usePolicyStore.getState();+ refreshManagedEnterpriseIdentity(accountId, authGeneration, workspaceId);}export const useWorkspaceStore = create<WorkspaceState>((set, get) => ({@@ -68,7 +81,7 @@ export const useWorkspaceStore = create<WorkspaceState>((set, get) => ({// land under the new one.membersRequestSeq++;set({ activeWorkspaceId: id, members: [] });- refreshManagedEnterpriseIdentity(id);+ refreshForWorkspace(id);},resetForAccountChange: () => {@@ -113,7 +126,7 @@ export const useWorkspaceStore = create<WorkspaceState>((set, get) => ({activeWorkspaceId: resolvedActiveId,});if (resolvedActiveId !== activeId) writeActiveWorkspaceId(resolvedActiveId);- refreshManagedEnterpriseIdentity(resolvedActiveId);+ refreshForWorkspace(resolvedActiveId);} catch (error) {if (generation !== accountGeneration) return;logger.error(diff --git a/test/helpers/enterpriseManagedConfig.test.js b/test/helpers/enterpriseManagedConfig.test.jsindex ce892de80..08ab2a63a 100644--- a/test/helpers/enterpriseManagedConfig.test.js+++ b/test/helpers/enterpriseManagedConfig.test.js@@ -121,9 +121,10 @@ test("required managed access overrides manual setup", () => {assert.equal(result.model, "model-a");});-test("ambiguous organization defaults fail with an administrator action", () => {+test("a cached envelope from before a provider switch resolves to the newest provider", () => {const azure = provider({provider: "azure",+ updatedAt: "2026-08-11T00:00:00.000Z",config: {tenantId: "11111111-1111-4111-8111-111111111111",clientId: "22222222-2222-4222-8222-222222222222",@@ -140,6 +141,7 @@ test("ambiguous organization defaults fail with an administrator action", () =>"dictationCleanup","auto");- assert.equal(result.kind, "error");- assert.equal(result.code, "MANAGED_PROVIDER_AMBIGUOUS");+ assert.equal(result.kind, "managed");+ assert.equal(result.provider, "azure");+ assert.equal(result.model, "deployment-a");});diff --git a/test/services/managedEnterpriseRouting.test.js b/test/services/managedEnterpriseRouting.test.jsnew file mode 100644index 000000000..91cef7970--- /dev/null+++ b/test/services/managedEnterpriseRouting.test.js@@ -0,0 +1,185 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++const enTranslations = require("../../src/locales/en/translation.json");++const REASONING_RESTRICTED = enTranslations.common.policyAiProcessingRestricted;++const SCOPES = [+ "dictationCleanup",+ "dictationAgent",+ "noteFormatting",+ "chatIntelligence",+ "dictationTranslation",+];++const MANAGED_MODEL = "anthropic.claude-sonnet-4-20250514-v1:0";++function managedBedrockConfig() {+ return {+ workspaceId: "workspace-a",+ version: 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: "bedrock",+ mode: "managed_required",+ allowManualSetup: false,+ config: {+ roleArn: "arn:aws:iam::123456789012:role/OpenWhispr",+ region: "us-east-1",+ allowedModels: [MANAGED_MODEL],+ scopeDefaults: Object.fromEntries(SCOPES.map((scope) => [scope, MANAGED_MODEL])),+ },+ version: 1,+ updatedAt: "2026-08-10T00:00:00.000Z",+ },+ ],+ };+}++function buildPolicy({ llmModes, llmEnterpriseProviders = [] }) {+ return {+ version: 1,+ transcription: { allowedModes: [], allowedByokProviders: [] },+ llm: {+ allowedModes: llmModes,+ allowedByokProviders: [],+ allowedEnterpriseProviders: llmEnterpriseProviders,+ },+ features: { agentEnabled: true, webSearchEnabled: false },+ sharing: { externalLinkSharing: "disabled" },+ dataRetention: {+ audioRetentionMaxDays: null,+ localHistoryMode: "user_choice",+ cloudBackupAllowed: false,+ },+ minAppVersion: null,+ };+}++// Regression: a self-hosted endpoint left over from before the administrator enabled managed+// access used to win the route, so prompts left through the employee's own server while the UI+// reported "Managed by your organization" — silently defeating managed_required.+test("managed enterprise access outranks a leftover self-hosted route", async (t) => {+ installBrowserGlobals(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-managed-routing-test-",+ });++ const reasoningService = (await vite.ssrLoadModule("/services/ReasoningService.ts")).default;+ t.after(() => reasoningService.destroy());+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");+ const { useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");+ const { useEnterpriseIdentityStore } = await vite.ssrLoadModule(+ "/stores/enterpriseIdentityStore.ts"+ );+ const { default: i18n } = await vite.ssrLoadModule("/i18n.ts");+ await i18n.changeLanguage("en");++ // The employee still has a self-hosted cleanup endpoint configured.+ useSettingsStore.setState({+ enterpriseSetupMode: "auto",+ cleanupMode: "self-hosted",+ cleanupRemoteUrl: "http://192.0.2.1:8080",+ });+ useEnterpriseIdentityStore.setState({+ accountId: "account-a",+ workspaceId: "workspace-a",+ authGeneration: 1,+ status: "ready",+ config: managedBedrockConfig(),+ error: null,+ });++ const setPolicy = (overrides) =>+ usePolicyStore.setState({+ status: "managed",+ appVersion: "1.8.1",+ policy: buildPolicy(overrides),+ });++ // An enterprise-only policy is the observation mechanism: it admits the managed route and+ // rejects the self-hosted one, so the outcome names the route that was chosen without ever+ // opening a socket.+ const enterpriseOnly = { llmModes: ["enterprise"], llmEnterpriseProviders: ["bedrock"] };++ await t.test("the stale self-hosted mode does not capture the route", async () => {+ setPolicy(enterpriseOnly);+ await assert.rejects(+ reasoningService.processText("hi", "", null, { inferenceScope: "dictationCleanup" }),+ (error) => error.message !== REASONING_RESTRICTED+ );+ });++ await t.test("an explicit per-call lanUrl does not capture the route either", async () => {+ setPolicy(enterpriseOnly);+ await assert.rejects(+ reasoningService.processText("hi", "", null, {+ inferenceScope: "noteFormatting",+ lanUrl: "http://192.0.2.9:9090",+ }),+ (error) => error.message !== REASONING_RESTRICTED+ );+ });++ await t.test("without managed access the self-hosted route still wins", async () => {+ useEnterpriseIdentityStore.setState({ config: null, status: "idle" });+ setPolicy(enterpriseOnly);+ await assert.rejects(+ reasoningService.processText("hi", "", null, { inferenceScope: "dictationCleanup" }),+ { message: REASONING_RESTRICTED }+ );+ });+});++// Managed access and the enterprise provider allowlist are configured on separate admin pages.+// If they disagree, employees must keep working on their own setup rather than have every+// request rejected by the workspace's own policy.+test("a managed provider that workspace policy forbids falls back to the employee's setup", async (t) => {+ installBrowserGlobals(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-managed-policy-gate-test-",+ });++ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");+ const { useSettingsStore, selectResolvedLLMConfig } = await vite.ssrLoadModule(+ "/stores/settingsStore.ts"+ );+ const { useEnterpriseIdentityStore } = await vite.ssrLoadModule(+ "/stores/enterpriseIdentityStore.ts"+ );++ useSettingsStore.setState({+ enterpriseSetupMode: "auto",+ cleanupMode: "local",+ cleanupProvider: "local",+ cleanupModel: "qwen-local",+ });+ useEnterpriseIdentityStore.setState({ status: "ready", config: managedBedrockConfig() });++ const resolvedMode = () =>+ selectResolvedLLMConfig(useSettingsStore.getState(), "dictationCleanup");++ usePolicyStore.setState({+ status: "managed",+ appVersion: "1.8.1",+ policy: buildPolicy({ llmModes: ["enterprise"], llmEnterpriseProviders: ["bedrock"] }),+ });+ assert.equal(resolvedMode().provider, "bedrock", "allowed managed provider applies");++ usePolicyStore.setState({+ status: "managed",+ appVersion: "1.8.1",+ policy: buildPolicy({ llmModes: ["local"], llmEnterpriseProviders: [] }),+ });+ const fallback = resolvedMode();+ assert.equal(fallback.mode, "local", "forbidden managed provider leaves the local mode intact");+ assert.equal(fallback.model, "qwen-local");+});