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(policy): Enforce org-required local model downloads (#1836)
Chad Piha409bc28d35ba
diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsxindex 5876e5a0d..690ad13e6 100644--- a/src/components/ControlPanel.tsx+++ b/src/components/ControlPanel.tsx@@ -14,6 +14,7 @@ import {} from "lucide-react";import UpgradePrompt from "./UpgradePrompt";import PostMigrationOnboarding from "./PostMigrationOnboarding";+import { RequiredModelsBanner } from "./RequiredModelsBanner";import { ConfirmDialog, AlertDialog } from "./ui/dialog";import { useDialogs } from "../hooks/useDialogs";import { useHotkey } from "../hooks/useHotkey";@@ -1099,6 +1100,7 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro</div></div>)}+ <RequiredModelsBanner />{usage?.isPastDue && activeView === "home" && (<div className="max-w-3xl mx-auto w-full mb-3"><div className="rounded-lg border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-950/50 p-3">diff --git a/src/components/OnboardingFlow.tsx b/src/components/OnboardingFlow.tsxindex 99a05240b..a3cc66dc9 100644--- a/src/components/OnboardingFlow.tsx+++ b/src/components/OnboardingFlow.tsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { AlertCircle } from "lucide-react";import { CompactAuthenticationFlow } from "./CompactAuthenticationFlow";@@ -13,6 +13,7 @@ import DemoStep from "./onboarding/DemoStep";import CalendarConnectionsStep from "./onboarding/CalendarConnectionsStep";import SetupChoiceStep from "./onboarding/SetupChoiceStep";import { ByokProviderStep, LocalModelSetupStep } from "./onboarding/ProviderSetupStep";+import { RequiredModelDownloadStep } from "./onboarding/RequiredModelDownloadStep";import { AlertDialog } from "./ui/dialog";import { useAuth } from "../hooks/useAuth";import { usePermissions } from "../hooks/usePermissions";@@ -23,6 +24,7 @@ import { useLocalStorage } from "../hooks/useLocalStorage";import { useHotkeyRegistration } from "../hooks/useHotkeyRegistration";import { useHotkeyModeInfo } from "../hooks/useHotkeyModeInfo";import { useWorkspace } from "../hooks/useWorkspace";+import { useRequiredLocalModels } from "../hooks/useRequiredLocalModels";import { usePolicyStore } from "../stores/policyStore";import { isAgentAllowed } from "../stores/policyRules";import { useSettingsStore } from "../stores/settingsStore";@@ -167,19 +169,55 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {(!workspacesLoaded ||(!activeWorkspace && skipSetupChoiceForEnterprise && Boolean(enterpriseWorkspace)));+ const requiredModels = useRequiredLocalModels();+ // Latched for the session once the step is entered (or resumed at), so a+ // mid-download policy refresh or the disk check settling can't rebuild the+ // route out from under the user. Seeded from the persisted session because+ // relaunching mid-download must resume on the step, not bounce off it while+ // the disk check is still pending.+ const requiredModelsLatchRef = useRef(session.currentStepId === "required-models");+ const requiredModelsPending = requiredModelsLatchRef.current || requiredModels.missing.length > 0;+const route = useMemo(() =>getOnboardingRoute({authPath: session.authPath,setupMode: session.setupMode,agentAllowed,+ requiredModelsPending,skipSetupChoice: skipSetupChoiceForEnterprise,}),- [agentAllowed, session.authPath, session.setupMode, skipSetupChoiceForEnterprise]+ [+ agentAllowed,+ requiredModelsPending,+ session.authPath,+ session.setupMode,+ skipSetupChoiceForEnterprise,+ ]);const currentStepId = reconcileStepWithRoute(session.currentStepId, route);const compact = COMPACT_STEPS.has(currentStepId);+ useEffect(() => {+ if (currentStepId === "required-models") requiredModelsLatchRef.current = true;+ }, [currentStepId]);++ // The auth step lands on "permissions" before the policy and disk checks+ // settle (AppRouter's policy gate remounts this component mid-transition),+ // so a persisted session can sit one step past the gate when the pending+ // flag arrives. Pull the user back — only from permissions, the immediate+ // post-auth screen, and only before the step was entered this session.+ useEffect(() => {+ if (+ requiredModelsPending &&+ currentStepId === "permissions" &&+ !requiredModelsLatchRef.current &&+ route.includes("required-models")+ ) {+ goTo("required-models");+ }+ }, [currentStepId, goTo, requiredModelsPending, route]);+useEffect(() => {if (session.currentStepId !== currentStepId) {setSession((current) => ({ ...current, currentStepId }));@@ -418,6 +456,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {authPath: session.authPath,setupMode: mode,agentAllowed,+ requiredModelsPending,});const next = getNextOnboardingStep("setup-choice", nextRoute);if (next) goTo(next);@@ -426,6 +465,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {agentAllowed,finalizeOnboarding,goTo,+ requiredModelsPending,session.authPath,setSelfHostedRequested,setSetupMode,@@ -532,6 +572,8 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {const canContinue = (() => {switch (currentStepId) {+ case "required-models":+ return !requiredModels.loading && requiredModels.missing.length === 0;case "permissions":return areRequiredPermissionsMet(permissions.micPermissionGranted);case "languages":@@ -581,6 +623,27 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {</div>);+ case "required-models":+ return (+ <div className="h-full w-full pt-2">+ <OnboardingStepHeader+ title={t("onboarding.requiredModels.title")}+ wideTitle+ description={t("onboarding.requiredModels.description", {+ organization:+ activeWorkspace?.name ?? t("onboarding.requiredModels.genericOrganization"),+ })}+ />+ <RequiredModelDownloadStep+ required={requiredModels.required}+ missing={requiredModels.missing}+ loading={requiredModels.loading}+ refresh={requiredModels.refresh}+ onProceed={() => void continueFromCurrentStep()}+ />+ </div>+ );+case "permissions":return (<CompactPermissionsStep@@ -931,7 +994,13 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {stepKey={currentStepId}// History is the only Back gate. This preserves the branch's provider// escape path and also lets users return from setup choice/languages.- onBack={hasShellNavigation && session.history.length > 0 ? goBack : undefined}+ // The required-models step is the exception: it is an org-mandated+ // blocker, so backing out of it (to auth) is suppressed.+ onBack={+ hasShellNavigation && session.history.length > 0 && currentStepId !== "required-models"+ ? goBack+ : undefined+ }onContinue={showsContinue ? () => void continueFromCurrentStep() : undefined}// The demos are practice, not configuration — a mic problem or an// unreachable transcription backend must never dead-end setup, so theydiff --git a/src/components/RequiredModelsBanner.tsx b/src/components/RequiredModelsBanner.tsxnew file mode 100644index 000000000..2c2c65a91--- /dev/null+++ b/src/components/RequiredModelsBanner.tsx@@ -0,0 +1,96 @@+import { useCallback, useMemo, useState } from "react";+import { AlertTriangle } from "lucide-react";+import { useTranslation } from "react-i18next";+import { Button } from "./ui/button";+import { DownloadProgressBar } from "./ui/DownloadProgressBar";+import { useModelDownload } from "../hooks/useModelDownload";+import { useRequiredLocalModels } from "../hooks/useRequiredLocalModels";+import { getParakeetModels, getWhisperModels } from "../models/ModelRegistry";++/**+ * Non-dismissable amber banner for managed users missing org-required local+ * models after onboarding (the admin added a requirement later, or the user+ * deleted a required model). Mirrors the update-required banner; disk truth+ * makes it disappear as soon as every required model is installed and return+ * if one goes missing again. Deliberately a nag surface, not a hard block.+ */+export function RequiredModelsBanner() {+ const { t } = useTranslation();+ const { missing, loading, refresh } = useRequiredLocalModels();+ const whisperDownload = useModelDownload({ modelType: "whisper", onDownloadComplete: refresh });+ const parakeetDownload = useModelDownload({ modelType: "parakeet", onDownloadComplete: refresh });+ const [downloadingAll, setDownloadingAll] = useState(false);++ const parakeetCatalog = getParakeetModels();+ const whisperCatalog = getWhisperModels();+ const missingNames = useMemo(+ () =>+ missing+ .map((modelId) => (parakeetCatalog[modelId] ?? whisperCatalog[modelId])?.name ?? modelId)+ .join(", "),+ [missing, parakeetCatalog, whisperCatalog]+ );++ const downloadMissing = useCallback(async () => {+ setDownloadingAll(true);+ try {+ // Sequential on purpose: the per-family managers reject concurrent+ // downloads, and downloadModel resolves only once its download settles.+ // Failures surface through the hook's alert dialog and leave the model+ // missing, so the banner (and this button) stick around for a retry.+ for (const modelId of missing) {+ const download = modelId in parakeetCatalog ? parakeetDownload : whisperDownload;+ await download.downloadModel(modelId);+ }+ } finally {+ setDownloadingAll(false);+ }+ }, [missing, parakeetCatalog, parakeetDownload, whisperDownload]);++ if (loading || missing.length === 0) return null;++ const activeDownload = parakeetDownload.isDownloading ? parakeetDownload : whisperDownload;+ const activeModelName = activeDownload.downloadingModel+ ? ((+ parakeetCatalog[activeDownload.downloadingModel] ??+ whisperCatalog[activeDownload.downloadingModel]+ )?.name ?? activeDownload.downloadingModel)+ : null;++ return (+ <div className="max-w-3xl mx-auto w-full mb-3">+ <div className="rounded-lg border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-950/50 p-3">+ <div className="flex items-start gap-3">+ <div className="shrink-0 w-8 h-8 rounded-md bg-amber-100 dark:bg-amber-900/50 flex items-center justify-center">+ <AlertTriangle size={16} className="text-amber-600 dark:text-amber-400" />+ </div>+ <div className="flex-1 min-w-0">+ <p className="text-xs font-medium text-amber-900 dark:text-amber-200 mb-0.5">+ {t("controlPanel.requiredModelsByOrg.title")}+ </p>+ <p className="text-xs text-amber-700 dark:text-amber-300/80 mb-2">+ {t("controlPanel.requiredModelsByOrg.description", { models: missingNames })}+ </p>+ {activeDownload.isDownloading && activeModelName ? (+ <DownloadProgressBar+ modelName={activeModelName}+ progress={activeDownload.downloadProgress}+ isInstalling={activeDownload.isInstalling}+ />+ ) : (+ <Button+ variant="default"+ size="sm"+ className="h-7 text-xs"+ disabled={downloadingAll}+ onClick={() => void downloadMissing()}+ >+ {t("controlPanel.requiredModelsByOrg.download")}+ </Button>+ )}+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/src/components/onboarding/BackgroundModelDownloadTray.tsx b/src/components/onboarding/BackgroundModelDownloadTray.tsxindex e90ad7d96..b17c3f7fe 100644--- a/src/components/onboarding/BackgroundModelDownloadTray.tsx+++ b/src/components/onboarding/BackgroundModelDownloadTray.tsx@@ -23,6 +23,7 @@ import type {WhisperDownloadProgressData,} from "../../types/electron";import { mergeHydratedDownloads } from "./localDownloadState";+import { ONBOARDING_SESSION_KEY, isRequiredModelsOnboardingStepActive } from "./flow";type DownloadKind = "whisper" | "parakeet" | "llm";@@ -226,6 +227,17 @@ export default function BackgroundModelDownloadTray() {percentage: number | undefined;error?: string;}) => {+ // The required-models onboarding step owns its downloads: it renders its+ // own per-row progress, and cancelling from here cannot stick because the+ // step auto-restarts org-mandated downloads. Suppress row creation while+ // that step is active; completions still pass so any pre-existing row+ // (a resumed local-setup download) can clear and activate normally.+ if (+ event.type !== "complete" &&+ isRequiredModelsOnboardingStepActive(localStorage.getItem(ONBOARDING_SESSION_KEY))+ ) {+ return;+ }const key = downloadKey(event.kind, event.id);const cancelledAt = cancelledKeys.current.get(key);if (cancelledAt !== undefined && event.type !== "complete") {diff --git a/src/components/onboarding/ProviderSetupStep.tsx b/src/components/onboarding/ProviderSetupStep.tsxindex 66b17938a..7b83ae897 100644--- a/src/components/onboarding/ProviderSetupStep.tsx+++ b/src/components/onboarding/ProviderSetupStep.tsx@@ -130,7 +130,7 @@ function StepSecondaryAction({}/** The card each setup mode's step renders into. Top margin is per call site. */-const SETUP_CARD_CLASS =+export const SETUP_CARD_CLASS ="mx-auto w-full max-w-[22rem] rounded-[1.125rem] border border-[var(--onboarding-control-border)] bg-[var(--onboarding-surface)] px-3 py-4 text-[var(--onboarding-text-primary)]";/** The field trigger. Call sites that can be disabled add the disabled: variants. */diff --git a/src/components/onboarding/RequiredModelDownloadStep.tsx b/src/components/onboarding/RequiredModelDownloadStep.tsxnew file mode 100644index 000000000..148e95d9e--- /dev/null+++ b/src/components/onboarding/RequiredModelDownloadStep.tsx@@ -0,0 +1,198 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { AlertCircle, Check } from "lucide-react";+import { useTranslation } from "react-i18next";+import { Button } from "../ui/button";+import { ProviderIcon } from "../ui/ProviderIcon";+import { useModelDownload } from "../../hooks/useModelDownload";+import { getParakeetModels, getWhisperModels } from "../../models/ModelRegistry";+import { SETUP_CARD_CLASS } from "./ProviderSetupStep";++type ModelFamily = "whisper" | "parakeet";++interface RequiredModelDownloadStepProps {+ /** Org-required registry ids, from useRequiredLocalModels. */+ required: string[];+ missing: string[];+ loading: boolean;+ refresh: () => Promise<void>;+ onProceed: () => void;+}++/**+ * The blocking download checklist for org-required local models. Downloads+ * auto-start sequentially (the per-family managers reject concurrency) and the+ * container's Continue enables only when every required model is on disk.+ * Deliberately does NOT write pendingLocalModels/localSetupPending: that+ * machinery lets users leave mid-download, the exact behavior this step+ * prevents. Back and Skip are suppressed by the container.+ */+export function RequiredModelDownloadStep({+ required,+ missing,+ loading,+ refresh,+ onProceed,+}: RequiredModelDownloadStepProps) {+ const { t } = useTranslation();+ const whisperCatalog = getWhisperModels();+ const parakeetCatalog = getParakeetModels();++ const whisperDownload = useModelDownload({ modelType: "whisper", onDownloadComplete: refresh });+ const parakeetDownload = useModelDownload({ modelType: "parakeet", onDownloadComplete: refresh });++ const [failedModels, setFailedModels] = useState<Record<string, string>>({});+ const lastStartedRef = useRef<{ family: ModelFamily; id: string } | null>(null);+ const startedAnyRef = useRef(false);+ const autoAdvancedRef = useRef(false);++ const familyOf = useCallback(+ (modelId: string): ModelFamily => (modelId in parakeetCatalog ? "parakeet" : "whisper"),+ [parakeetCatalog]+ );+ const missingSet = useMemo(() => new Set(missing), [missing]);+ const anyDownloadActive = whisperDownload.isDownloading || parakeetDownload.isDownloading;++ // useModelDownload clears its downloading state on error, so the failing+ // model id has to be remembered here to pin the error to its row.+ useEffect(() => {+ const last = lastStartedRef.current;+ if (!last) return;+ const error =+ last.family === "whisper" ? whisperDownload.downloadError : parakeetDownload.downloadError;+ if (!error) return;+ setFailedModels((current) =>+ current[last.id] === error ? current : { ...current, [last.id]: error }+ );+ }, [whisperDownload.downloadError, parakeetDownload.downloadError]);++ const startDownload = useCallback(+ (modelId: string) => {+ startedAnyRef.current = true;+ setFailedModels((current) => {+ if (!(modelId in current)) return current;+ const next = { ...current };+ delete next[modelId];+ return next;+ });+ const family = familyOf(modelId);+ lastStartedRef.current = { family, id: modelId };+ const download = family === "parakeet" ? parakeetDownload : whisperDownload;+ void download.downloadModel(modelId);+ },+ [familyOf, parakeetDownload, whisperDownload]+ );++ // Sequential auto-start: kick off the next missing model whenever nothing is+ // downloading. Rows that already failed wait for an explicit Retry.+ useEffect(() => {+ if (loading || anyDownloadActive) return;+ const next = missing.find((modelId) => !failedModels[modelId]);+ if (next) startDownload(next);+ }, [loading, anyDownloadActive, missing, failedModels, startDownload]);++ // The route raced a completed download (or the requirement was lifted) and+ // everything is already on disk: continue instead of showing a stale+ // blocking screen. Only before any download ran here — after one, the user+ // sees the completed checklist and continues themselves.+ useEffect(() => {+ if (autoAdvancedRef.current || startedAnyRef.current) return;+ if (!loading && missing.length === 0) {+ autoAdvancedRef.current = true;+ onProceed();+ }+ }, [loading, missing, onProceed]);++ const hasFailures = Object.keys(failedModels).length > 0;++ return (+ <section className={`mt-5 ${SETUP_CARD_CLASS}`}>+ <div className="onboarding-scroll-hidden max-h-72 overflow-y-auto rounded-2xl border border-[var(--onboarding-control-border)] bg-[var(--onboarding-surface-secondary)] px-3">+ {required.map((modelId) => {+ const family = familyOf(modelId);+ const info = family === "parakeet" ? parakeetCatalog[modelId] : whisperCatalog[modelId];+ const download = family === "parakeet" ? parakeetDownload : whisperDownload;+ const isDownloading = download.isDownloadingModel(modelId);+ const failure = failedModels[modelId];+ const installed = !loading && !missingSet.has(modelId) && !isDownloading;+ const percentage = Math.round(download.downloadProgress.percentage);++ return (+ <div+ key={modelId}+ className="flex min-h-14 items-center gap-3 border-b border-[var(--onboarding-control-border)] px-1 py-2 last:border-b-0"+ >+ <span className="flex size-9 shrink-0 items-center justify-center rounded-xl border border-[var(--onboarding-control-border)] bg-[var(--onboarding-surface)]">+ <ProviderIcon+ provider={family === "parakeet" ? "nvidia" : "openai"}+ className="size-5"+ />+ </span>+ <div className="min-w-0 flex-1 text-left">+ <span className="block truncate text-sm font-medium text-[var(--onboarding-text-primary)]">+ {info?.name ?? modelId}+ </span>+ {failure ? (+ <span className="mt-0.5 block truncate text-xs text-destructive">{failure}</span>+ ) : (+ <span className="mt-0.5 block truncate text-xs text-[var(--onboarding-text-secondary)]">+ {info?.size?.replace(/(?<=\d)(?=[A-Za-z])/, " ") ?? ""}+ </span>+ )}+ </div>++ {isDownloading ? (+ <span className="relative -mr-2 flex shrink-0 items-center gap-2 overflow-hidden rounded-[38px] border border-[var(--onboarding-control-border)] bg-[var(--onboarding-surface)] px-3 py-1.5 text-sm font-medium leading-[1.4] text-[var(--onboarding-text-secondary)]">+ <span+ className="absolute inset-y-0 left-0 bg-[var(--onboarding-surface-tertiary)] transition-[width] duration-300 ease-out"+ style={{ width: `${percentage}%` }}+ aria-hidden="true"+ />+ <span className="relative">{percentage}%</span>+ <span className="relative whitespace-nowrap">+ {download.isInstalling+ ? t("onboarding.rehaul.local.installing")+ : t("onboarding.rehaul.local.downloadingShort")}+ </span>+ </span>+ ) : failure ? (+ <Button+ type="button"+ onClick={() => startDownload(modelId)}+ className="-mr-2 h-7 gap-1.5 rounded-full border-0! bg-[var(--onboarding-accent)] px-2.5 text-xs font-normal text-[var(--onboarding-accent-foreground)] shadow-none! hover:bg-[var(--onboarding-accent-hover)] hover:shadow-none!"+ >+ {t("common.retry")}+ </Button>+ ) : installed ? (+ <span className="-mr-2 flex h-7 shrink-0 items-center gap-1 rounded-full bg-[var(--onboarding-accent)] px-3 text-xs text-[var(--onboarding-accent-foreground)]">+ <Check className="size-3.5" />+ {t("onboarding.requiredModels.installed")}+ </span>+ ) : (+ <span className="-mr-2 shrink-0 text-xs text-[var(--onboarding-text-secondary)]">+ {t("onboarding.requiredModels.queued")}+ </span>+ )}+ </div>+ );+ })}+ </div>++ {hasFailures && (+ <div+ role="alert"+ className="mt-3 flex w-full flex-col items-center rounded-2xl border border-[var(--onboarding-control-border)] bg-[var(--onboarding-surface)] px-4 py-5 text-center"+ >+ <span className="flex size-10 items-center justify-center rounded-full bg-[var(--onboarding-surface-secondary)] text-[var(--onboarding-accent)]">+ <AlertCircle className="size-5" />+ </span>+ <h2 className="mt-3 text-sm font-semibold text-[var(--onboarding-text-primary)]">+ {t("onboarding.requiredModels.failed.title")}+ </h2>+ <p className="mt-1.5 text-xs leading-5 text-[var(--onboarding-text-secondary)]">+ {t("onboarding.requiredModels.failed.description")}+ </p>+ </div>+ )}+ </section>+ );+}diff --git a/src/components/onboarding/flow.ts b/src/components/onboarding/flow.tsindex 5371e184b..e2591eaef 100644--- a/src/components/onboarding/flow.ts+++ b/src/components/onboarding/flow.ts@@ -6,6 +6,7 @@ type OnboardingStorage = Pick<Storage, "setItem" | "removeItem">;export type OnboardingStepId =| "auth"+ | "required-models"| "permissions"| "languages"| "use-cases"@@ -37,6 +38,13 @@ export interface OnboardingRouteContext {authPath: OnboardingAuthPath;setupMode: OnboardingSetupMode;agentAllowed: boolean;+ /**+ * Org-required local models are missing on disk. Inserts the blocking+ * "required-models" step right after auth — account path only, since guests+ * never fetch a policy. Callers latch this once the step is entered so a+ * mid-download policy refresh can't yank the step from under the user.+ */+ requiredModelsPending?: boolean;/** A confirmed Enterprise workspace is already provisioned outside onboarding. */skipSetupChoice?: boolean;}@@ -60,6 +68,7 @@ const SETUP_ROUTES: Record<Exclude<OnboardingSetupMode, null | "cloud">, Onboard// it to clamp backwards instead of jumping to the end of the route.const STEP_ORDER: OnboardingStepId[] = ["auth",+ "required-models","permissions","languages","use-cases",@@ -151,6 +160,10 @@ export function getOnboardingRoute(context: OnboardingRouteContext): OnboardingS...setupChoice,];+ if (context.requiredModelsPending && context.authPath === "account") {+ route.splice(route.indexOf("auth") + 1, 0, "required-models");+ }+if (context.setupMode && context.setupMode !== "cloud") {route.push(...SETUP_ROUTES[context.setupMode].filter(@@ -210,6 +223,17 @@ export function parseOnboardingSession(value: string | null): OnboardingSession}}+/**+ * True while a persisted onboarding session sits on the blocking+ * required-models step. The background download tray uses this to keep its+ * hands off downloads that step owns: a tray row would duplicate the step's+ * own progress pill, and the tray's cancel cannot stick — the step+ * auto-restarts org-mandated downloads.+ */+export function isRequiredModelsOnboardingStepActive(sessionValue: string | null): boolean {+ return parseOnboardingSession(sessionValue)?.currentStepId === "required-models";+}+export function migrateLegacyOnboardingStep(value: string | null): OnboardingStepId {if (!value) return "auth";if (isOnboardingStepId(value)) return value;diff --git a/src/helpers/policyValidation.js b/src/helpers/policyValidation.jsindex 5f9d065c5..0e25458b7 100644--- a/src/helpers/policyValidation.js+++ b/src/helpers/policyValidation.js@@ -47,6 +47,12 @@ function isValidPolicyShape(policy) {(policy.dataRetention?.audioRetentionMaxDays === null ||(Number.isSafeInteger(policy.dataRetention?.audioRetentionMaxDays) &&policy.dataRetention.audioRetentionMaxDays > 0)) &&+ // Shape-only on purpose: a future model id added server-side must not make+ // an older app discard the entire managed policy. Unknown ids are filtered+ // at enforcement time instead (see policyRules.requiredLocalModelIds).+ (policy.requiredLocalModels === undefined ||+ (Array.isArray(policy.requiredLocalModels) &&+ policy.requiredLocalModels.every((item) => typeof item === "string"))) &&(policy.minAppVersion === null || isCanonicalAppVersion(policy.minAppVersion)));}diff --git a/src/hooks/useModelDownload.ts b/src/hooks/useModelDownload.tsindex 344613172..ae85f424e 100644--- a/src/hooks/useModelDownload.ts+++ b/src/hooks/useModelDownload.ts@@ -15,6 +15,17 @@ import "../types/electron";const PROGRESS_THROTTLE_MS = 100;+/**+ * Fired on this window whenever a local model lands on or leaves the disk+ * (download complete, model deleted), so surfaces that mirror disk truth+ * without owning the download — e.g. useRequiredLocalModels — can re-check.+ */+export const LOCAL_MODELS_CHANGED_EVENT = "openwhispr-local-models-changed";++function notifyLocalModelsChanged(): void {+ window.dispatchEvent(new Event(LOCAL_MODELS_CHANGED_EVENT));+}+export interface DownloadProgress {percentage: number;downloadedBytes: number;@@ -203,6 +214,7 @@ export function useModelDownload({const terminalVersion = ++downloadStateVersionRef.current;if (data.type === "complete") {+ notifyLocalModelsChanged();void (async () => {try {await onDownloadCompleteRef.current?.();@@ -458,6 +470,7 @@ export function useModelDownload({});}} else {+ notifyLocalModelsChanged();onSelectAfterDownload?.(modelId);}@@ -534,6 +547,7 @@ export function useModelDownload({description: t("hooks.modelDownload.modelDeleted.description"),});}+ notifyLocalModelsChanged();onComplete?.();} catch (error: unknown) {const errorMessage = error instanceof Error ? error.message : String(error);diff --git a/src/hooks/useRequiredLocalModels.ts b/src/hooks/useRequiredLocalModels.tsnew file mode 100644index 000000000..415dd05f2--- /dev/null+++ b/src/hooks/useRequiredLocalModels.ts@@ -0,0 +1,73 @@+import { useCallback, useEffect, useMemo, useState } from "react";+import { usePolicySnapshot } from "./usePolicy";+import { LOCAL_MODELS_CHANGED_EVENT } from "./useModelDownload";+import { missingRequiredLocalModels, requiredLocalModelIds } from "../stores/policyRules";++export interface RequiredLocalModelsState {+ /** Org-required model ids this build's registry knows how to download. */+ required: string[];+ /** Required ids not yet on disk. Empty while `loading` — check that flag. */+ missing: string[];+ /** True until the disk check for the current required list settles. */+ loading: boolean;+ /** Re-run the disk check. Call after a download completes or a model is deleted. */+ refresh: () => Promise<void>;+}++/**+ * Joins the org's required-download policy with disk truth — the same+ * listWhisperModels/listParakeetModels fan-out LocalModelSetupStep uses.+ * Policy updates arrive reactively (workspace-policy-changed → policy store →+ * usePolicySnapshot) and re-run the disk check. Shared by the onboarding+ * required-models step and the ControlPanel fleet banner.+ */+export function useRequiredLocalModels(): RequiredLocalModelsState {+ const snapshot = usePolicySnapshot();+ // Key on content: policy refreshes swap object identities every few minutes+ // without changing the list, and the disk fan-out shouldn't rerun for that.+ const requiredKey = useMemo(() => requiredLocalModelIds(snapshot).join("\n"), [snapshot]);+ const required = useMemo(() => (requiredKey ? requiredKey.split("\n") : []), [requiredKey]);+ const [installed, setInstalled] = useState<string[] | null>(null);++ const refresh = useCallback(async (): Promise<void> => {+ const [whisper, parakeet] = await Promise.all([+ window.electronAPI?.listWhisperModels?.().catch(() => undefined),+ window.electronAPI?.listParakeetModels?.().catch(() => undefined),+ ]);+ setInstalled([+ ...(whisper?.models ?? []).filter((model) => model.downloaded).map((model) => model.model),+ ...(parakeet?.models ?? []).filter((model) => model.downloaded).map((model) => model.model),+ ]);+ }, []);++ useEffect(() => {+ // Nothing required (the common case) — skip the IPC fan-out entirely.+ if (!requiredKey) return;+ void refresh();++ // Downloads and deletions elsewhere in this window (Settings, the+ // background tray) change disk truth without going through this hook.+ const handleModelsChanged = () => void refresh();+ window.addEventListener(LOCAL_MODELS_CHANGED_EVENT, handleModelsChanged);+ window.addEventListener("openwhispr-models-cleared", handleModelsChanged);+ return () => {+ window.removeEventListener(LOCAL_MODELS_CHANGED_EVENT, handleModelsChanged);+ window.removeEventListener("openwhispr-models-cleared", handleModelsChanged);+ };+ }, [requiredKey, refresh]);++ const missing = useMemo(+ () =>+ required.length === 0 || installed === null+ ? []+ : missingRequiredLocalModels(required, installed),+ [required, installed]+ );++ return {+ required,+ missing,+ loading: required.length > 0 && installed === null,+ refresh,+ };+}diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex a493adf17..2789557c7 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -533,6 +533,17 @@"step2": "Öffne die Corti-Konsole und erstelle API-Zugangsdaten","step3": "Füge Client-ID und Secret unten ein"}+ },+ "requiredModels": {+ "title": "Erforderliche Modelle installieren",+ "description": "{{organization}} erfordert diese Modelle auf diesem Gerät, bevor Sie mit dem Diktieren beginnen können.",+ "genericOrganization": "Ihre Organisation",+ "installed": "Installiert",+ "queued": "In Warteschlange",+ "failed": {+ "title": "Ein Download wurde nicht abgeschlossen",+ "description": "Prüfen Sie Ihre Verbindung und den freien Speicherplatz und versuchen Sie es erneut. Wenn der Fehler weiterhin auftritt, wenden Sie sich an Ihren Administrator."+ }}},"streaming": {@@ -656,7 +667,12 @@"enableButton": "GPU aktivieren","dismissButton": "Nicht jetzt"},- "backToNotes": "Zurück zu Notizen"+ "backToNotes": "Zurück zu Notizen",+ "requiredModelsByOrg": {+ "title": "Erforderliche Modelle fehlen",+ "description": "Ihre Organisation erfordert diese Modelle auf diesem Gerät: {{models}}.",+ "download": "Herunterladen"+ }},"reasoning": {"mode": {diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 2ce5aa0b5..de4e5e869 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -533,6 +533,17 @@"step2": "Open the Corti console and create API credentials","step3": "Paste your Client ID and Secret below"}+ },+ "requiredModels": {+ "title": "Install required models",+ "description": "{{organization}} requires these models on this device before you can start dictating.",+ "genericOrganization": "Your organization",+ "installed": "Installed",+ "queued": "Queued",+ "failed": {+ "title": "A download didn't finish",+ "description": "Check your connection and free disk space, then retry. If it keeps failing, contact your administrator."+ }}},"streaming": {@@ -656,7 +667,12 @@"enableButton": "Enable GPU","dismissButton": "Not now"},- "backToNotes": "Back to notes"+ "backToNotes": "Back to notes",+ "requiredModelsByOrg": {+ "title": "Required models missing",+ "description": "Your organization requires these models on this device: {{models}}.",+ "download": "Download"+ }},"reasoning": {"mode": {diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex e76f9a326..4edd99db8 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -533,6 +533,17 @@"step2": "Abre la consola de Corti y crea credenciales de API","step3": "Pega tu Client ID y Secret abajo"}+ },+ "requiredModels": {+ "title": "Instala los modelos requeridos",+ "description": "{{organization}} requiere estos modelos en este dispositivo antes de que puedas empezar a dictar.",+ "genericOrganization": "Tu organización",+ "installed": "Instalado",+ "queued": "En cola",+ "failed": {+ "title": "Una descarga no se completó",+ "description": "Comprueba tu conexión y el espacio libre en disco, y vuelve a intentarlo. Si sigue fallando, contacta a tu administrador."+ }}},"streaming": {@@ -656,7 +667,12 @@"enableButton": "Activar GPU","dismissButton": "Ahora no"},- "backToNotes": "Volver a notas"+ "backToNotes": "Volver a notas",+ "requiredModelsByOrg": {+ "title": "Faltan modelos requeridos",+ "description": "Tu organización requiere estos modelos en este dispositivo: {{models}}.",+ "download": "Descargar"+ }},"reasoning": {"mode": {diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 456119398..4c969524c 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -533,6 +533,17 @@"step2": "Ouvrez la console Corti et créez des identifiants API","step3": "Collez votre Client ID et votre Secret ci-dessous"}+ },+ "requiredModels": {+ "title": "Installez les modèles requis",+ "description": "{{organization}} exige ces modèles sur cet appareil avant que vous puissiez commencer la dictée.",+ "genericOrganization": "Votre organisation",+ "installed": "Installé",+ "queued": "En attente",+ "failed": {+ "title": "Un téléchargement ne s'est pas terminé",+ "description": "Vérifiez votre connexion et l'espace disque disponible, puis réessayez. Si le problème persiste, contactez votre administrateur."+ }}},"streaming": {@@ -656,7 +667,12 @@"enableButton": "Activer le GPU","dismissButton": "Pas maintenant"},- "backToNotes": "Retour aux notes"+ "backToNotes": "Retour aux notes",+ "requiredModelsByOrg": {+ "title": "Modèles requis manquants",+ "description": "Votre organisation exige ces modèles sur cet appareil : {{models}}.",+ "download": "Télécharger"+ }},"reasoning": {"mode": {diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 2772375dc..bb437f7c3 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -533,6 +533,17 @@"step2": "Apri la console Corti e crea le credenziali API","step3": "Incolla qui sotto Client ID e Secret"}+ },+ "requiredModels": {+ "title": "Installa i modelli richiesti",+ "description": "{{organization}} richiede questi modelli su questo dispositivo prima che tu possa iniziare a dettare.",+ "genericOrganization": "La tua organizzazione",+ "installed": "Installato",+ "queued": "In coda",+ "failed": {+ "title": "Un download non è stato completato",+ "description": "Controlla la connessione e lo spazio libero su disco, poi riprova. Se continua a fallire, contatta il tuo amministratore."+ }}},"streaming": {@@ -656,7 +667,12 @@"enableButton": "Attiva GPU","dismissButton": "Non ora"},- "backToNotes": "Torna alle note"+ "backToNotes": "Torna alle note",+ "requiredModelsByOrg": {+ "title": "Modelli richiesti mancanti",+ "description": "La tua organizzazione richiede questi modelli su questo dispositivo: {{models}}.",+ "download": "Scarica"+ }},"reasoning": {"mode": {diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex 504b8edd8..4082c27cb 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -533,6 +533,17 @@"step2": "Corti コンソールで API 認証情報を作成","step3": "Client ID と Secret を下に貼り付け"}+ },+ "requiredModels": {+ "title": "必須モデルをインストール",+ "description": "{{organization}}では、ディクテーションを開始する前にこれらのモデルをこのデバイスにインストールする必要があります。",+ "genericOrganization": "所属組織",+ "installed": "インストール済み",+ "queued": "待機中",+ "failed": {+ "title": "ダウンロードが完了しませんでした",+ "description": "接続とディスクの空き容量を確認して、再試行してください。それでも失敗する場合は、管理者にお問い合わせください。"+ }}},"streaming": {@@ -656,7 +667,12 @@"enableButton": "GPU を有効化","dismissButton": "後で"},- "backToNotes": "ノートに戻る"+ "backToNotes": "ノートに戻る",+ "requiredModelsByOrg": {+ "title": "必須モデルがありません",+ "description": "組織では、このデバイスにこれらのモデルが必要です:{{models}}。",+ "download": "ダウンロード"+ }},"reasoning": {"mode": {diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex de0aea85c..34919e1bb 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -512,6 +512,17 @@"step2": "Abra o console da Corti e crie credenciais de API","step3": "Cole seu Client ID e Secret abaixo"}+ },+ "requiredModels": {+ "title": "Instale os modelos exigidos",+ "description": "{{organization}} exige estes modelos neste dispositivo antes que você possa começar a ditar.",+ "genericOrganization": "Sua organização",+ "installed": "Instalado",+ "queued": "Na fila",+ "failed": {+ "title": "Um download não foi concluído",+ "description": "Verifique sua conexão e o espaço livre em disco e tente novamente. Se continuar falhando, entre em contato com seu administrador."+ }}},"streaming": {@@ -635,7 +646,12 @@"enableButton": "Ativar GPU","dismissButton": "Agora não"},- "backToNotes": "Voltar para notas"+ "backToNotes": "Voltar para notas",+ "requiredModelsByOrg": {+ "title": "Modelos exigidos ausentes",+ "description": "Sua organização exige estes modelos neste dispositivo: {{models}}.",+ "download": "Baixar"+ }},"reasoning": {"mode": {diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 00a5f4022..ee86387cf 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -533,6 +533,17 @@"step2": "Откройте консоль Corti и создайте учётные данные API","step3": "Вставьте Client ID и Secret ниже"}+ },+ "requiredModels": {+ "title": "Установите обязательные модели",+ "description": "{{organization}} требует наличия этих моделей на этом устройстве, прежде чем вы сможете начать диктовку.",+ "genericOrganization": "Ваша организация",+ "installed": "Установлено",+ "queued": "В очереди",+ "failed": {+ "title": "Загрузка не завершилась",+ "description": "Проверьте подключение и свободное место на диске, затем повторите попытку. Если ошибка повторяется, обратитесь к администратору."+ }}},"streaming": {@@ -656,7 +667,12 @@"enableButton": "Включить GPU","dismissButton": "Не сейчас"},- "backToNotes": "Назад к заметкам"+ "backToNotes": "Назад к заметкам",+ "requiredModelsByOrg": {+ "title": "Отсутствуют обязательные модели",+ "description": "Ваша организация требует наличия этих моделей на этом устройстве: {{models}}.",+ "download": "Скачать"+ }},"reasoning": {"mode": {diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 062ccfb81..9ae287828 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -533,6 +533,17 @@"step2": "打开 Corti 控制台并创建 API 凭据","step3": "在下方粘贴 Client ID 和 Secret"}+ },+ "requiredModels": {+ "title": "安装必需的模型",+ "description": "{{organization}}要求在此设备上安装这些模型后才能开始听写。",+ "genericOrganization": "您的组织",+ "installed": "已安装",+ "queued": "排队中",+ "failed": {+ "title": "有一项下载未完成",+ "description": "请检查网络连接和磁盘剩余空间,然后重试。如果仍然失败,请联系您的管理员。"+ }}},"streaming": {@@ -656,7 +667,12 @@"enableButton": "启用 GPU","dismissButton": "暂不启用"},- "backToNotes": "返回笔记"+ "backToNotes": "返回笔记",+ "requiredModelsByOrg": {+ "title": "缺少必需的模型",+ "description": "您的组织要求在此设备上安装这些模型:{{models}}。",+ "download": "下载"+ }},"reasoning": {"mode": {diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex f65d14e4a..38953cd11 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -533,6 +533,17 @@"step2": "開啟 Corti 控制台並建立 API 憑證","step3": "在下方貼上 Client ID 和 Secret"}+ },+ "requiredModels": {+ "title": "安裝必要的模型",+ "description": "{{organization}}要求在此裝置上安裝這些模型後才能開始聽寫。",+ "genericOrganization": "您的組織",+ "installed": "已安裝",+ "queued": "排隊中",+ "failed": {+ "title": "有一項下載未完成",+ "description": "請檢查網路連線與磁碟剩餘空間,然後重試。如果仍然失敗,請聯絡您的管理員。"+ }}},"streaming": {@@ -656,7 +667,12 @@"enableButton": "啟用 GPU","dismissButton": "暫時不要"},- "backToNotes": "返回筆記"+ "backToNotes": "返回筆記",+ "requiredModelsByOrg": {+ "title": "缺少必要的模型",+ "description": "您的組織要求在此裝置上安裝這些模型:{{models}}。",+ "download": "下載"+ }},"reasoning": {"mode": {diff --git a/src/stores/policyRules.ts b/src/stores/policyRules.tsindex 53308cb18..383b19113 100644--- a/src/stores/policyRules.ts+++ b/src/stores/policyRules.ts@@ -2,6 +2,10 @@ import type { InferenceMode, ShareVisibility } from "../types/electron";import type { OrgPolicy, PolicyScope } from "../types/policy";import type { SettingsState } from "./settingsStore";import { compareAppVersions } from "../utils/version.ts";+// The registry JSON directly (like policyValidation.js), NOT ModelRegistry:+// that module pulls the settings/identity stores, whose module scope needs+// real browser globals, and this file is imported by node-run sync tests.+import modelRegistryData from "../models/modelRegistryData.json";export type PolicyStatus = "idle" | "loading" | "managed" | "unmanaged" | "error";@@ -117,6 +121,43 @@ export function isScreenContextAllowed(state: PolicyDecisionSnapshot): boolean {return managedPolicyDecision(state, (policy) => policy.features.screenContextEnabled !== false);}+const warnedUnknownRequiredModelIds = new Set<string>();++/**+ * Model ids the org requires on disk, filtered to ids this build's registry+ * knows how to download. Unknown ids (a newer server) are dropped with a+ * warning instead of failing the policy — minAppVersion is the enforcement+ * backstop. Fail-open for idle/loading/unmanaged/error: this field only ever+ * adds work for managed users, so an unresolved policy requires nothing yet.+ */+export function requiredLocalModelIds(state: PolicyDecisionSnapshot): string[] {+ const required = managedPolicy(state)?.requiredLocalModels;+ if (!required?.length) return [];+ const known = new Set<string>([+ ...Object.keys(modelRegistryData.whisperModels),+ ...Object.keys(modelRegistryData.parakeetModels),+ ]);+ const usable: string[] = [];+ for (const id of required) {+ if (known.has(id)) {+ if (!usable.includes(id)) usable.push(id);+ } else if (!warnedUnknownRequiredModelIds.has(id)) {+ warnedUnknownRequiredModelIds.add(id);+ console.warn(`[policy] Ignoring unknown required local model id: ${id}`);+ }+ }+ return usable;+}++/** Required ids not yet on disk. Disk truth (installed ids) comes from the caller. */+export function missingRequiredLocalModels(+ required: readonly string[],+ installedIds: readonly string[]+): string[] {+ const installed = new Set(installedIds);+ return required.filter((id) => !installed.has(id));+}+/** Whether cloud backup/sync is allowed. */export function isCloudBackupAllowed(state: PolicyDecisionSnapshot): boolean {return managedPolicyDecision(state, (policy) => policy.dataRetention.cloudBackupAllowed);diff --git a/src/types/policy.ts b/src/types/policy.tsindex 01e20bdf2..15faebbef 100644--- a/src/types/policy.ts+++ b/src/types/policy.ts@@ -41,6 +41,13 @@ export interface OrgPolicy {localHistoryMode: LocalHistoryMode;cloudBackupAllowed: boolean;};+ /**+ * Model ids (whisper/parakeet registry keys) members must download.+ * Absent on servers that predate the field; absent/empty means none.+ * Validated shape-only so future server-side ids can't invalidate the+ * policy — unknown ids are filtered at enforcement time.+ */+ requiredLocalModels?: string[];minAppVersion: string | null;}diff --git a/test/components/onboardingFlow.test.js b/test/components/onboardingFlow.test.jsindex 3a68646da..0da96c5c1 100644--- a/test/components/onboardingFlow.test.js+++ b/test/components/onboardingFlow.test.js@@ -268,3 +268,85 @@ test("progress counts only the guest steps that draw a footer", async () => {// An off-route step has no position to report.assert.equal(getOnboardingProgress("notes", guestByok), null);});++test("required models insert a blocking step right after auth — account path only", async () => {+ const { getOnboardingRoute } = await load();+ const route = getOnboardingRoute({+ authPath: "account",+ setupMode: null,+ agentAllowed: true,+ requiredModelsPending: true,+ });+ assert.deepEqual(route.slice(0, 3), ["auth", "required-models", "permissions"]);++ // Guests never fetch a policy, so the gate cannot apply to them.+ const guest = getOnboardingRoute({+ authPath: "guest",+ setupMode: null,+ agentAllowed: true,+ requiredModelsPending: true,+ });+ assert.equal(guest.includes("required-models"), false);++ // Absent flag (older callers, nothing missing) leaves the route unchanged.+ const noFlag = getOnboardingRoute({ authPath: "account", setupMode: null, agentAllowed: true });+ assert.equal(noFlag.includes("required-models"), false);+});++test("required-models coexists with policy- and enterprise-shortened routes", async () => {+ const { getOnboardingRoute } = await load();+ const route = getOnboardingRoute({+ authPath: "account",+ setupMode: null,+ agentAllowed: false,+ requiredModelsPending: true,+ skipSetupChoice: true,+ });+ assert.deepEqual(route.slice(0, 3), ["auth", "required-models", "permissions"]);+ assert.equal(route.at(-1), "notes");+ assert.equal(route.includes("assistant-hotkey"), false);+});++test("an off-route required-models session clamps to a neighbour step", async () => {+ const { getOnboardingRoute, reconcileStepWithRoute } = await load();+ // The session latch normally keeps the step on-route; if a stale session+ // still names it after the requirement went away across restarts, it must+ // clamp next to auth/permissions rather than teleport down the route.+ const route = getOnboardingRoute({ authPath: "account", setupMode: null, agentAllowed: true });+ assert.ok(["auth", "permissions"].includes(reconcileStepWithRoute("required-models", route)));+});++test("the required-models step is counted in progress", async () => {+ const { getOnboardingProgress, getOnboardingRoute } = await load();+ const route = getOnboardingRoute({+ authPath: "account",+ setupMode: null,+ agentAllowed: true,+ requiredModelsPending: true,+ });+ assert.deepEqual(getOnboardingProgress("required-models", route), { index: 0, total: 10 });+ assert.deepEqual(getOnboardingProgress("languages", route), { index: 1, total: 10 });+});++test("the tray suppression predicate matches only an active required-models session", async () => {+ const { createOnboardingSession, isRequiredModelsOnboardingStepActive } = await load();++ assert.equal(isRequiredModelsOnboardingStepActive(null), false);+ assert.equal(isRequiredModelsOnboardingStepActive("not json"), false);++ const session = createOnboardingSession();+ assert.equal(isRequiredModelsOnboardingStepActive(JSON.stringify(session)), false);+ assert.equal(+ isRequiredModelsOnboardingStepActive(+ JSON.stringify({ ...session, currentStepId: "required-models" })+ ),+ true+ );+ // A completed/cleared session (the post-onboarding state) never suppresses.+ assert.equal(+ isRequiredModelsOnboardingStepActive(+ JSON.stringify({ ...session, currentStepId: "permissions" })+ ),+ false+ );+});diff --git a/test/helpers/policyRules.test.js b/test/helpers/policyRules.test.jsindex 3928d95a7..42747c655 100644--- a/test/helpers/policyRules.test.js+++ b/test/helpers/policyRules.test.js@@ -769,3 +769,65 @@ test("cloud-backup resume fires only on a denial-to-grant transition", async ()assert.equal(cloudBackupResumed(unmanaged, unmanaged), false);assert.equal(cloudBackupResumed(managedAllowed, managedAllowed), false);});++test("required local models resolve only for managed policies", async () => {+ const { requiredLocalModelIds } = await load();+ const required = ["base", "parakeet-tdt-0.6b-v3"];+ const managed = {+ status: "managed",+ policy: { ...policy, requiredLocalModels: required },+ appVersion: "1.9.0",+ };++ assert.deepEqual(requiredLocalModelIds(managed), required);+ for (const status of ["idle", "loading", "unmanaged", "error"]) {+ assert.deepEqual(requiredLocalModelIds({ status, policy: null, appVersion: null }), [], status);+ }+ // Absent field (older server) and empty list both mean nothing is required.+ assert.deepEqual(requiredLocalModelIds({ status: "managed", policy, appVersion: null }), []);+ assert.deepEqual(+ requiredLocalModelIds({+ status: "managed",+ policy: { ...policy, requiredLocalModels: [] },+ appVersion: null,+ }),+ []+ );+});++test("required local models drop ids the registry does not know, with a warning", async () => {+ const { requiredLocalModelIds } = await load();+ const warnings = [];+ const originalWarn = console.warn;+ console.warn = (...args) => warnings.push(args.join(" "));+ try {+ const managed = {+ status: "managed",+ policy: {+ ...policy,+ requiredLocalModels: ["base", "a-model-from-the-future", "turbo", "base"],+ },+ appVersion: null,+ };+ // Unknown ids are filtered (forward compat) and duplicates collapse.+ assert.deepEqual(requiredLocalModelIds(managed), ["base", "turbo"]);+ } finally {+ console.warn = originalWarn;+ }+ assert.equal(+ warnings.some((line) => line.includes("a-model-from-the-future")),+ true+ );+});++test("missing required models is a pure set difference over disk truth", async () => {+ const { missingRequiredLocalModels } = await load();++ assert.deepEqual(missingRequiredLocalModels([], []), []);+ assert.deepEqual(missingRequiredLocalModels(["base"], []), ["base"]);+ assert.deepEqual(+ missingRequiredLocalModels(["base", "turbo"], ["turbo", "small"]),+ ["base"]+ );+ assert.deepEqual(missingRequiredLocalModels(["base"], ["base"]), []);+});diff --git a/test/helpers/policyValidation.test.js b/test/helpers/policyValidation.test.jsindex f7d881f72..48d684524 100644--- a/test/helpers/policyValidation.test.js+++ b/test/helpers/policyValidation.test.js@@ -65,6 +65,33 @@ test("rejects a malformed screenContextEnabled", () => {}});+test("accepts requiredLocalModels as an optional string list", () => {+ for (const value of [[], ["base"], ["base", "parakeet-tdt-0.6b-v3"]]) {+ const policy = validPolicy();+ policy.requiredLocalModels = value;+ assert.equal(isValidPolicyShape(policy), true, JSON.stringify(value));+ }++ // Servers that predate the field omit it — the old-server contract.+ assert.equal(isValidPolicyShape(validPolicy()), true);+});++test("accepts unknown-but-string required model ids — shape-only forward compat", () => {+ // A future model id added server-side must not make this build discard the+ // entire managed policy; enforcement filters unknown ids instead.+ const policy = validPolicy();+ policy.requiredLocalModels = ["a-model-from-the-future"];+ assert.equal(isValidPolicyShape(policy), true);+});++test("rejects a malformed requiredLocalModels", () => {+ for (const value of ["base", [42], [null], [{ id: "base" }], {}]) {+ const policy = validPolicy();+ policy.requiredLocalModels = value;+ assert.equal(isValidPolicyShape(policy), false, JSON.stringify(value));+ }+});+test("tolerates the server-only memoryEnabled flag", () => {// The API gates Mem0 agent memory itself and the app never reads the field,// so its presence must not invalidate an otherwise valid policy.