Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(model-provider): never submit a provider the egress policy blocks (#5662 follow-up) (#5749)

LearningCircuitfd8b0b5784b3
diff --git a/changelog.d/5749.bugfix.md b/changelog.d/5749.bugfix.md
new file mode 100644
index 0000000000..da65c1cf47
--- /dev/null
+++ b/changelog.d/5749.bugfix.md
@@ -0,0 +1,34 @@
+The New Research page no longer switches you to a different model provider
+when the one you configured is blocked by the "Require Local LLM Endpoint"
+policy. It previously picked the first available provider without saving that
+choice, so the form submitted a provider you never selected paired with the
+model saved for the blocked one, while the settings page still showed your
+original provider. The blocked provider now stays visible with the reason it
+was blocked, and the selection is left empty so the run fails with a policy
+error instead of quietly using a provider you did not pick.
+
+The New Research page and the news subscription form both submit the
+remembered provider once the visible selection has been cleared, so each run is
+refused by name for the provider you configured rather than falling back to an
+older saved default. Creating or updating a subscription needs that too,
+because it only checks the egress policy when a provider is present — omitting
+it there would skip the check and quietly blank the stored provider instead of
+reporting the rejection with its reason. Of the two forms this change touches,
+only the subscription form's test run omits the key: it drops the provider when
+it has no value, and starting a run with the key absent substitutes your saved
+provider setting for it.
+
+Blocked providers are also greyed out on the news subscription form and the
+benchmark evaluation settings, which previously offered them as ordinary
+choices. The reason shown now names the control that actually caused the
+block — the egress scope or a server-side lock, not just the checkbox — and
+when the default Adaptive scope is what resolved to Private only, the reason
+names Adaptive rather than a "Private only" selection you never made.
+
+Provider selection also follows changes made after page load: blocking and re-enabling the latest choice restores that choice, and a server flag whose value the policy does not treat as true no longer hides a denial caused by the Private-only scope.
+
+Submission retains the intended provider while a settings save is pending, so a policy rejection cannot silently fall back to an older database default.
+
+Subscription actions retain a policy-blocked saved provider instead of clearing it on unrelated edits. Benchmark provider availability uses the evaluation endpoint configuration, and starting waits for a selectable provider, completed settings saves and refreshed availability. Model discovery responses from an older request no longer overwrite newer policy state.
+
+The benchmark endpoint URL input follows the remembered evaluation provider regardless of the spelling the server returns for it, so a policy-blocked endpoint can still be corrected on the page.
diff --git a/src/local_deep_research/security/egress/policy.py b/src/local_deep_research/security/egress/policy.py
index 3483884c8b..e79fed9688 100644
--- a/src/local_deep_research/security/egress/policy.py
+++ b/src/local_deep_research/security/egress/policy.py
@@ -2395,3 +2395,16 @@ def _coerce_bool(value) -> bool:
if isinstance(value, str):
return value.strip().lower() in ("true", "1", "yes", "on")
return bool(value)
+
+
+def coerce_policy_bool(value) -> bool:
+ """Public alias for the coercion the policy applies to its own flags.
+
+ UI code that has to report *whether the policy is in force* (for example
+ the reason a provider is greyed out) must decide truthiness the same way
+ ``context_from_snapshot`` does. HTML-checkbox parsers such as
+ ``settings.manager.parse_boolean`` treat every non-falsy string as True,
+ so ``LDR_LLM_REQUIRE_LOCAL_ENDPOINT=enabled`` would be reported as a
+ server lock while the policy itself computes ``require_local_llm=False``.
+ """
+ return _coerce_bool(value)
diff --git a/src/local_deep_research/web/routers/settings.py b/src/local_deep_research/web/routers/settings.py
index 0e7cc78fe5..6260039d5d 100644
--- a/src/local_deep_research/web/routers/settings.py
+++ b/src/local_deep_research/web/routers/settings.py
@@ -79,6 +79,7 @@ from ...security.egress.policy import (
EgressContext,
EgressScope,
PolicyDeniedError,
+ coerce_policy_bool,
context_from_snapshot,
effective_scope_for_display,
evaluate_llm_endpoint,
@@ -90,6 +91,7 @@ from ...security.egress.validators import (
first_egress_validation_error,
)
from ...utilities.db_utils import get_settings_manager
+from ...utilities.type_utils import unwrap_setting
from ...utilities.url_utils import normalize_url
from ...settings.manager import (
@@ -363,14 +365,14 @@ def _resolve_model_discovery_policy(
)
-def _model_discovery_provider_allowed(
+def _model_discovery_provider_decision(
provider: str,
policy_context: EgressContext,
settings_snapshot: dict[str, Any],
-) -> bool:
- """Return whether a provider's configured endpoint is allowed to list models."""
+) -> Decision:
+ """Return the policy decision for a provider's configured endpoint."""
if not policy_context.require_local_llm:
- return True
+ return Decision(True, "no_local_requirement")
decision = evaluate_llm_endpoint(
normalize_provider(provider),
policy_context,
@@ -382,7 +384,128 @@ def _model_discovery_provider_allowed(
provider=normalize_provider(provider),
reason=decision.reason,
)
- return decision.allowed
+ return decision
+
+
+def _model_discovery_provider_allowed(
+ provider: str,
+ policy_context: EgressContext,
+ settings_snapshot: dict[str, Any],
+) -> bool:
+ """Return whether a provider's configured endpoint is allowed to list models."""
+ return _model_discovery_provider_decision(
+ provider, policy_context, settings_snapshot
+ ).allowed
+
+
+# Maps the policy's internal denial reason onto a short phrase describing
+# what the user would have to change. Anything unmapped falls back to the
+# control clause alone rather than leaking a raw reason token into the UI.
+_PROVIDER_DENIAL_CAUSES = {
+ "provider_cloud_only": "cloud-only provider",
+ "provider_url_unset": "no endpoint URL configured",
+ "url_malformed": "endpoint URL is malformed",
+ "provider_remote": "endpoint URL is not local",
+}
+
+
+def _configured_egress_scope(
+ settings_snapshot: dict[str, Any] | None,
+) -> EgressScope | None:
+ """Return the scope the user actually selected, or None if unknown.
+
+ ``EgressContext.scope`` is the RESOLVED scope: ``context_from_snapshot``
+ runs ``_resolve_adaptive_scope``, so the default ``adaptive`` selection
+ is stored as ``PRIVATE_ONLY`` whenever the primary search engine is
+ local. Naming that resolved value in the UI sends the user to a control
+ they never touched — their Egress Scope select still reads "Adaptive".
+ The configured value survives only on the settings snapshot, so read it
+ back from there, env-first — the same precedence
+ ``_resolve_model_discovery_policy`` and ``context_from_snapshot`` use
+ for this setting.
+ """
+ raw = check_env_setting("policy.egress_scope")
+ if raw is None:
+ if not isinstance(settings_snapshot, dict):
+ return None
+ raw = unwrap_setting(
+ settings_snapshot.get("policy.egress_scope", DEFAULT_EGRESS_SCOPE)
+ )
+ # Retired `both` is coerced to the protective default, as every other
+ # reader of this setting does (see context_from_snapshot).
+ if str(raw).strip().lower() == EgressScope.BOTH.value:
+ raw = EgressScope.ADAPTIVE.value
+ try:
+ return parse_user_egress_scope(raw, disabled_unprotected="adaptive")
+ except PolicyDeniedError:
+ return None
+
+
+def _provider_disabled_reason(
+ decision: Decision,
+ policy_context: EgressContext,
+ settings_snapshot: dict[str, Any] | None,
+) -> str:
+ """Build the user-facing reason a provider is greyed out in the dropdown.
+
+ ``require_local_llm`` has three possible origins and the UI has to name
+ the right one, or the user goes hunting for a control that won't help:
+ an operator env lock, the ``private_only`` egress scope (which forces
+ the flag on at ``context_from_snapshot``), or the user's own
+ "Require Local LLM Endpoint" checkbox.
+
+ The scope arm has a fourth case hiding inside it: ``private_only`` may be
+ what ``adaptive`` RESOLVED to rather than what the user chose, so the
+ message is built from ``settings_snapshot`` — the same snapshot the
+ context was built from — and names the selection the user can actually
+ see. The parameter is required rather than defaulted: a caller with no
+ snapshot must say so with an explicit ``None`` (falling back to the
+ resolved scope) instead of silently getting the wrong control named.
+ """
+ env_value = check_env_setting("llm.require_local_endpoint")
+ # Truthiness must match what the policy enforces, not HTML-checkbox
+ # semantics: parse_boolean() calls "enabled" / "T" / "y" True, while
+ # context_from_snapshot() computes require_local_llm with the policy's
+ # own {"true","1","yes","on"} vocabulary. The looser parser reported a
+ # server lock that was not actually in force.
+ env_locked = env_value is not None and coerce_policy_bool(env_value)
+
+ notes = []
+ if not env_locked and policy_context.scope == EgressScope.PRIVATE_ONLY:
+ if _configured_egress_scope(settings_snapshot) == EgressScope.ADAPTIVE:
+ control = 'Blocked by egress scope "Adaptive"'
+ notes.append(
+ "resolved to Private only from your primary search engine"
+ )
+ else:
+ control = 'Blocked by egress scope "Private only"'
+ else:
+ control = 'Blocked by "Require Local LLM Endpoint"'
+
+ cause = _PROVIDER_DENIAL_CAUSES.get(decision.reason)
+ if cause:
+ notes.append(cause)
+ if env_locked:
+ notes.append("locked by the server")
+ return f"{control} ({'; '.join(notes)})" if notes else control
+
+
+def _provider_options_for_snapshot(options, policy_context, policy_snapshot):
+ """Describe provider availability without fetching models or credentials."""
+ provider_options = []
+ for option in options:
+ entry = dict(option)
+ decision = _model_discovery_provider_decision(
+ option["value"], policy_context, policy_snapshot
+ )
+ entry["disabled"] = not decision.allowed
+ entry["disabled_reason"] = (
+ _provider_disabled_reason(decision, policy_context, policy_snapshot)
+ if not decision.allowed
+ else None
+ )
+ provider_options.append(entry)
+ return provider_options
def _get_setting_from_session(key: str | None, username: str, default=None):
@@ -2847,23 +2970,39 @@ def api_get_available_models(
# so we never actually call a blocked provider (#5922 / #5662).
from ...llm.providers import get_discovered_provider_options
- provider_options = []
- for option in get_discovered_provider_options():
- entry = dict(option) # shallow copy
- if (
- policy_context.require_local_llm
- and not _model_discovery_provider_allowed(
- option["value"], policy_context, policy_snapshot
- )
- ):
- entry["disabled"] = True
- entry["disabled_reason"] = (
- 'Blocked by "Require Local LLM Endpoint"'
- )
- else:
- entry["disabled"] = False
- entry["disabled_reason"] = None
- provider_options.append(entry)
+ options = list(get_discovered_provider_options())
+ provider_options = _provider_options_for_snapshot(
+ options, policy_context, policy_snapshot
+ )
+ # Grading uses its own endpoint override. Keep this copied snapshot
+ # out of research model discovery, credential reads and model caches.
+ #
+ # The override is read back from the SAME snapshot the policy context
+ # was built from, not through a second settings read: the snapshot
+ # already carries the LDR_* overlay for this key, so the two agree
+ # (no TOCTOU between classifying the endpoint and reading it), and it
+ # costs one fewer get_user_db_session per request. The route's own
+ # deny-before-credential-read ordering is unaffected either way:
+ # _resolve_model_discovery_policy above has already opened a session
+ # and read the whole snapshot before anything here runs, and the
+ # per-provider api_key_setting reads still happen only after the
+ # denial point.
+ benchmark_snapshot = dict(policy_snapshot)
+ benchmark_endpoint = unwrap_setting(
+ policy_snapshot.get(
+ "benchmark.evaluation.endpoint_url",
+ "https://openrouter.ai/api/v1",
+ )
+ )
+ # Match get_llm's explicit endpoint-override normalization.
+ benchmark_snapshot["llm.openai_endpoint.url"] = (
+ benchmark_endpoint.strip()
+ if isinstance(benchmark_endpoint, str)
+ else benchmark_endpoint
+ )
+ benchmark_provider_options = _provider_options_for_snapshot(
+ options, policy_context, benchmark_snapshot
+ )
# Add remaining hardcoded providers (complex local providers not yet migrated)
@@ -2920,6 +3059,7 @@ def api_get_available_models(
logger.info("Returning cached models from database")
return {
"provider_options": provider_options,
+ "benchmark_provider_options": benchmark_provider_options,
"providers": providers,
}
@@ -3104,7 +3244,11 @@ def api_get_available_models(
# Return all options
_log_available_models_duration(endpoint_start, cache_hit=False)
- return {"provider_options": provider_options, "providers": providers}
+ return {
+ "provider_options": provider_options,
+ "benchmark_provider_options": benchmark_provider_options,
+ "providers": providers,
+ }
except PolicyDeniedError as exc:
reason = exc.decision.reason
diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.js
index 68690dbad8..8fcd2448e7 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -992,6 +992,33 @@
// and the egress-policy warning banner refreshes immediately.
let policyScopeSaveQueue = Promise.resolve();
let policyScopeSaveGeneration = 0;
+
+ // Both the egress-scope select and the "Require Local LLM Endpoint"
+ // checkbox reshape which providers the backend reports as disabled,
+ // and both have to re-fetch AFTER their save lands, because the
+ // backend rebuilds provider_options from the DB on every request.
+ //
+ // Call this synchronously inside the change handler to claim a
+ // generation, then run the returned thunk on policyScopeSaveQueue.
+ // The shared queue keeps a scope save and a checkbox save ordered
+ // against each other; the generation guard drops every refresh but
+ // the newest one, so two quick toggles can't land their responses
+ // out of order and leave the previous policy's disabled set
+ // rendered. A cached (non-force_refresh) fetch is enough here — the
+ // ~1s force_refresh path re-discovers every provider's models and
+ // buys nothing, since provider_options is policy-derived per
+ // request.
+ let policyModelRefreshGeneration = 0;
+ function claimPolicyModelRefresh() {
+ const generation = ++policyModelRefreshGeneration;
+ return () => {
+ if (generation !== policyModelRefreshGeneration) {
+ return undefined;
+ }
+ invalidateCacheKey(CACHE_KEYS.MODELS);
+ return loadModelOptions(false).catch(() => undefined);
+ };
+ }
const policyScopeSelect = document.getElementById('policy_egress_scope');
if (policyScopeSelect) {
policyScopeSelect.dataset.savedValue = policyScopeSelect.value;
@@ -1013,23 +1040,10 @@
applyEgressScopeToEngines();
}
// private_only forces require_local_llm at the backend,
- // which reshapes the LLM provider dropdown. The save has
- // to land first because the backend reads the policy from
- // the DB on every request — firing the refresh before
- // saveSearchSetting resolves would just re-fetch the old
- // policy and leave the dropdown stale. Chain the refresh
- // onto the save queue so the next call sees the
- // freshly-saved scope.
- //
- // Invalidate the client-side 5-minute cache so the chained
- // loadModelOptions(false) actually round-trips the server
- // instead of returning the dropdown options that were
- // captured BEFORE the user toggled the scope. The server
- // builds ``provider_options`` from the current policy on
- // every request, so a cached (non-force_refresh) fetch is
- // enough to reflect the new disabled set — no need for the
- // ~1s force_refresh path that re-discovers every
- // provider's models.
+ // which reshapes the LLM provider dropdown. The refresh is
+ // chained onto the save queue so it sees the freshly-saved
+ // scope rather than the policy it replaced.
+ const refreshProviders = claimPolicyModelRefresh();
policyScopeSaveQueue = policyScopeSaveQueue
.catch(() => undefined)
.then(() => saveSearchSetting(
@@ -1046,15 +1060,12 @@
}
}
))
- .then(() => {
- if (typeof invalidateCacheKey === 'function') {
- invalidateCacheKey(CACHE_KEYS.MODELS);
- }
- if (typeof loadModelOptions === 'function') {
- return loadModelOptions(false).catch(() => undefined);
- }
- return undefined;
- });
+ .then(refreshProviders)
+ // The queue is left dangling until the next toggle
+ // chains onto it, so it has to be self-contained: an
+ // escaping rejection here would surface as an
+ // unhandledRejection with no one to catch it.
+ .catch(() => undefined);
});
// Apply the initial cue on page load (the data-scope attribute is
// already set server-side from settings; this just keeps the icon
@@ -1081,30 +1092,20 @@
if (llmRequireLocalInput && llmRequireLocalInput.dataset.envLocked !== "true") {
llmRequireLocalInput.addEventListener('change', function() {
// The toggle reshapes which cloud providers are blocked in
- // the Model Provider dropdown. The backend reads
- // require_local_llm from the DB on every request, so the
- // refresh has to fire AFTER saveSearchSetting resolves —
- // otherwise we just re-fetch the old policy. Invalidate
- // the client-side 5-minute cache first so the chained
- // loadModelOptions(false) actually round-trips the server
- // (whose provider_options is rebuilt from the current
- // policy on every request — a cached fetch is enough; the
- // ~1s force_refresh path is unnecessary here).
- saveSearchSetting('llm.require_local_endpoint', this.checked)
- .then(() => {
- if (typeof invalidateCacheKey === 'function') {
- invalidateCacheKey(CACHE_KEYS.MODELS);
- }
- if (typeof loadModelOptions === 'function') {
- return loadModelOptions(false);
- }
- return undefined;
- })
- // Swallow errors so a transient backend hiccup doesn't
- // surface as an unhandled rejection. ESLint's no-void
- // rule forbids ``void`` here, so we discard the chain
- // by simply not assigning it — the .catch below makes
- // the promise safe to leave dangling.
+ // the Model Provider dropdown, so the refresh has to fire
+ // after the save lands. Runs on the same queue as the
+ // egress-scope save: private_only forces this same flag on
+ // at the backend, so letting the two race would mean the
+ // dropdown reflects whichever response happened to arrive
+ // last rather than the policy actually in effect.
+ const refreshProviders = claimPolicyModelRefresh();
+ const checked = this.checked;
+ policyScopeSaveQueue = policyScopeSaveQueue
+ .catch(() => undefined)
+ .then(() => saveSearchSetting(
+ 'llm.require_local_endpoint', checked
+ ))
+ .then(refreshProviders)
.catch(() => undefined);
});
}
@@ -1259,8 +1260,12 @@
return;
}
- // Store current value before clearing
+ // Remember the latest selection across a policy-driven clear, so
+ // re-enabling it restores that provider instead of the page-load one.
const currentValue = modelProviderSelect.value;
+ if (currentValue) {
+ modelProviderSelect.setAttribute('data-initial-value', currentValue);
+ }
// Clear existing options
modelProviderSelect.innerHTML = '';
@@ -1283,8 +1288,28 @@
modelProviderSelect.appendChild(option);
});
- // Restore previous value if it exists in new options and is not disabled,
- // otherwise fall back to initial provider or the first enabled provider.
+ // Reconcile the selection against the new option list, mirroring
+ // reconcileSearchEngineSelection() below.
+ //
+ // Rules:
+ // 1. If the current selection is still present AND enabled, keep
+ // it (the user's last pick wins).
+ // 2. Otherwise restore the most recently selected provider from
+ // data-initial-value, when that one is enabled.
+ // 3. If neither is selectable, CLEAR the selection instead of
+ // substituting some other enabled provider.
+ //
+ // Rule 3 is deliberate. Substituting looks friendlier but submits a
+ // provider the user never chose: the assignment is programmatic, so
+ // the change listener never fires and llm.provider is never saved,
+ // and the model input is left holding a model that belongs to the
+ // provider we just navigated away from. The form would post that
+ // mismatched pair while the settings DB still said something else.
+ // Submission keeps the remembered provider even when selection is
+ // empty, so the backend rejects the intended provider regardless
+ // of whether its settings save has finished. The blocked provider
+ // stays visible in the list with
+ // its reason attached, so nothing is hidden from the user.
const optionsList = Array.from(modelProviderSelect.options);
const currentOpt = currentValue
? optionsList.find(opt => opt.value === currentValue)
@@ -1302,15 +1327,10 @@
SafeLogger.log('Initial provider from data attribute:', initialProvider);
modelProviderSelect.value = initialOpt.value;
} else {
- const firstEnabled = optionsList.find(opt => !opt.disabled);
- if (firstEnabled) {
- SafeLogger.log('Falling back to first enabled provider:', firstEnabled.value);
- modelProviderSelect.value = firstEnabled.value;
- } else if (currentOpt) {
- modelProviderSelect.value = currentOpt.value;
- } else {
- modelProviderSelect.value = initialProvider;
- }
+ SafeLogger.log(
+ 'No selectable model provider (configured provider blocked or missing); clearing selection'
+ );
+ modelProviderSelect.value = '';
}
const selectedProvider = modelProviderSelect.value || initialProvider;
@@ -1680,6 +1700,7 @@
// Update provider dropdown if we have a valid provider
if (providerSetting && modelProviderSelect) {
const providerValue = providerSetting.value.toUpperCase();
+ modelProviderSelect.setAttribute('data-initial-value', providerValue);
SafeLogger.log('Setting provider to:', providerValue);
// Find the matching option in the dropdown
@@ -1693,24 +1714,27 @@
// Also save to localStorage
// Provider saved to DB: matchingOption.value);
} else if (!matchingOption) {
- // If no match, try to find case-insensitive or partial match among enabled options
- const caseInsensitiveMatch = Array.from(modelProviderSelect.options).find(
- option => !option.disabled && (
- option.value.toUpperCase().includes(providerValue) ||
- providerValue.includes(option.value.toUpperCase())
- )
- );
-
- if (caseInsensitiveMatch) {
- SafeLogger.log('Found case-insensitive provider match:', caseInsensitiveMatch.value);
- modelProviderSelect.value = caseInsensitiveMatch.value;
- // Also save to localStorage
- // Provider saved to DB: caseInsensitiveMatch.value);
- } else {
- SafeLogger.warn(`No matching provider option found for '${providerValue}'`);
- }
+ modelProviderSelect.value = '';
+ // No option matches the saved provider at all (e.g. it
+ // was removed from the provider list). Leave the
+ // selection cleared rather than fuzzy-matching to a
+ // different enabled provider by substring — that's the
+ // same silent-substitution pattern populateModelProviders()'s
+ // Rule 3 and the disabled-provider branch below both
+ // reject: the assignment is programmatic, so the change
+ // listener never fires and nothing gets persisted, and
+ // the model input is left holding a model for a
+ // provider the user never chose.
+ SafeLogger.warn(`No matching provider option found for '${providerValue}'`);
} else {
- SafeLogger.log('Configured provider is disabled by egress policy; keeping enabled fallback:', modelProviderSelect.value);
+ // Settings may have changed since the page was rendered.
+ modelProviderSelect.value = '';
+ // The saved provider is present but policy-blocked.
+ // Clear any older selection. activeProvider below still
+ // resolves to the configured provider, so its API
+ // key / URL fields stay visible and the user can
+ // fix the setting that caused the block.
+ SafeLogger.log('Configured provider is disabled by egress policy; leaving selection cleared:', providerValue);
}
modelProviderSelect.disabled = !providerSetting.editable;
@@ -2108,6 +2132,8 @@
/**
* Load model options from API or cache
*/
+ let modelOptionsRequestGeneration = 0;
+
function loadModelOptions(forceRefresh = false) {
return new Promise((resolve) => {
// Check in-memory cache first if not forcing refresh (5-minute expiration)
@@ -2120,11 +2146,52 @@
}
}
+ const requestGeneration = ++modelOptionsRequestGeneration;
+
// Add loading class to parent
if (modelInput && modelInput.parentNode) {
modelInput.parentNode.classList.add('ldr-loading');
}
+ // Unwind a response that a newer request has superseded. Such a
+ // response must not touch MODEL_PROVIDERS or the dropdown - that is
+ // what the generation check is for - but it still has to settle its
+ // caller without leaving the cache unset, or two concurrent chains
+ // deadlock:
+ // * leave the cache holding an array. updateModelOptionsForProvider()
+ // re-enters loadModelOptions() whenever the cache is *null*
+ // (see the EMPTY_CACHE_DURATION note further down), and every
+ // entry bumps modelOptionsRequestGeneration - so two chains
+ // that both bail out with the cache still null invalidate each
+ // other forever: an unbounded request storm, a spinner that
+ // never clears and callers whose promises never settle.
+ // Caching [] briefly is the same guard the empty-result and
+ // API-failure paths below use. This write is the half that
+ // terminates the storm.
+ // * drop the 'ldr-loading' this call added. classList is a set,
+ // not a counter, so this clears the spinner outright rather
+ // than balancing an add: the indicator can go out slightly
+ // early while the newer request is still in flight. That is
+ // the deliberate trade - the newer chain may never render
+ // anything (a policy refresh that is itself superseded, a
+ // response that never arrives), and an unconditional remove
+ // is what keeps the spinner from being stranded then.
+ // loadSearchEngineOptions takes the opposite side of the same
+ // trade and keeps its class on a stale response.
+ const resolveSupersededRequest = () => {
+ if (modelInput && modelInput.parentNode) {
+ modelInput.parentNode.classList.remove('ldr-loading');
+ }
+ const cachedData = getCachedData(CACHE_KEYS.MODELS);
+ if (cachedData) {
+ resolve(cachedData);
+ return;
+ }
+ SafeLogger.log('Superseded model response and no cache - caching empty model list briefly');
+ cacheData(CACHE_KEYS.MODELS, []);
+ resolve([]);
+ };
+
// Fetch from API if cache is invalid or refresh is forced
const url = forceRefresh
? `${URLS.SETTINGS_API.AVAILABLE_MODELS}?force_refresh=true`
@@ -2138,6 +2205,10 @@
return response.json();
})
.then(data => {
+ if (requestGeneration !== modelOptionsRequestGeneration) {
+ resolveSupersededRequest();
+ return;
+ }
// Remove loading class
if (modelInput && modelInput.parentNode) {
modelInput.parentNode.classList.remove('ldr-loading');
@@ -2175,6 +2246,10 @@
}
})
.catch(error => {
+ if (requestGeneration !== modelOptionsRequestGeneration) {
+ resolveSupersededRequest();
+ return;
+ }
SafeLogger.error('Error loading models:', error.message || error);
// Remove loading class on error
@@ -2312,7 +2387,7 @@
}
// Canonical LangGraph strategy id — mirrors
- // ``LANGGRAPH_STRATEGY_NAME`` in web/routes/research_routes.py and
+ // ``LANGGRAPH_STRATEGY_NAME`` in web/routers/research.py and
// ``AVAILABLE_STRATEGIES`` in constants.py. The per-collection
// ``agent_enabled`` flag is exclusive to this strategy, so the
// dropdown only consults the flag when the user picks it.
@@ -2360,7 +2435,7 @@
// Re-fetch the search engine list under the current egress scope
// and re-render the dropdown so disabled markers reflect the new
- // scope. The backend's precheck (web/routes/research_routes.py::
+ // scope. The backend's precheck (web/routers/research.py::
// _precheck_engine_policy) is the security guarantee; this is the
// UX guarantee that keeps the user from having to submit to
// discover the mismatch (issue #5204).
@@ -3421,7 +3496,12 @@
}
// Get values from form fields (query already read above)
- const modelProvider = modelProviderSelect ? modelProviderSelect.value : '';
+ // A policy refresh can clear the visible selection while its
+ // provider save is still pending. Send the remembered choice so
+ // the backend checks that provider instead of an older DB default.
+ const modelProvider = modelProviderSelect
+ ? (modelProviderSelect.value || modelProviderSelect.getAttribute('data-initial-value') || '')
+ : '';
// Get values from hidden inputs for custom dropdowns
const model = document.querySelector('#model_hidden') ?
diff --git a/src/local_deep_research/web/templates/pages/benchmark.html b/src/local_deep_research/web/templates/pages/benchmark.html
index ff59b8d974..b8a5a4ad5f 100644
--- a/src/local_deep_research/web/templates/pages/benchmark.html
+++ b/src/local_deep_research/web/templates/pages/benchmark.html
@@ -212,6 +212,7 @@
<label for="evaluation_provider">Evaluation Provider</label>
<select id="evaluation_provider"
name="evaluation_provider"
+ required data-policy-pending="true"
class="ldr-form-control"
data-initial-value="{{ eval_settings.evaluation_provider }}">
<option value="">Loading providers...</option>
@@ -676,6 +677,21 @@ function getConfigurationData() {
function startBenchmark() {
if (benchmarkStartInFlight) return Promise.resolve();
+ const providerSelect = document.getElementById('evaluation_provider');
+ if (providerSelect && (
+ !providerSelect.value ||
+ providerSelect.selectedOptions[0]?.disabled ||
+ providerSelect.dataset.policyPending === 'true'
+ )) {
+ showAlert('Please select an available evaluation provider before starting.', 'warning');
+ return Promise.resolve();
+ }
+ if (typeof saveEvaluationSetting === 'function' && (
+ saveEvaluationSetting.pending || saveEvaluationSetting.failedKeys?.size
+ )) {
+ showAlert('Please finish saving evaluation settings before starting.', 'warning');
+ return Promise.resolve();
+ }
benchmarkStartInFlight = true;
const intentGeneration = ++benchmarkIntentGeneration;
const config = getConfigurationData();
@@ -2012,10 +2028,43 @@ function initializeEvaluationSettings() {
}, 100);
}
+// Select a provider without ever landing on a policy-blocked option.
+// `select.value = x` happily selects a disabled <option>, which would put
+// the form back in the state this guard exists to prevent: a provider the
+// grader will refuse, chosen for the user and submitted silently. Clearing
+// instead leaves the blocked provider visible with its reason and forces a
+// deliberate pick.
+function applyEvaluationProvider(value) {
+ if (!evaluationProviderSelect) return;
+ const match = Array.from(evaluationProviderSelect.options).find(
+ opt => opt.value.toLowerCase() === String(value).toLowerCase()
+ );
+ if (match && !match.disabled) {
+ evaluationProviderSelect.value = match.value;
+ return;
+ }
+ if (match && match.disabled) {
+ console.log('Evaluation provider blocked by egress policy:', value);
+ }
+ evaluationProviderSelect.value = '';
+}
+
+// Provider option values arrive from /settings/api/available-models
+// upper-cased ("OPENAI_ENDPOINT"), while stored settings and the template
+// default are lower-case. The endpoint URL field has to recognise both
+// spellings: hiding it because the remembered provider came back upper-cased
+// strands a policy-blocked endpoint with no control left to correct it.
+function isOpenAIEndpointProvider(value) {
+ return String(value || '').toLowerCase() === 'openai_endpoint';
+}
+
function populateEvaluationProviders() {
if (!evaluationProviderSelect) return;
const currentProvider = evaluationProviderSelect.value;
+ if (currentProvider) {
+ evaluationProviderSelect.setAttribute('data-initial-value', currentProvider);
+ }
// Clear existing options
evaluationProviderSelect.innerHTML = '';
@@ -2030,27 +2079,31 @@ function populateEvaluationProviders() {
{ value: 'llamacpp', label: 'Llama.cpp (Local GGUF files only)' }
];
- // Add options
+ // Add options. Providers blocked by the egress policy arrive from
+ // /settings/api/available-models flagged rather than omitted, so render
+ // them greyed with the reason instead of offering a provider whose
+ // grading calls will be refused once the benchmark is already running.
providers.forEach(provider => {
const option = document.createElement('option');
option.value = provider.value;
- option.textContent = provider.label;
+ const isDisabled = provider.disabled === true;
+ option.disabled = isDisabled;
+ option.textContent = isDisabled && provider.disabled_reason
+ ? `${provider.label} — ${provider.disabled_reason}`
+ : provider.label;
evaluationProviderSelect.appendChild(option);
});
// Set initial value from data attribute
const initialProvider = evaluationProviderSelect.getAttribute('data-initial-value') || 'openai_endpoint';
- const selectedProvider = currentProvider && Array.from(evaluationProviderSelect.options)
- .some(option => option.value === currentProvider)
- ? currentProvider
- : initialProvider;
+ const selectedProvider = currentProvider || initialProvider;
console.log('Setting evaluation provider to:', selectedProvider);
- evaluationProviderSelect.value = selectedProvider;
+ applyEvaluationProvider(selectedProvider);
// Show/hide endpoint field based on the retained provider
if (evaluationEndpointInput && evaluationEndpointInput.parentNode) {
evaluationEndpointInput.parentNode.style.display =
- selectedProvider === 'openai_endpoint' ? 'block' : 'none';
+ isOpenAIEndpointProvider(selectedProvider) ? 'block' : 'none';
}
console.log('Populated evaluation providers with value:', selectedProvider);
@@ -2120,8 +2173,19 @@ function setupEvaluationModelDropdown() {
if (data && data.providers) {
// Store provider options if available
- if (data.provider_options && Array.isArray(data.provider_options)) {
- EVAL_MODEL_PROVIDERS = data.provider_options;
+ // Non-empty, not merely an array: Array.isArray([]) is
+ // true, but an empty list sends
+ // populateEvaluationProviders() down its hardcoded
+ // fallback, whose entries carry no `disabled` flag - so
+ // the saved provider would be re-selected as an enabled
+ // option with policyPending already deleted, and the
+ // start gate would pass for a provider the policy may
+ // refuse. Keep policyPending set until the server
+ // actually advertises options.
+ if (Array.isArray(data.benchmark_provider_options)
+ && data.benchmark_provider_options.length > 0) {
+ EVAL_MODEL_PROVIDERS = data.benchmark_provider_options;
+ if (evaluationProviderSelect) delete evaluationProviderSelect.dataset.policyPending;
console.log('Updated EVAL_MODEL_PROVIDERS from API:', EVAL_MODEL_PROVIDERS);
// Re-populate the provider dropdown with new options
populateEvaluationProviders();
@@ -2186,21 +2250,25 @@ function getEvaluationModelOptions() {
loadEvaluationModelsFromAPI();
}
- // Return minimal defaults while loading
+ // Return minimal defaults while loading. Match on the normalised key, not
+ // the raw select value: /settings/api/available-models emits provider
+ // values upper-cased ("OPENAI_ENDPOINT"), so comparing the raw value would
+ // fall through to the empty list after a refresh even though the cached
+ // lookup above already uses providerKey.
console.log(`No models loaded yet for ${provider}, returning defaults`);
- if (provider === 'openai_endpoint') {
+ if (isOpenAIEndpointProvider(provider)) {
return [
{ value: 'anthropic/claude-3.5-sonnet', label: 'Claude 3.5 Sonnet' },
{ value: 'openai/gpt-4o', label: 'GPT-4o' },
{ value: '01-ai/yi-large', label: 'Yi Large' }
];
- } else if (provider === 'openai') {
+ } else if (providerKey === 'openai') {
return [
{ value: 'gpt-4o', label: 'GPT-4o' },
{ value: 'gpt-4', label: 'GPT-4' },
{ value: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo' }
];
- } else if (provider === 'anthropic') {
+ } else if (providerKey === 'anthropic') {
return [
{ value: 'claude-3-5-sonnet-latest', label: 'Claude 3.5 Sonnet' },
{ value: 'claude-3-opus-20240229', label: 'Claude 3 Opus' }
@@ -2229,11 +2297,11 @@ function debounce(func, wait) {
}
// Debounced version of loadEvaluationModelsFromAPI
-const loadEvaluationModelsFromAPI = debounce(function(forceRefresh = false) {
+const loadEvaluationModelsFromAPI = debounce(function(forceRefresh = false, refreshMetadata = false) {
console.log('Loading evaluation models from API...', forceRefresh ? '(force refresh)' : '');
// Prevent multiple simultaneous loads
- if (window.modelsLoading && !forceRefresh) {
+ if (window.modelsLoading && !forceRefresh && !refreshMetadata) {
console.log('Models already loading, skipping...');
return;
}
@@ -2252,8 +2320,14 @@ const loadEvaluationModelsFromAPI = debounce(function(forceRefresh = false) {
if (data && data.providers) {
// Store provider options if available
- if (data.provider_options && Array.isArray(data.provider_options)) {
- EVAL_MODEL_PROVIDERS = data.provider_options;
+ // Non-empty, not merely an array - see the force-refresh
+ // handler above: an empty list would disarm policyPending while
+ // populateEvaluationProviders() falls back to the unflagged
+ // hardcoded provider list.
+ if (Array.isArray(data.benchmark_provider_options)
+ && data.benchmark_provider_options.length > 0) {
+ EVAL_MODEL_PROVIDERS = data.benchmark_provider_options;
+ if (evaluationProviderSelect) delete evaluationProviderSelect.dataset.policyPending;
console.log('Updated EVAL_MODEL_PROVIDERS from API (initial load):', EVAL_MODEL_PROVIDERS);
// Re-populate the provider dropdown with new options
populateEvaluationProviders();
@@ -2365,7 +2439,7 @@ function setupEvaluationEventHandlers() {
// Show/hide endpoint URL field
if (evaluationEndpointInput && evaluationEndpointInput.parentNode) {
evaluationEndpointInput.parentNode.style.display =
- provider === 'openai_endpoint' || provider === 'OPENAI_ENDPOINT' ? 'block' : 'none';
+ isOpenAIEndpointProvider(provider) ? 'block' : 'none';
}
// Update model options for new provider
@@ -2435,12 +2509,12 @@ function loadEvaluationSettings() {
}
console.log('Setting evaluation provider to:', providerValue);
- evaluationProviderSelect.value = providerValue;
+ applyEvaluationProvider(providerValue);
// Show/hide endpoint field
if (evaluationEndpointInput && evaluationEndpointInput.parentNode) {
evaluationEndpointInput.parentNode.style.display =
- (providerValue === 'openai_endpoint' || providerValue === 'OPENAI_ENDPOINT') ? 'block' : 'none';
+ isOpenAIEndpointProvider(providerValue) ? 'block' : 'none';
}
}
@@ -2518,7 +2592,10 @@ function loadEvaluationSettings() {
function setEvaluationDefaults() {
console.log('Setting evaluation defaults');
if (evaluationProviderSelect) {
- evaluationProviderSelect.value = 'openai_endpoint';
+ // Route the default through the guard: a default is still a choice
+ // the user did not make, so it must not land on a provider the
+ // egress policy has disabled.
+ applyEvaluationProvider('openai_endpoint');
// Show endpoint field for default provider
if (evaluationEndpointInput && evaluationEndpointInput.parentNode) {
evaluationEndpointInput.parentNode.style.display = 'block';
@@ -2530,27 +2607,63 @@ function setEvaluationDefaults() {
}
function saveEvaluationSetting(key, value) {
- console.log('Saving evaluation setting:', key, '=', value);
-
- fetch(`/settings/api/${key}`, {
- method: 'PUT',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': csrfToken
- },
- body: JSON.stringify({ value: value })
- })
- .then(response => response.json())
- .then(data => {
- if (data.success) {
- console.log('Successfully saved evaluation setting:', key);
- } else {
- console.error('Failed to save evaluation setting:', data.error);
+ saveEvaluationSetting.pending = (saveEvaluationSetting.pending || 0) + 1;
+ saveEvaluationSetting.failedKeys ||= new Set();
+ const save = () => {
+ // `save` must never throw synchronously either: the decrement below
+ // lives in a .finally() on the chain it returns, so a throw while
+ // building the request (JSON.stringify on a value it cannot
+ // represent) would leak the increment the same way a rejected queue
+ // link does. Turn it into a rejection the .catch() already handles.
+ let request;
+ try {
+ request = fetch(`/settings/api/${key}`, {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({ value })
+ });
+ } catch (error) {
+ request = Promise.reject(error);
}
- })
- .catch(error => {
- console.error('Error saving evaluation setting:', error);
- });
+ return request
+ .then(async response => {
+ const data = await response.json();
+ // The settings PUT route returns a message on success,
+ // including idempotent no-ops. It does not return a
+ // success boolean.
+ if (response.ok !== true || typeof data?.message !== 'string') {
+ throw new Error('Evaluation setting was not saved');
+ }
+ saveEvaluationSetting.failedKeys.delete(key);
+ if (key === 'benchmark.evaluation.endpoint_url') {
+ // Invalidate an older metadata response immediately,
+ // before the debounced cached-model request starts.
+ // No forced rediscovery.
+ evaluationModelsRequestVersion += 1;
+ if (evaluationProviderSelect) evaluationProviderSelect.dataset.policyPending = 'true';
+ loadEvaluationModelsFromAPI(false, true);
+ }
+ return true;
+ })
+ .catch(error => {
+ saveEvaluationSetting.failedKeys.add(key);
+ console.error('Error saving evaluation setting:', error);
+ return false;
+ })
+ .finally(() => { saveEvaluationSetting.pending -= 1; });
+ };
+ // Preserve input order when two saves for the same setting overlap.
+ // Chain on BOTH settlements: `save` itself never rejects, but if any link
+ // in the queue ever does, a plain `.then(save)` would skip `save` entirely
+ // - so its `.finally()` would never run, `pending` would never come back
+ // down, and startBenchmark()'s "finish saving" gate would stay closed for
+ // the life of the page (each later call adding one more).
+ saveEvaluationSetting.queue = (saveEvaluationSetting.queue || Promise.resolve())
+ .then(save, save);
+ return saveEvaluationSetting.queue;
}
</script>
diff --git a/src/local_deep_research/web/templates/pages/news-subscription-form.html b/src/local_deep_research/web/templates/pages/news-subscription-form.html
index db6f0b0503..68e3055868 100644
--- a/src/local_deep_research/web/templates/pages/news-subscription-form.html
+++ b/src/local_deep_research/web/templates/pages/news-subscription-form.html
@@ -464,10 +464,22 @@ async function loadProviders() {
data.provider_options.forEach(provider => {
const option = document.createElement('option');
option.value = provider.value;
- option.textContent = provider.label;
+ // The endpoint advertises every provider and marks the ones
+ // the egress policy blocks, rather than omitting them, so a
+ // configured cloud key is still visible as such. Render that
+ // state here too — otherwise a blocked provider looks
+ // perfectly selectable and the subscription is rejected at
+ // creation time with no hint as to why.
+ const isDisabled = provider.disabled === true;
+ option.disabled = isDisabled;
+ option.textContent = isDisabled && provider.disabled_reason
+ ? `${provider.label} — ${provider.disabled_reason}`
+ : provider.label;
// Handle case-insensitive comparison for provider names
- option.selected = provider.value.toUpperCase() === currentProvider.toUpperCase() ||
- (!currentProvider && provider.default);
+ option.selected = !isDisabled && (
+ provider.value.toUpperCase() === currentProvider.toUpperCase() ||
+ (!currentProvider && provider.default)
+ );
providerSelect.appendChild(option);
});
@@ -505,9 +517,27 @@ async function loadProviders() {
}
}
- // Set default selected value for provider
+ // Set default selected value for provider. `select.value = x`
+ // happily selects a disabled <option>, which would undo the
+ // guarded selection the forEach loop above already made and
+ // resubmit a policy-blocked provider on the edit path — the
+ // same footgun applyEvaluationProvider() guards against in
+ // benchmark.html. The create path also compares a lowercase
+ // `llm.provider` default against uppercase option values, so
+ // match case-insensitively instead of wiping the selection on
+ // a case mismatch.
if (currentProvider) {
- providerSelect.value = currentProvider;
+ const match = Array.from(providerSelect.options).find(
+ opt => opt.value.toUpperCase() === currentProvider.toUpperCase()
+ );
+ if (match && !match.disabled) {
+ providerSelect.value = match.value;
+ currentProvider = match.value;
+ } else if (match && match.disabled) {
+ console.log('Subscription provider blocked by egress policy:', currentProvider);
+ }
+ // No match at all: leave the selection the forEach loop
+ // above already established rather than clearing it.
}
}
} catch (error) {
@@ -690,7 +720,7 @@ async function handleSubscriptionSubmit(e) {
// Model configuration
const modelHidden = document.getElementById('subscription-model_hidden');
const model = modelHidden ? modelHidden.value : '';
- const provider = document.getElementById('subscription-provider').value;
+ const provider = document.getElementById('subscription-provider').value || currentProvider || '';
const customEndpoint = document.getElementById('subscription-custom-endpoint').value;
if (model && model.includes(':')) {
const parts = model.split(':');
@@ -792,7 +822,7 @@ async function handleTestRun(event, actionAlreadyOwned = false) {
}
// Collect all configuration
- const provider = document.getElementById('subscription-provider').value;
+ const provider = document.getElementById('subscription-provider').value || currentProvider || '';
const modelHidden = document.getElementById('subscription-model_hidden');
const model = modelHidden ? modelHidden.value : '';
const customEndpoint = document.getElementById('subscription-custom-endpoint').value;
@@ -942,7 +972,7 @@ async function handleCreateAndRun(event) {
// Model configuration
const modelHidden = document.getElementById('subscription-model_hidden');
const model = modelHidden ? modelHidden.value : '';
- const provider = document.getElementById('subscription-provider').value;
+ const provider = document.getElementById('subscription-provider').value || currentProvider || '';
const customEndpoint = document.getElementById('subscription-custom-endpoint').value;
// Search configuration
diff --git a/tests/js/components/research-model-provider.test.js b/tests/js/components/research-model-provider.test.js
index 522c5b13fd..5358c9c31c 100644
--- a/tests/js/components/research-model-provider.test.js
+++ b/tests/js/components/research-model-provider.test.js
@@ -55,15 +55,25 @@ function buildForm() {
<div class="ldr-advanced-options-panel ldr-expanded" id="advanced-options-panel" role="group">
<select id="model_provider"><option value="OLLAMA" selected>Ollama</option></select>
- <input type="text" id="model">
- <input type="hidden" id="model_hidden" value="">
- <div id="model-dropdown"><div id="model-dropdown-list"></div></div>
- <button type="button" id="model-refresh"></button>
-
- <input type="text" id="search_engine">
- <input type="hidden" id="search_engine_hidden" value="searxng">
- <div id="search-engine-dropdown"><div id="search-engine-dropdown-list"></div></div>
- <button type="button" id="search_engine-refresh"></button>
+ <!-- Each loader writes 'ldr-loading' onto its own input's
+ parentNode, so #model and #search_engine need separate
+ wrappers here (as research.test.js:61-73 has them). Left
+ as direct siblings they share one parent and the model
+ loader's spinner becomes indistinguishable from the
+ search-engine loader's. -->
+ <div class="ldr-model-control">
+ <input type="text" id="model">
+ <input type="hidden" id="model_hidden" value="">
+ <div id="model-dropdown"><div id="model-dropdown-list"></div></div>
+ <button type="button" id="model-refresh"></button>
+ </div>
+
+ <div class="ldr-search-engine-control">
+ <input type="text" id="search_engine">
+ <input type="hidden" id="search_engine_hidden" value="searxng">
+ <div id="search-engine-dropdown"><div id="search-engine-dropdown-list"></div></div>
+ <button type="button" id="search_engine-refresh"></button>
+ </div>
<select id="strategy"><option value="source-based" selected>source-based</option><option value="langgraph-agent">LangGraph Agent</option></select>
<input id="iterations" value="2">
@@ -175,6 +185,9 @@ beforeEach(() => {
// fixture's lone <option value="OLLAMA">.
const sel = document.getElementById('model_provider');
sel.innerHTML = '<option value="OLLAMA" selected>Ollama</option>';
+ // Tests that stage a specific persisted provider set this; clear it here
+ // so a failing assertion can't leak the attribute into the next test.
+ sel.removeAttribute('data-initial-value');
// Reset privacy controls.
const policyScope = document.getElementById('policy_egress_scope');
policyScope.value = 'adaptive';
@@ -388,8 +401,15 @@ describe('research form — model provider dropdown', () => {
expect(forceRefreshCalls).toHaveLength(0);
});
- it('a failing save does not surface as an unhandled rejection', async () => {
- // Make the save reject so we exercise the .catch on the chain.
+ it('a rejected save leaves the queue quiet and the page usable', async () => {
+ // Note on what this can and cannot prove: saveSearchSetting swallows
+ // its own errors and always resolves, so a non-ok PUT does not by
+ // itself produce a rejection to catch. What this guards is the
+ // shape of the chain — the save queue is a dangling promise between
+ // toggles, so anything that DID reject in it (a throwing refresh, a
+ // future non-swallowing save) would escape as an unhandledRejection
+ // with no handler attached. The terminal .catch on the queue is what
+ // keeps that impossible.
fetchMock.mockImplementation((url, init) => {
if (
url === '/settings/api/policy.egress_scope' &&
@@ -516,7 +536,7 @@ describe('research form — model provider dropdown', () => {
);
});
- it('resets selection to an enabled fallback when the currently selected provider becomes disabled after policy toggle', async () => {
+ it('remembers a newer provider through policy blocking and re-enabling', async () => {
// First load with DEEPSEEK enabled
const initialProviders = [
{ value: 'OLLAMA', label: 'Ollama 💻 Local', disabled: false },
@@ -538,9 +558,14 @@ describe('research form — model provider dropdown', () => {
{ timeout: 1000 }
);
- // Select DEEPSEEK
+ // The user changes the provider after the page started with OLLAMA.
+ // Reverting the remembered selection would silently restore OLLAMA
+ // after the policy toggle, while the database still says DEEPSEEK.
const sel = document.getElementById('model_provider');
+ sel.setAttribute('data-initial-value', 'OLLAMA');
sel.value = 'DEEPSEEK';
+ sel.dispatchEvent(new Event('change'));
+ await flush();
expect(sel.value).toBe('DEEPSEEK');
// Now toggle policy to private_only where DEEPSEEK is disabled
@@ -557,19 +582,35 @@ describe('research form — model provider dropdown', () => {
{ timeout: 1000 }
);
- // Selection should have been reset to an enabled provider (e.g. OLLAMA)
- expect(sel.value).not.toBe('DEEPSEEK');
- const selectedOpt = getProviderOption(sel.value);
- expect(selectedOpt).toBeDefined();
- expect(selectedOpt.disabled).toBe(false);
+ expect(sel.value).toBe('');
+ expect(sel.selectedIndex).toBe(-1);
+ expect(sel.getAttribute('data-initial-value')).toBe('DEEPSEEK');
+ const providerSaves = fetchMock.mock.calls.filter(
+ ([url, init]) => url === '/settings/api/llm.provider' && init?.method === 'PUT'
+ );
+ expect(providerSaves).toHaveLength(1);
+ expect(JSON.parse(providerSaves[0][1].body).value).toBe('deepseek');
+
+ stubModelsResponse(initialProviders);
+ scope.value = 'public_only';
+ scope.dispatchEvent(new Event('change'));
+ await vi.waitFor(() => expect(sel.value).toBe('DEEPSEEK'));
});
- it('falls back to the first enabled provider when initialProvider is also disabled', async () => {
+ it('clears the selection instead of substituting when the configured provider is blocked', async () => {
+ // The regression this guards: substituting some other enabled
+ // provider is a programmatic assignment, so the change listener
+ // never fires and llm.provider is never saved. The form would then
+ // post a provider the user never chose, paired with the model saved
+ // for the blocked one, while the settings DB still said otherwise.
+ // Clearing instead makes the backend fall back to the saved
+ // llm.provider and fail with a clean PolicyDeniedError.
const sel = document.getElementById('model_provider');
sel.setAttribute('data-initial-value', 'OPENAI');
sel.value = 'OPENAI';
- // Provide options where OPENAI is disabled, but LMSTUDIO is enabled
+ // OPENAI (both current and initial) is blocked; LMSTUDIO is a
+ // perfectly good enabled option that we must NOT silently jump to.
const providers = [
{ value: 'OPENAI', label: 'OpenAI ☁️ Cloud', disabled: true, disabled_reason: 'Blocked by policy' },
{ value: 'LMSTUDIO', label: 'LM Studio 💻 Local', disabled: false },
@@ -590,12 +631,359 @@ describe('research form — model provider dropdown', () => {
{ timeout: 1000 }
);
- // Selection should have fallen back to first enabled provider (LMSTUDIO)
- expect(sel.value).toBe('LMSTUDIO');
- const selectedOpt = getProviderOption(sel.value);
- expect(selectedOpt.disabled).toBe(false);
+ expect(sel.value).toBe('');
+ expect(sel.selectedIndex).toBe(-1);
+
+ // And nothing was persisted on the user's behalf.
+ const providerSaves = fetchMock.mock.calls.filter(
+ ([u, init]) => u === '/settings/api/llm.provider' && init?.method === 'PUT'
+ );
+ expect(providerSaves).toEqual([]);
// Clean up data-initial-value
sel.removeAttribute('data-initial-value');
});
+
+ it('never selects a disabled option when every provider is blocked', async () => {
+ // `select.value = x` happily selects a disabled <option>, so the
+ // all-blocked case has to clear rather than fall through to
+ // "keep whatever we had".
+ const sel = document.getElementById('model_provider');
+ sel.setAttribute('data-initial-value', 'OPENAI');
+ sel.value = 'OPENAI';
+
+ const providers = [
+ { value: 'OPENAI', label: 'OpenAI ☁️ Cloud', disabled: true, disabled_reason: 'Blocked by policy' },
+ { value: 'DEEPSEEK', label: 'DeepSeek ☁️ Cloud', disabled: true, disabled_reason: 'Blocked by policy' },
+ ];
+ stubModelsResponse(providers);
+
+ const scope = document.getElementById('policy_egress_scope');
+ scope.value = 'private_only';
+ scope.dispatchEvent(new Event('change'));
+
+ await vi.waitFor(
+ () => {
+ const deepseek = getProviderOption('DEEPSEEK');
+ expect(deepseek).toBeDefined();
+ expect(deepseek.disabled).toBe(true);
+ },
+ { timeout: 1000 }
+ );
+
+ expect(sel.value).toBe('');
+ expect(sel.selectedIndex).toBe(-1);
+ // Both blocked providers stay visible with their reason, so the
+ // user can still see that the key they configured was read.
+ expect(getProviderOption('OPENAI').textContent).toContain('Blocked by policy');
+
+ sel.removeAttribute('data-initial-value');
+ });
+
+ it('applies only the newest policy toggle when two land back to back', async () => {
+ // Both the scope select and the local-only checkbox run on the same
+ // save queue with a shared generation counter. Without the guard,
+ // two quick toggles fire two independent save->refresh chains and
+ // whichever response arrives last wins — which may be the older
+ // policy's disabled set.
+ const blocked = [
+ { value: 'OLLAMA', label: 'Ollama 💻 Local', disabled: false },
+ { value: 'DEEPSEEK', label: 'DeepSeek ☁️ Cloud', disabled: true, disabled_reason: 'Blocked by policy' },
+ ];
+ const allowed = [
+ { value: 'OLLAMA', label: 'Ollama 💻 Local', disabled: false },
+ { value: 'DEEPSEEK', label: 'DeepSeek ☁️ Cloud', disabled: false },
+ ];
+
+ // Model the backend: provider_options is derived from whatever
+ // policy is currently saved, so the response depends on the PUTs
+ // that landed before it. The refresh that survives must therefore
+ // render the policy in effect after BOTH toggles, not after one.
+ let blockedByPolicy = false;
+ fetchMock.mockImplementation((url, init) => {
+ if (typeof url === 'string' && url.startsWith(AVAILABLE_MODELS)) {
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () =>
+ Promise.resolve({
+ status: 'ok',
+ provider_options: blockedByPolicy ? blocked : allowed,
+ providers: {},
+ }),
+ text: () => Promise.resolve(''),
+ });
+ }
+ if (init?.method === 'PUT' && typeof url === 'string') {
+ const value = JSON.parse(init.body).value;
+ if (url === '/settings/api/policy.egress_scope') {
+ blockedByPolicy = value === 'private_only';
+ } else if (url === '/settings/api/llm.require_local_endpoint') {
+ blockedByPolicy = value === true;
+ }
+ }
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ status: 'ok' }),
+ text: () => Promise.resolve(''),
+ });
+ });
+ fetchMock.mockClear();
+
+ const scope = document.getElementById('policy_egress_scope');
+ const checkbox = document.getElementById('llm_require_local_endpoint');
+
+ // Public-only leaves the local-inference checkbox editable.
+ scope.value = 'public_only';
+ scope.dispatchEvent(new Event('change'));
+ checkbox.checked = true;
+ checkbox.dispatchEvent(new Event('change'));
+
+ await vi.waitFor(
+ () => {
+ const saves = fetchMock.mock.calls.filter(
+ ([u, init]) =>
+ u === '/settings/api/llm.require_local_endpoint' &&
+ init?.method === 'PUT'
+ );
+ expect(saves.length).toBe(1);
+ },
+ { timeout: 1000 }
+ );
+ await flush();
+ await flush();
+
+ // Superseded refresh was dropped: one models fetch, not two.
+ const modelFetches = fetchMock.mock.calls.filter(
+ ([u]) => typeof u === 'string' && u.startsWith(AVAILABLE_MODELS)
+ );
+ expect(modelFetches.length).toBe(1);
+ // The later checkbox save requires local inference even with a
+ // public search scope, so cloud providers must now be disabled.
+ expect(getProviderOption('DEEPSEEK').disabled).toBe(true);
+ });
+});
+
+
+it('ignores an older manual model response after a policy refresh completes', async () => {
+ let resolveManual;
+ const manual = new Promise(resolve => { resolveManual = resolve; });
+ let requestedManual = false;
+ const payload = disabled => ({
+ ok: true,
+ json: async () => ({ providers: {}, provider_options: [
+ { value: 'OPENAI', label: 'OpenAI', disabled },
+ { value: 'OLLAMA', label: 'Ollama', disabled: false },
+ ] }),
+ });
+ fetchMock.mockImplementation((url) => {
+ if (url.startsWith(AVAILABLE_MODELS)) {
+ if (url.includes('force_refresh=true') && !requestedManual) {
+ requestedManual = true;
+ return manual;
+ }
+ return Promise.resolve(payload(true));
+ }
+ return Promise.resolve({ ok: true, json: async () => ({ status: 'ok' }), text: async () => '' });
+ });
+ const provider = document.getElementById('model_provider');
+ provider.innerHTML = '<option value="OPENAI" selected>OpenAI</option>';
+ document.getElementById('model-refresh').click();
+ await vi.waitFor(() => expect(requestedManual).toBe(true));
+ const local = document.getElementById('llm_require_local_endpoint');
+ local.checked = true;
+ local.dispatchEvent(new Event('change'));
+ await vi.waitFor(() => expect(getProviderOption('OPENAI').disabled).toBe(true));
+ expect(provider.value).toBe('');
+ resolveManual(payload(false));
+ await flush();
+ await flush();
+ expect(getProviderOption('OPENAI').disabled).toBe(true);
+ expect(provider.value).toBe('');
+});
+
+it('clears the model loading state when a superseded request rejects', async () => {
+ // The sibling test above drives the .then arm of loadModelOptions' stale
+ // guard; this one drives the .catch arm, which has the same two jobs on the
+ // way out. A superseded response must undo the loading class it added and
+ // leave the models cache holding an array: updateModelOptionsForProvider()
+ // reloads whenever the cache is null, so returning early with it still null
+ // strands the spinner AND issues another request - and because every entry
+ // bumps the generation, two concurrent chains keep each other stale forever.
+ const modelLoading = () => document
+ .getElementById('model')
+ .parentNode.classList.contains('ldr-loading');
+ const modelFetches = () => fetchMock.mock.calls.filter(
+ ([u]) => typeof u === 'string' && u.startsWith(AVAILABLE_MODELS)
+ ).length;
+ const providerPayload = (providerOptions) => ({
+ ok: true,
+ status: 200,
+ json: async () => ({
+ status: 'ok',
+ providers: {},
+ provider_options: providerOptions,
+ }),
+ text: async () => '',
+ });
+ let rejectManual;
+ const manual = new Promise((_resolve, reject) => { rejectManual = reject; });
+ // The newer request is deferred, not abandoned. While it is unsettled,
+ // nothing but the rejection below can clear the loading state - that is
+ // this test's whole signal - but it is released before the test returns.
+ // research.js chains the policy refresh onto policyScopeSaveQueue, which
+ // is scoped to the setupEventListeners() IIFE and so is unreachable from
+ // beforeEach: a request abandoned in flight would park that queue for
+ // every later test in this file, not just for this one.
+ let resolveNewer;
+ const newer = new Promise((resolve) => { resolveNewer = resolve; });
+ let requestedManual = false;
+ fetchMock.mockImplementation((url) => {
+ if (typeof url === 'string' && url.startsWith(AVAILABLE_MODELS)) {
+ if (url.includes('force_refresh=true') && !requestedManual) {
+ requestedManual = true;
+ return manual;
+ }
+ return newer;
+ }
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: async () => ({ status: 'ok' }),
+ text: async () => '',
+ });
+ });
+
+ document.getElementById('model-refresh').click();
+ await vi.waitFor(() => expect(requestedManual).toBe(true));
+ // A policy toggle supersedes the manual request: it invalidates the models
+ // cache and starts a newer load, which has not answered yet.
+ const local = document.getElementById('llm_require_local_endpoint');
+ local.checked = true;
+ local.dispatchEvent(new Event('change'));
+ await vi.waitFor(() => expect(modelFetches()).toBe(2));
+ expect(modelLoading()).toBe(true);
+
+ const beforeReject = modelFetches();
+ rejectManual(new Error('models endpoint unreachable'));
+ await flush();
+ await flush();
+ await flush();
+
+ try {
+ expect(modelLoading()).toBe(false);
+ expect(modelFetches()).toBe(beforeReject);
+ } finally {
+ // Released in a finally: a failing assertion above must not leave the
+ // queue parked for the tests that follow.
+ resolveNewer(providerPayload([
+ { value: 'OLLAMA', label: 'Ollama' },
+ { value: 'NEWEST_ONLY', label: 'Newest only' },
+ ]));
+ }
+ // The refresh thunk settles only once this response has been rendered, and
+ // the queue's trailing .catch runs on the microtasks right after it.
+ await vi.waitFor(() => expect(getProviderOption('NEWEST_ONLY')).toBeDefined());
+ await flush();
+});
+
+it('keeps the loader bounded when a superseded request succeeds', async () => {
+ // Sibling of the test above, on the other arm. That one rejects, so it can
+ // only reach loadModelOptions' .catch handler; a superseded response that
+ // *succeeds* reaches the .then handler instead, and that is the arm whose
+ // unwind is load-bearing. Reverting only it (back to
+ // `resolve(getCachedData(CACHE_KEYS.MODELS) || [])`) leaves the cache unset
+ // and the loading class on, so the refresh button's own .then re-enters
+ // updateModelOptionsForProvider() -> loadModelOptions(), which bumps the
+ // generation and supersedes the request that is still in flight. Measured
+ // against that single-arm revert: a third request instead of two, and the
+ // spinner stuck on. The fetch-count and loading assertions are what carry
+ // that signal. The dropdown assertions are a positive control that the
+ // newest payload is the one that renders - they hold under the revert too,
+ // because the mock hands the same shared promise to every request after
+ // the first, so the extra request the revert provokes answers with the
+ // newest payload as well.
+ const modelLoading = () => document
+ .getElementById('model')
+ .parentNode.classList.contains('ldr-loading');
+ const modelFetches = () => fetchMock.mock.calls.filter(
+ ([u]) => typeof u === 'string' && u.startsWith(AVAILABLE_MODELS)
+ ).length;
+ const providerPayload = (providerOptions) => ({
+ ok: true,
+ status: 200,
+ json: async () => ({
+ status: 'ok',
+ providers: {},
+ provider_options: providerOptions,
+ }),
+ text: async () => '',
+ });
+ let resolveManual;
+ const manual = new Promise((resolve) => { resolveManual = resolve; });
+ let resolveNewer;
+ const newer = new Promise((resolve) => { resolveNewer = resolve; });
+ let requestedManual = false;
+ fetchMock.mockImplementation((url) => {
+ if (typeof url === 'string' && url.startsWith(AVAILABLE_MODELS)) {
+ if (url.includes('force_refresh=true') && !requestedManual) {
+ requestedManual = true;
+ return manual;
+ }
+ return newer;
+ }
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: async () => ({ status: 'ok' }),
+ text: async () => '',
+ });
+ });
+
+ document.getElementById('model-refresh').click();
+ await vi.waitFor(() => expect(requestedManual).toBe(true));
+ // A policy toggle supersedes the manual request: it invalidates the models
+ // cache and starts a newer load, which has not answered yet. The cache
+ // being unset is what makes the .then unwind matter.
+ const local = document.getElementById('llm_require_local_endpoint');
+ local.checked = true;
+ local.dispatchEvent(new Event('change'));
+ await vi.waitFor(() => expect(modelFetches()).toBe(2));
+ expect(modelLoading()).toBe(true);
+
+ // The superseded request now SUCCEEDS with a well-formed payload.
+ resolveManual(providerPayload([
+ { value: 'STALE_ONLY', label: 'Stale only' },
+ ]));
+ await flush();
+ await flush();
+ await flush();
+
+ try {
+ // No third request, no stranded spinner, and the stale payload never
+ // reaches the dropdown.
+ expect(modelFetches()).toBe(2);
+ expect(modelLoading()).toBe(false);
+ expect(getProviderOption('STALE_ONLY')).toBeUndefined();
+ } finally {
+ // The still-in-flight request is the newest one, so its data is what
+ // renders when it lands. Released in a finally for the same reason as
+ // the sibling test above: policyScopeSaveQueue is waiting on this
+ // request, so a failing assertion must not leave it in flight.
+ resolveNewer(providerPayload([
+ { value: 'OLLAMA', label: 'Ollama' },
+ {
+ value: 'OPENAI',
+ label: 'OpenAI',
+ disabled: true,
+ disabled_reason: 'Blocked by "Require Local LLM Endpoint"',
+ },
+ ]));
+ }
+ await vi.waitFor(() => expect(getProviderOption('OPENAI')).toBeDefined());
+ expect(getProviderOption('OPENAI').disabled).toBe(true);
+ expect(getProviderOption('STALE_ONLY')).toBeUndefined();
+ expect(modelFetches()).toBe(2);
+ expect(modelLoading()).toBe(false);
});
diff --git a/tests/js/components/research-provider-settings-reconcile.test.js b/tests/js/components/research-provider-settings-reconcile.test.js
new file mode 100644
index 0000000000..3ecdcd49d0
--- /dev/null
+++ b/tests/js/components/research-provider-settings-reconcile.test.js
@@ -0,0 +1,181 @@
+/**
+ * Mount-time reconciliation of the saved llm.provider against the policy.
+ *
+ * This is the branch in research.js's loadSettings() that runs when the
+ * settings API reports an ``llm.provider`` that the egress policy has since
+ * blocked — the returning-user case for #5662. It only executes during
+ * initialization, so it needs its own module instance with a settings
+ * response staged before DOMContentLoaded; that is why this lives in a
+ * separate file from research-model-provider.test.js rather than as another
+ * ``it`` block there (same reasoning that split that file off research.test.js).
+ *
+ * The contract: a blocked provider is never selected, nothing is silently
+ * persisted in its place, and the provider's own API key field stays visible
+ * so the user can still see and fix the setting that caused the block.
+ */
+
+import '@js/config/urls.js';
+import '@js/utils/alert-helpers.js';
+import '@js/security/xss-protection.js';
+import '@js/utils/form-validation.js';
+import '@js/components/custom_dropdown.js';
+
+const AVAILABLE_MODELS = '/settings/api/available-models';
+const SETTINGS_BASE = '/settings/api';
+
+// OPENAI is what the user configured and what the settings API still
+// reports; the policy blocks it. LMSTUDIO is the tempting enabled option
+// that must NOT be chosen on the user's behalf.
+const PROVIDERS = [
+ {
+ value: 'OPENAI',
+ label: 'OpenAI ☁️ Cloud',
+ disabled: true,
+ disabled_reason: 'Blocked by "Require Local LLM Endpoint" (cloud-only provider)',
+ },
+ { value: 'LMSTUDIO', label: 'LM Studio 💻 Local', disabled: false },
+];
+
+let fetchMock;
+
+beforeAll(async () => {
+ fetchMock = vi.fn((url) => {
+ if (typeof url === 'string' && url.startsWith(AVAILABLE_MODELS)) {
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () =>
+ Promise.resolve({
+ status: 'ok',
+ provider_options: PROVIDERS,
+ providers: {},
+ }),
+ text: () => Promise.resolve(''),
+ });
+ }
+ if (url === SETTINGS_BASE) {
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () =>
+ Promise.resolve({
+ status: 'ok',
+ settings: {
+ 'llm.provider': { value: 'openai', editable: true },
+ 'llm.model': { value: 'gpt-4o', editable: true },
+ },
+ }),
+ text: () => Promise.resolve(''),
+ });
+ }
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ status: 'ok', engines: [] }),
+ text: () => Promise.resolve(''),
+ });
+ });
+ vi.spyOn(globalThis, 'fetch').mockImplementation(fetchMock);
+ window.api = { getCsrfToken: () => 'test-csrf' };
+ window.RESEARCH_STATUS = { QUEUED: 'queued', IN_PROGRESS: 'in_progress' };
+
+ document.body.innerHTML = `
+ <form id="research-form">
+ <div id="research-alert" role="alert" style="display:none"></div>
+ <div id="research-error-alert" class="ldr-settings-error-container" style="display:none"></div>
+ <textarea id="query" name="query"></textarea>
+
+ <label class="ldr-mode-option"><input type="radio" name="research_mode" value="quick" checked></label>
+
+ <div class="ldr-advanced-options-panel ldr-expanded" id="advanced-options-panel" role="group">
+ <select id="model_provider" data-initial-value="openai">
+ <option value="OPENAI" selected>OpenAI</option>
+ </select>
+ <div id="openai_api_key_container" style="display:none"></div>
+
+ <input type="text" id="model">
+ <input type="hidden" id="model_hidden" value="">
+ <div id="model-dropdown"><div id="model-dropdown-list"></div></div>
+
+ <input type="text" id="search_engine">
+ <input type="hidden" id="search_engine_hidden" value="searxng">
+ <div id="search-engine-dropdown"><div id="search-engine-dropdown-list"></div></div>
+
+ <select id="strategy"><option value="source-based" selected>source-based</option></select>
+ <input id="iterations" value="2">
+ <input id="questions_per_iteration" value="3">
+ </div>
+
+ <button type="submit" id="start-research-btn"><span></span></button>
+ </form>
+ `;
+
+ await import('@js/components/research.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+
+ // loadSettings() is chained off the mount-time loadModelOptions, so wait
+ // for the settings fetch to have been made and its handlers to drain.
+ await vi.waitFor(
+ () => {
+ expect(
+ fetchMock.mock.calls.some(([u]) => u === SETTINGS_BASE)
+ ).toBe(true);
+ },
+ { timeout: 1000 }
+ );
+ await new Promise((r) => setTimeout(r, 0));
+ await new Promise((r) => setTimeout(r, 0));
+});
+
+function providerSelect() {
+ return document.getElementById('model_provider');
+}
+
+describe('mount-time provider reconciliation against the egress policy', () => {
+ it('does not select the saved provider when the policy blocks it', async () => {
+ await vi.waitFor(
+ () => {
+ const openai = Array.from(providerSelect().options).find(
+ (o) => o.value === 'OPENAI'
+ );
+ expect(openai).toBeDefined();
+ expect(openai.disabled).toBe(true);
+ },
+ { timeout: 1000 }
+ );
+
+ expect(providerSelect().value).toBe('');
+ expect(providerSelect().selectedIndex).toBe(-1);
+ });
+
+ it('does not substitute the enabled provider that happens to be available', () => {
+ // LMSTUDIO is selectable, but picking it for the user would submit a
+ // provider they never chose alongside the model saved for OpenAI.
+ expect(providerSelect().value).not.toBe('LMSTUDIO');
+ });
+
+ it('does not persist a replacement provider behind the user\'s back', () => {
+ const providerSaves = fetchMock.mock.calls.filter(
+ ([u, init]) =>
+ u === '/settings/api/llm.provider' && init?.method === 'PUT'
+ );
+ expect(providerSaves).toEqual([]);
+ });
+
+ it('keeps the blocked provider visible with its reason', () => {
+ const openai = Array.from(providerSelect().options).find(
+ (o) => o.value === 'OPENAI'
+ );
+ expect(openai.textContent).toContain('OpenAI');
+ expect(openai.textContent).toContain('Require Local LLM Endpoint');
+ });
+
+ it('still shows the blocked provider\'s API key field so the user can fix it', () => {
+ // activeProvider falls back to the configured provider when the
+ // selection is cleared — the whole point of #5662 was that users
+ // could not tell their key had been saved.
+ expect(
+ document.getElementById('openai_api_key_container').style.display
+ ).toBe('block');
+ });
+});
diff --git a/tests/js/components/research.test.js b/tests/js/components/research.test.js
index 798fd38001..ebd479bd5e 100644
--- a/tests/js/components/research.test.js
+++ b/tests/js/components/research.test.js
@@ -2358,3 +2358,32 @@ describe('research form — LangGraph agent_enabled dropdown filter', () => {
expect(item.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);
});
});
+
+
+it('submits the remembered provider when policy clears the visible selection', async () => {
+ // A pending settings PUT can leave the DB on a previous provider.
+ // The request must carry the latest choice so server policy checks
+ // that provider instead of falling back to the stale saved default.
+ const provider = document.getElementById('model_provider');
+ const previousValue = provider.value;
+ const previousInitial = provider.getAttribute('data-initial-value');
+ try {
+ provider.setAttribute('data-initial-value', 'DEEPSEEK');
+ provider.value = '';
+ document.getElementById('model_hidden').value = 'deepseek-chat';
+
+ submitForm();
+
+ const calls = callsTo(START_RESEARCH);
+ expect(calls).toHaveLength(1);
+ const payload = JSON.parse(calls[0][1].body);
+ expect(payload.model_provider).toBe('DEEPSEEK');
+ expect(payload.model).toBe('deepseek-chat');
+ await Promise.resolve();
+ await Promise.resolve();
+ } finally {
+ provider.value = previousValue;
+ if (previousInitial === null) provider.removeAttribute('data-initial-value');
+ else provider.setAttribute('data-initial-value', previousInitial);
+ }
+});
diff --git a/tests/js/components/settings-provider-options-disabled.test.js b/tests/js/components/settings-provider-options-disabled.test.js
new file mode 100644
index 0000000000..09831e8174
--- /dev/null
+++ b/tests/js/components/settings-provider-options-disabled.test.js
@@ -0,0 +1,114 @@
+/**
+ * The Settings page must carry the policy's ``disabled`` / ``disabled_reason``
+ * flags from /settings/api/available-models through to the provider dropdown.
+ *
+ * ``custom_dropdown.js`` already knows how to render a greyed item with its
+ * reason (see custom-dropdown.test.js, added for #5204). The only thing
+ * standing between the API response and that renderer is the ``.map()`` in
+ * settings.js's processModelData — drop a field there and blocked providers
+ * silently become selectable again on the Settings page, which is exactly the
+ * regression #5662 fixed on the New Research page.
+ *
+ * Strategy mirrors settings-model-data.test.js: processModelData lives inside
+ * an IIFE and is never exposed, so we extract the literal source of the
+ * provider_options block and execute it. That way the test tracks the shipped
+ * code rather than a re-implementation, and it fails loudly if the block is
+ * refactored away.
+ */
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const SETTINGS_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/static/js/components/settings.js',
+);
+
+const MARKER = 'if (\n Array.isArray(data.provider_options) &&';
+
+/** Extract the whole `if (Array.isArray(data.provider_options) ...) { ... }` statement. */
+function extractProviderOptionsBlock(source) {
+ const start = source.indexOf(MARKER);
+ if (start < 0) {
+ throw new Error(
+ 'Could not find the provider_options block in settings.js — ' +
+ 'it may have been refactored. Update this test.',
+ );
+ }
+ const openBrace = source.indexOf('{', source.indexOf(')', start));
+ let depth = 0;
+ let i = openBrace;
+ for (; i < source.length; i++) {
+ const ch = source[i];
+ if (ch === '{') depth++;
+ else if (ch === '}') {
+ depth--;
+ if (depth === 0) break;
+ }
+ }
+ if (depth !== 0) {
+ throw new Error('Brace mismatch when extracting the provider_options block.');
+ }
+ return source.slice(start, i + 1);
+}
+
+/** Run the extracted block against a synthetic response, return the result. */
+function runBlock(data) {
+ const block = extractProviderOptionsBlock(readFileSync(SETTINGS_PATH, 'utf8'));
+ // Running the shipped source is the whole point — a re-implementation
+ // here would pass while production dropped the field.
+ // eslint-disable-next-line no-new-func
+ const fn = new Function(
+ 'data',
+ 'SafeLogger',
+ `let discoveredProviderOptions = null;\n${block}\nreturn discoveredProviderOptions;`,
+ );
+ return fn(data, { log() {}, warn() {}, error() {} });
+}
+
+describe('settings.js — provider_options disabled passthrough', () => {
+ it('preserves disabled and disabled_reason for a blocked provider', () => {
+ const result = runBlock({
+ provider_options: [
+ { value: 'OLLAMA', label: 'Ollama 💻 Local' },
+ {
+ value: 'DEEPSEEK',
+ label: 'DeepSeek ☁️ Cloud',
+ disabled: true,
+ disabled_reason: 'Blocked by "Require Local LLM Endpoint" (cloud-only provider)',
+ },
+ ],
+ });
+
+ expect(result).toHaveLength(2);
+ const deepseek = result.find(o => o.value === 'DEEPSEEK');
+ expect(deepseek.disabled).toBe(true);
+ expect(deepseek.disabled_reason).toContain('Require Local LLM Endpoint');
+ expect(deepseek.label).toBe('DeepSeek ☁️ Cloud');
+ });
+
+ it('normalizes an unblocked provider to disabled:false / reason:null', () => {
+ // custom_dropdown.js checks `item.disabled`; leaving it undefined
+ // would work by accident today but is not a contract worth relying on.
+ const result = runBlock({
+ provider_options: [{ value: 'OLLAMA', label: 'Ollama 💻 Local' }],
+ });
+
+ expect(result[0].disabled).toBe(false);
+ expect(result[0].disabled_reason).toBeNull();
+ });
+
+ it('does not treat a truthy non-true disabled value as blocked', () => {
+ const result = runBlock({
+ provider_options: [
+ { value: 'OLLAMA', label: 'Ollama', disabled: 'no' },
+ ],
+ });
+
+ expect(result[0].disabled).toBe(false);
+ });
+
+ it('leaves the discovered list untouched when the response has none', () => {
+ expect(runBlock({ provider_options: [] })).toBeNull();
+ expect(runBlock({})).toBeNull();
+ });
+});
diff --git a/tests/js/pages/benchmark-endpoint-runtime.test.js b/tests/js/pages/benchmark-endpoint-runtime.test.js
index 6d20cf542a..295eba7f7a 100644
--- a/tests/js/pages/benchmark-endpoint-runtime.test.js
+++ b/tests/js/pages/benchmark-endpoint-runtime.test.js
@@ -75,10 +75,29 @@ function compileSaveEvaluationSetting(csrfToken) {
return factory(csrfToken);
}
-function compileEvaluationModelsHarness() {
+// startBenchmark's second gate reads saveEvaluationSetting.pending and
+// .failedKeys. Compiling the function with `saveEvaluationSetting` left
+// undeclared makes `typeof saveEvaluationSetting === 'function'` false, so that
+// whole clause is unreachable and a full revert of it would be caught by
+// nothing. Binding it as a parameter makes it testable; callers that pass
+// nothing get the previous behaviour exactly, since an unsupplied parameter is
+// `undefined` and `typeof undefined` is still not 'function'.
+function compileStartBenchmark(showAlert, saveEvaluationSetting) {
+ const source = extractFunction(templateSource(), 'startBenchmark');
+ const factory = new Function( // eslint-disable-line no-new-func
+ 'showAlert',
+ 'saveEvaluationSetting',
+ `let benchmarkStartInFlight = false; ${source}; return startBenchmark;`,
+ );
+ return factory(showAlert, saveEvaluationSetting);
+}
+
+function compileEvaluationModelsHarness(initialProviders = []) {
const source = templateSource();
const functions = [
'debounce',
+ 'applyEvaluationProvider',
+ 'isOpenAIEndpointProvider',
'populateEvaluationProviders',
'setupEvaluationModelDropdown',
'getEvaluationModelOptions',
@@ -91,7 +110,7 @@ function compileEvaluationModelsHarness() {
const factory = new Function( // eslint-disable-line no-new-func
`
const csrfToken = 'csrf-benchmark';
- let EVAL_MODEL_PROVIDERS = [];
+ let EVAL_MODEL_PROVIDERS = ${JSON.stringify(initialProviders)};
let evaluationModelsRequestVersion = 0;
let evaluationProviderSelect = document.getElementById('evaluation_provider');
let evaluationModelInput = document.getElementById('evaluation_model');
@@ -110,12 +129,29 @@ function compileEvaluationModelsHarness() {
return factory();
}
+// Option values as /settings/api/available-models really emits them: the
+// provider key from auto_discovery.ProviderInfo, which is the class-level
+// `provider_key` ("OPENAI", "OLLAMA", ...) upper-cased. The per-provider
+// model map is keyed separately and IS lower-case (`openai_models`), which is
+// why the template lower-cases the selected value before looking models up.
+const PROVIDER_OPTIONS = [
+ { value: 'OPENAI', label: 'OpenAI' },
+ { value: 'OLLAMA', label: 'Ollama' },
+];
+
+// getEvaluationModelOptions' "while loading" fallback for OpenAI. The same list
+// has to come back for both spellings of the provider, which is why the two
+// tests below assert against this one constant.
+const OPENAI_DEFAULT_MODELS = [
+ { value: 'gpt-4o', label: 'GPT-4o' },
+ { value: 'gpt-4', label: 'GPT-4' },
+ { value: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo' },
+];
+
function modelsPayload(modelValue, modelLabel = modelValue) {
return {
- provider_options: [
- { value: 'openai', label: 'OpenAI' },
- { value: 'ollama', label: 'Ollama' },
- ],
+ provider_options: PROVIDER_OPTIONS.map(provider => ({ ...provider })),
+ benchmark_provider_options: PROVIDER_OPTIONS.map(provider => ({ ...provider })),
providers: {
openai_models: [{ value: modelValue, label: modelLabel }],
ollama_models: [{ value: 'nomic-embed-text', label: 'Nomic' }],
@@ -131,9 +167,12 @@ function deferred() {
return { promise, resolve: resolveDeferred };
}
-function renderEvaluationControls() {
+// `data-initial-value` is the stored benchmark.evaluation.provider echoed
+// verbatim. Defaults may be lower-case while live options use upper-case;
+// provider reconciliation handles both forms.
+function renderEvaluationControls(initialProvider = 'OPENAI') {
document.body.innerHTML = `
- <select id="evaluation_provider" data-initial-value="openai"></select>
+ <select id="evaluation_provider"></select>
<div><input id="evaluation_endpoint_url"></div>
<div data-target="evaluation-model-dropdown">
<input id="evaluation_model">
@@ -142,6 +181,9 @@ function renderEvaluationControls() {
<button class="refresh-btn"><i></i></button>
</div>
`;
+ document
+ .getElementById('evaluation_provider')
+ .setAttribute('data-initial-value', initialProvider);
window.setupCustomDropdown = vi.fn(() => ({ setValue: vi.fn() }));
window.updateDropdownOptions = vi.fn();
window.evaluationModels = {};
@@ -224,7 +266,8 @@ it('keeps the active benchmark intact when cancellation is rejected', async () =
it('saves an evaluation setting with the FastAPI value envelope and CSRF', async () => {
const fetchMock = vi.fn().mockResolvedValue({
- json: vi.fn().mockResolvedValue({ success: true }),
+ ok: true,
+ json: vi.fn().mockResolvedValue({ message: 'Setting benchmark.evaluation.temperature updated successfully' }),
});
vi.stubGlobal('fetch', fetchMock);
vi.spyOn(console, 'log').mockImplementation(() => {});
@@ -261,7 +304,7 @@ it('loads and force-refreshes evaluation providers and model options', async ()
});
vi.stubGlobal('fetch', fetchMock);
vi.spyOn(console, 'log').mockImplementation(() => {});
- const harness = compileEvaluationModelsHarness();
+ const harness = compileEvaluationModelsHarness(PROVIDER_OPTIONS);
harness.populateEvaluationProviders();
harness.setupEvaluationModelDropdown();
@@ -279,8 +322,8 @@ it('loads and force-refreshes evaluation providers and model options', async ()
expect(fetchMock.mock.calls[1][0])
.toBe('/settings/api/available-models?force_refresh=true');
expect(harness.getProviders()).toEqual([
- { value: 'openai', label: 'OpenAI' },
- { value: 'ollama', label: 'Ollama' },
+ { value: 'OPENAI', label: 'OpenAI' },
+ { value: 'OLLAMA', label: 'Ollama' },
]);
expect(window.evaluationModels.openai).toEqual([
{ value: 'fresh-model', label: 'Fresh Model' },
@@ -294,7 +337,10 @@ it('loads and force-refreshes evaluation providers and model options', async ()
});
it('starts the initial model request when an empty dropdown asks for options', async () => {
- renderEvaluationControls();
+ // Before the API answers, populateEvaluationProviders() falls back to the
+ // template's own hard-coded provider list, which is lower-case; this test
+ // deliberately stays on that path.
+ renderEvaluationControls('openai');
vi.useFakeTimers();
const fetchMock = vi.fn().mockResolvedValue({
json: vi.fn().mockResolvedValue(modelsPayload('initial-model')),
@@ -304,11 +350,7 @@ it('starts the initial model request when an empty dropdown asks for options', a
const harness = compileEvaluationModelsHarness();
harness.populateEvaluationProviders();
- expect(harness.getEvaluationModelOptions()).toEqual([
- { value: 'gpt-4o', label: 'GPT-4o' },
- { value: 'gpt-4', label: 'GPT-4' },
- { value: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo' },
- ]);
+ expect(harness.getEvaluationModelOptions()).toEqual(OPENAI_DEFAULT_MODELS);
expect(fetchMock).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(500);
@@ -328,12 +370,18 @@ it('does not schedule a fallback request while force refresh is in flight', asyn
const fetchMock = vi.fn().mockReturnValue(refreshResponse.promise);
vi.stubGlobal('fetch', fetchMock);
vi.spyOn(console, 'log').mockImplementation(() => {});
- const harness = compileEvaluationModelsHarness();
+ const harness = compileEvaluationModelsHarness(PROVIDER_OPTIONS);
harness.populateEvaluationProviders();
harness.setupEvaluationModelDropdown();
document.querySelector('.refresh-btn').click();
- harness.getEvaluationModelOptions();
+ // populateEvaluationProviders() selected the provider under the API's
+ // spelling, so this call goes through the same "while loading" fallback as
+ // the lower-case test above but with an upper-cased value. It has to return
+ // the same list: matching the raw select value instead of the normalised
+ // key drops it to the empty list here, even though the cached lookup
+ // higher up in the function already lower-cases.
+ expect(harness.getEvaluationModelOptions()).toEqual(OPENAI_DEFAULT_MODELS);
await vi.advanceTimersByTimeAsync(500);
expect(fetchMock).toHaveBeenCalledOnce();
@@ -353,16 +401,16 @@ it('keeps the selected provider while force refresh rebuilds its options', async
json: vi.fn().mockResolvedValue(modelsPayload('fresh-openai')),
}));
vi.spyOn(console, 'log').mockImplementation(() => {});
- const harness = compileEvaluationModelsHarness();
+ const harness = compileEvaluationModelsHarness(PROVIDER_OPTIONS);
harness.populateEvaluationProviders();
harness.setupEvaluationModelDropdown();
const provider = document.getElementById('evaluation_provider');
- provider.value = 'ollama';
+ provider.value = 'OLLAMA';
document.querySelector('.refresh-btn').click();
await flushPromises();
- expect(provider.value).toBe('ollama');
+ expect(provider.value).toBe('OLLAMA');
expect(window.updateDropdownOptions).toHaveBeenLastCalledWith(
document.getElementById('evaluation_model'),
[{ value: 'nomic-embed-text', label: 'Nomic' }],
@@ -380,7 +428,7 @@ it('does not let a deferred initial model response overwrite a force refresh', a
});
vi.stubGlobal('fetch', fetchMock);
vi.spyOn(console, 'log').mockImplementation(() => {});
- const harness = compileEvaluationModelsHarness();
+ const harness = compileEvaluationModelsHarness(PROVIDER_OPTIONS);
harness.populateEvaluationProviders();
harness.setupEvaluationModelDropdown();
@@ -416,7 +464,7 @@ it('keeps the newest result when force-refresh responses finish out of order', a
.mockReturnValueOnce(secondRefresh.promise);
vi.stubGlobal('fetch', fetchMock);
vi.spyOn(console, 'log').mockImplementation(() => {});
- const harness = compileEvaluationModelsHarness();
+ const harness = compileEvaluationModelsHarness(PROVIDER_OPTIONS);
harness.populateEvaluationProviders();
harness.setupEvaluationModelDropdown();
@@ -453,7 +501,7 @@ it('cancels the pending debounced load when refresh is requested immediately', a
});
vi.stubGlobal('fetch', fetchMock);
vi.spyOn(console, 'log').mockImplementation(() => {});
- const harness = compileEvaluationModelsHarness();
+ const harness = compileEvaluationModelsHarness(PROVIDER_OPTIONS);
harness.populateEvaluationProviders();
harness.setupEvaluationModelDropdown();
@@ -467,3 +515,507 @@ it('cancels the pending debounced load when refresh is requested immediately', a
.toBe('/settings/api/available-models?force_refresh=true');
expect(window.evaluationModels.openai[0].value).toBe('manual-model');
});
+
+
+it('clears a provider that becomes blocked during model refresh', async () => {
+ renderEvaluationControls();
+ const payload = modelsPayload('fresh-openai');
+ payload.benchmark_provider_options = payload.benchmark_provider_options.map(provider => ({
+ ...provider,
+ disabled: provider.value === 'OLLAMA',
+ disabled_reason: provider.value === 'OLLAMA' ? 'Endpoint is not local' : null,
+ }));
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue(payload),
+ }));
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const harness = compileEvaluationModelsHarness(PROVIDER_OPTIONS);
+ harness.populateEvaluationProviders();
+ harness.setupEvaluationModelDropdown();
+ const provider = document.getElementById('evaluation_provider');
+ provider.value = 'OLLAMA';
+ // The guard has to be what clears it: assert it was actually selectable
+ // before the refresh, or a silent no-match would pass this test.
+ expect(provider.value).toBe('OLLAMA');
+
+ document.querySelector('.refresh-btn').click();
+ await flushPromises();
+
+ expect(provider.value).toBe('');
+ const blocked = Array.from(provider.options).find(option => option.value === 'OLLAMA');
+ expect(blocked.disabled).toBe(true);
+ expect(blocked.textContent).toContain('Endpoint is not local');
+});
+
+// Option values once an OpenAI-compatible endpoint is configured, as
+// /settings/api/available-models emits them: upper-case, while the stored
+// benchmark.evaluation.provider that seeds `data-initial-value` is
+// lower-case. The endpoint URL input is the only control that can repair a
+// blocked endpoint, so it has to follow the remembered provider under either
+// spelling.
+const ENDPOINT_PROVIDER_OPTIONS = [
+ { value: 'OPENAI_ENDPOINT', label: 'OpenAI-Compatible Endpoint' },
+ { value: 'OLLAMA', label: 'Ollama' },
+];
+
+function endpointProviderPayload(blockEndpoint = false) {
+ const block = provider => blockEndpoint && provider.value === 'OPENAI_ENDPOINT';
+ return {
+ providers: {},
+ provider_options: ENDPOINT_PROVIDER_OPTIONS.map(provider => ({ ...provider })),
+ benchmark_provider_options: ENDPOINT_PROVIDER_OPTIONS.map(provider => ({
+ ...provider,
+ disabled: block(provider),
+ disabled_reason: block(provider) ? 'Endpoint is not local' : null,
+ })),
+ };
+}
+
+function endpointRowDisplay() {
+ return document.getElementById('evaluation_endpoint_url').parentNode.style.display;
+}
+
+it('keeps the endpoint URL field visible when a refresh returns the saved provider upper-cased', async () => {
+ renderEvaluationControls('openai_endpoint');
+ vi.stubGlobal('fetch', vi.fn().mockImplementation(async () => ({
+ json: async () => endpointProviderPayload(),
+ })));
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const harness = compileEvaluationModelsHarness(ENDPOINT_PROVIDER_OPTIONS);
+ harness.populateEvaluationProviders();
+ harness.setupEvaluationModelDropdown();
+ expect(endpointRowDisplay()).toBe('block');
+
+ document.querySelector('.refresh-btn').click();
+ await flushPromises();
+
+ // The refresh re-selects the same provider under the API's spelling, so
+ // the field holding that provider's endpoint URL must survive it.
+ const select = document.getElementById('evaluation_provider');
+ expect(select.value).toBe('OPENAI_ENDPOINT');
+ expect(endpointRowDisplay()).toBe('block');
+});
+
+it('keeps the endpoint URL field visible when the saved endpoint provider is blocked by policy', async () => {
+ renderEvaluationControls('openai_endpoint');
+ vi.stubGlobal('fetch', vi.fn().mockImplementation(async () => ({
+ json: async () => endpointProviderPayload(true),
+ })));
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const harness = compileEvaluationModelsHarness(ENDPOINT_PROVIDER_OPTIONS);
+ harness.populateEvaluationProviders();
+ harness.setupEvaluationModelDropdown();
+ const select = document.getElementById('evaluation_provider');
+
+ document.querySelector('.refresh-btn').click();
+ await flushPromises();
+
+ // The selection is cleared because the endpoint is refused, which leaves
+ // the endpoint URL field as the only control that can correct it.
+ expect(select.value).toBe('');
+ expect(select.dataset.initialValue).toBe('OPENAI_ENDPOINT');
+ expect(endpointRowDisplay()).toBe('block');
+
+ // A further refresh reaches the fallback with the remembered provider
+ // already stored upper-cased, the shape the raw comparison missed.
+ document.querySelector('.refresh-btn').click();
+ await flushPromises();
+
+ expect(select.value).toBe('');
+ expect(endpointRowDisplay()).toBe('block');
+});
+
+it('hides the endpoint URL field for a saved provider that does not use one', async () => {
+ renderEvaluationControls('ollama');
+ vi.stubGlobal('fetch', vi.fn().mockImplementation(async () => ({
+ json: async () => endpointProviderPayload(),
+ })));
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const harness = compileEvaluationModelsHarness(ENDPOINT_PROVIDER_OPTIONS);
+ harness.populateEvaluationProviders();
+ harness.setupEvaluationModelDropdown();
+
+ document.querySelector('.refresh-btn').click();
+ await flushPromises();
+
+ expect(document.getElementById('evaluation_provider').value).toBe('OLLAMA');
+ expect(endpointRowDisplay()).toBe('none');
+});
+
+
+it('uses evaluation availability even when the research endpoint is blocked', async () => {
+ renderEvaluationControls('openai');
+ const payload = modelsPayload('evaluation-model');
+ payload.provider_options[0].disabled = true;
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => payload }));
+ const harness = compileEvaluationModelsHarness();
+ harness.populateEvaluationProviders();
+ harness.setupEvaluationModelDropdown();
+ document.querySelector('.refresh-btn').click();
+ await flushPromises();
+ const select = document.getElementById('evaluation_provider');
+ expect(select.value).toBe('OPENAI');
+ expect(select.selectedOptions[0].disabled).toBe(false);
+});
+
+it('takes initial-load evaluation availability from benchmark_provider_options, not provider_options', async () => {
+ // The refresh-button site is covered above ('uses evaluation availability
+ // even when the research endpoint is blocked'); this is the same divergence
+ // through the initial-load handler, which runs on every page load. Reverting
+ // that handler to `EVAL_MODEL_PROVIDERS = data.provider_options` swaps the
+ // two disabled sets below, so OPENAI would be cleared and OLLAMA offered.
+ renderEvaluationControls('openai');
+ vi.useFakeTimers();
+ const payload = modelsPayload('evaluation-model');
+ // Research: OPENAI blocked. Grading: OLLAMA blocked, OPENAI available.
+ payload.provider_options = payload.provider_options.map(provider => ({
+ ...provider,
+ disabled: provider.value === 'OPENAI',
+ disabled_reason: provider.value === 'OPENAI' ? 'Research endpoint is not local' : null,
+ }));
+ payload.benchmark_provider_options = payload.benchmark_provider_options.map(provider => ({
+ ...provider,
+ disabled: provider.value === 'OLLAMA',
+ disabled_reason: provider.value === 'OLLAMA' ? 'Evaluation endpoint is not local' : null,
+ }));
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => payload }));
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const harness = compileEvaluationModelsHarness();
+ harness.populateEvaluationProviders();
+ const select = document.getElementById('evaluation_provider');
+ select.dataset.policyPending = 'true';
+
+ harness.loadEvaluationModelsFromAPI();
+ await vi.advanceTimersByTimeAsync(500);
+ await flushPromises();
+
+ expect(harness.getProviders()).toEqual(payload.benchmark_provider_options);
+ expect(select.value).toBe('OPENAI');
+ expect(select.selectedOptions[0].disabled).toBe(false);
+ const grading = Array.from(select.options).find(option => option.value === 'OLLAMA');
+ expect(grading.disabled).toBe(true);
+ expect(grading.textContent).toContain('Evaluation endpoint is not local');
+ expect(select.dataset.policyPending).toBeUndefined();
+});
+
+it('keeps the start gate armed when the initial load advertises no evaluation providers', async () => {
+ // Array.isArray([]) is true, so an empty list used to delete policyPending
+ // while populateEvaluationProviders() fell back to the template's hardcoded
+ // provider list, whose entries carry no `disabled` flag - re-selecting the
+ // saved provider as an enabled option and letting the start gate pass.
+ renderEvaluationControls('openai');
+ vi.useFakeTimers();
+ const payload = modelsPayload('evaluation-model');
+ payload.benchmark_provider_options = [];
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: async () => payload }));
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const harness = compileEvaluationModelsHarness();
+ harness.populateEvaluationProviders();
+ const select = document.getElementById('evaluation_provider');
+ select.dataset.policyPending = 'true';
+
+ harness.loadEvaluationModelsFromAPI();
+ await vi.advanceTimersByTimeAsync(500);
+ await flushPromises();
+
+ expect(harness.getProviders()).toEqual([]);
+ expect(select.dataset.policyPending).toBe('true');
+ // The hardcoded fallback is still rendered and still looks selectable, so
+ // policyPending is the only thing standing between it and a blocked
+ // grading call: assert the gate itself, not just the flag.
+ expect(select.value).toBe('openai');
+ const showAlert = vi.fn();
+ const start = compileStartBenchmark(showAlert);
+ // The gate has to return before the rest of startBenchmark runs: the
+ // compiled wrapper deliberately leaves everything past it undefined, so a
+ // gate that lets the start through surfaces here instead of posting.
+ let startError = null;
+ try {
+ await start();
+ } catch (error) {
+ startError = error;
+ }
+ expect(startError).toBeNull();
+ expect(showAlert).toHaveBeenCalledWith(
+ expect.stringContaining('available evaluation provider'),
+ 'warning',
+ );
+});
+
+it('does not start a benchmark while the selected evaluation provider is disabled', async () => {
+ // Covers startBenchmark's selectedOptions[0]?.disabled clause on its own:
+ // the value is set and policyPending is resolved, so neither of the other
+ // two clauses can be what blocks the start.
+ renderEvaluationControls();
+ const select = document.getElementById('evaluation_provider');
+ const showAlert = vi.fn();
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+ const start = compileStartBenchmark(showAlert);
+
+ // A blocked provider arrives flagged rather than omitted, so the option
+ // exists and can still be the selected one.
+ const blocked = document.createElement('option');
+ blocked.value = 'OPENAI';
+ blocked.textContent = 'OpenAI - Blocked by "Require Local LLM Endpoint"';
+ blocked.disabled = true;
+ select.appendChild(blocked);
+ select.value = 'OPENAI';
+ delete select.dataset.policyPending;
+
+ await start();
+
+ // Pin that the disabled clause is what fired, not an empty value or a
+ // pending policy.
+ expect(select.value).toBe('OPENAI');
+ expect(select.selectedOptions[0].disabled).toBe(true);
+ expect(select.dataset.policyPending).toBeUndefined();
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(showAlert).toHaveBeenCalledWith(
+ expect.stringContaining('available evaluation provider'),
+ 'warning',
+ );
+});
+
+it('does not start a benchmark with cleared or unresolved evaluation availability', async () => {
+ renderEvaluationControls();
+ const select = document.getElementById('evaluation_provider');
+ const showAlert = vi.fn();
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+ const start = compileStartBenchmark(showAlert);
+ await start();
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(showAlert).toHaveBeenCalledWith(expect.stringContaining('available evaluation provider'), 'warning');
+ const option = document.createElement('option');
+ option.value = 'OPENAI';
+ option.textContent = 'OpenAI';
+ select.appendChild(option);
+ select.value = 'OPENAI';
+ select.dataset.policyPending = 'true';
+ showAlert.mockClear();
+ await start();
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(showAlert).toHaveBeenCalledOnce();
+});
+
+function selectableEvaluationProvider() {
+ const select = document.getElementById('evaluation_provider');
+ const option = document.createElement('option');
+ option.value = 'OPENAI';
+ option.textContent = 'OpenAI';
+ select.appendChild(option);
+ select.value = 'OPENAI';
+ delete select.dataset.policyPending;
+ return select;
+}
+
+it('does not start a benchmark while an evaluation setting save is still in flight', async () => {
+ // The first gate is deliberately satisfied - the provider is selected,
+ // enabled and not pending - so the save gate is the only thing left that
+ // can block the start.
+ renderEvaluationControls();
+ const select = selectableEvaluationProvider();
+ const showAlert = vi.fn();
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+ const saveEvaluationSetting = vi.fn(() => Promise.resolve(true));
+ saveEvaluationSetting.pending = 1;
+ saveEvaluationSetting.failedKeys = new Set();
+ const start = compileStartBenchmark(showAlert, saveEvaluationSetting);
+
+ await start();
+
+ expect(select.value).toBe('OPENAI');
+ expect(select.selectedOptions[0].disabled).toBe(false);
+ expect(select.dataset.policyPending).toBeUndefined();
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(showAlert).toHaveBeenCalledWith(
+ expect.stringContaining('finish saving evaluation settings'),
+ 'warning',
+ );
+
+ // Control: with nothing pending and nothing failed the gate must let the
+ // start through, or a stub that blocks unconditionally would pass the two
+ // assertions above. Everything past the gate is left undefined in the
+ // compiled wrapper, so getting there surfaces as a throw rather than a POST.
+ showAlert.mockClear();
+ saveEvaluationSetting.pending = 0;
+ let startError = null;
+ try {
+ await start();
+ } catch (error) {
+ startError = error;
+ }
+ expect(startError).not.toBeNull();
+ expect(showAlert).not.toHaveBeenCalled();
+});
+
+it('does not start a benchmark while an evaluation setting save has failed', async () => {
+ // Same gate, other clause: pending is back to 0 but a key is still in
+ // failedKeys, so the settings the grader would read are not the ones on
+ // screen.
+ renderEvaluationControls();
+ const select = selectableEvaluationProvider();
+ const showAlert = vi.fn();
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+ const saveEvaluationSetting = vi.fn(() => Promise.resolve(false));
+ saveEvaluationSetting.pending = 0;
+ saveEvaluationSetting.failedKeys = new Set(['benchmark.evaluation.provider']);
+ const start = compileStartBenchmark(showAlert, saveEvaluationSetting);
+
+ await start();
+
+ expect(select.selectedOptions[0].disabled).toBe(false);
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(showAlert).toHaveBeenCalledWith(
+ expect.stringContaining('finish saving evaluation settings'),
+ 'warning',
+ );
+
+ // Control: clearing the failed key must reopen the gate.
+ showAlert.mockClear();
+ saveEvaluationSetting.failedKeys.clear();
+ let startError = null;
+ try {
+ await start();
+ } catch (error) {
+ startError = error;
+ }
+ expect(startError).not.toBeNull();
+ expect(showAlert).not.toHaveBeenCalled();
+});
+
+it('serializes evaluation saves and retains failed keys until that key is retried', async () => {
+ const first = deferred();
+ const fetchMock = vi.fn()
+ .mockReturnValueOnce(first.promise)
+ .mockResolvedValue({ ok: true, json: async () => ({ message: 'Setting updated successfully' }) });
+ vi.stubGlobal('fetch', fetchMock);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const save = compileSaveEvaluationSetting('csrf-test');
+ const failed = save('benchmark.evaluation.provider', 'openai');
+ const next = save('benchmark.evaluation.temperature', 0.5);
+ await flushPromises();
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(save.pending).toBe(2);
+ first.resolve({ ok: false, json: async () => ({ success: false }) });
+ expect(await failed).toBe(false);
+ expect(await next).toBe(true);
+ expect(save.failedKeys.has('benchmark.evaluation.provider')).toBe(true);
+ expect(save.pending).toBe(0);
+ expect(await save('benchmark.evaluation.provider', 'ollama')).toBe(true);
+ expect(save.failedKeys.size).toBe(0);
+});
+
+it('keeps saving after a rejected link in the save queue', async () => {
+ // saveEvaluationSetting chains on BOTH settlements (`.then(save, save)`).
+ // With a plain `.then(save)` a rejected predecessor skips `save` entirely,
+ // so its `.finally()` never runs: `pending` stays up for the life of the
+ // page and startBenchmark's "finish saving" gate never reopens - and the
+ // promise handed back to the caller rejects instead of reporting false.
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ message: 'Setting updated successfully' }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const save = compileSaveEvaluationSetting('csrf-test');
+ const poisoned = Promise.reject(new Error('previous queue link rejected'));
+ // The chain below is what handles it; this only keeps the unhandled
+ // rejection reporter quiet in the window before that.
+ poisoned.catch(() => {});
+ save.queue = poisoned;
+
+ let rejection = null;
+ const result = await save('benchmark.evaluation.provider', 'openai')
+ .catch((error) => { rejection = error; return 'REJECTED'; });
+
+ expect(rejection).toBeNull();
+ expect(result).toBe(true);
+ expect(save.pending).toBe(0);
+ expect(fetchMock).toHaveBeenCalledOnce();
+
+ // The queue is usable again, so the gate can reopen.
+ expect(await save('benchmark.evaluation.temperature', 0.5)).toBe(true);
+ expect(save.pending).toBe(0);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+});
+
+it('reports a value it cannot serialise instead of leaking a pending save', async () => {
+ // The other half of the same totality guard, and the only shape that
+ // reaches it: `save` runs as a .then(save, save) handler, so a synchronous
+ // throw while building the request - JSON.stringify on a value it cannot
+ // represent - rejects the queue itself. The .finally() that brings
+ // `pending` back down is attached to the chain `save` RETURNS, so a throw
+ // before that return leaks the increment: `pending` stays up for the life
+ // of the page, startBenchmark's "finish saving" gate never reopens, and
+ // the caller gets a rejection instead of the documented false. Without the
+ // try/catch this resolves to 'REJECTED' with pending stuck at 1.
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ message: 'Setting updated successfully' }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const save = compileSaveEvaluationSetting('csrf-test');
+
+ let rejection = null;
+ const result = await save('benchmark.evaluation.temperature', 1n)
+ .catch((error) => { rejection = error; return 'REJECTED'; });
+
+ expect(rejection).toBeNull();
+ expect(result).toBe(false);
+ expect(save.pending).toBe(0);
+ expect(save.failedKeys.has('benchmark.evaluation.temperature')).toBe(true);
+ // The throw happens while evaluating the request body, so nothing is sent.
+ expect(fetchMock).not.toHaveBeenCalled();
+
+ // The queue survives it, so the gate can reopen.
+ expect(await save('benchmark.evaluation.temperature', 0.5)).toBe(true);
+ expect(save.pending).toBe(0);
+ expect(save.failedKeys.size).toBe(0);
+ expect(fetchMock).toHaveBeenCalledOnce();
+});
+
+
+it('retains the latest intended evaluation provider across repeated blocked refreshes', async () => {
+ renderEvaluationControls('OPENAI');
+ let blocked = false;
+ const payload = () => ({
+ providers: {},
+ provider_options: PROVIDER_OPTIONS,
+ benchmark_provider_options: PROVIDER_OPTIONS.map(p => ({ ...p, disabled: p.value === 'OLLAMA' && blocked })),
+ });
+ vi.stubGlobal('fetch', vi.fn().mockImplementation(async () => ({ json: async () => payload() })));
+ const harness = compileEvaluationModelsHarness(PROVIDER_OPTIONS);
+ harness.populateEvaluationProviders();
+ harness.setupEvaluationModelDropdown();
+ const select = document.getElementById('evaluation_provider');
+ select.value = 'OLLAMA';
+ blocked = true;
+ for (let i = 0; i < 2; i += 1) {
+ document.querySelector('.refresh-btn').click();
+ await flushPromises();
+ expect(select.value).toBe('');
+ expect(select.dataset.initialValue).toBe('OLLAMA');
+ }
+ blocked = false;
+ document.querySelector('.refresh-btn').click();
+ await flushPromises();
+ expect(select.value).toBe('OLLAMA');
+});
+
+it('accepts the message-only settings response and rejects an incompatible success envelope', async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ message: 'Setting benchmark.evaluation.provider updated successfully' }) })
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ success: true }) });
+ vi.stubGlobal('fetch', fetchMock);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const save = compileSaveEvaluationSetting('csrf-test');
+ expect(await save('benchmark.evaluation.provider', 'ollama')).toBe(true);
+ expect(save.failedKeys.size).toBe(0);
+ expect(await save('benchmark.evaluation.provider', 'openai')).toBe(false);
+ expect(save.failedKeys.has('benchmark.evaluation.provider')).toBe(true);
+});
diff --git a/tests/js/pages/news-subscription-test-run-runtime.test.js b/tests/js/pages/news-subscription-test-run-runtime.test.js
index 0239bf3e6e..d066cc0579 100644
--- a/tests/js/pages/news-subscription-test-run-runtime.test.js
+++ b/tests/js/pages/news-subscription-test-run-runtime.test.js
@@ -526,3 +526,21 @@ it('releases create-and-run ownership when subscription creation fails', async (
expect(sessionStorage.getItem('activeTestRunResearchId'))
.toBe('research-after-create-retry');
});
+
+
+it.each(['handleSubscriptionSubmit', 'handleTestRun', 'handleCreateAndRun'])(
+ '%s retains the configured provider after policy clears its selection', async action => {
+ const select = document.getElementById('subscription-provider');
+ select.value = '';
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: false, status: 400, json: async () => ({ error: 'Policy refused provider' }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const runner = compileSubscriptionRunner({ ...createDependencies(), currentProvider: 'OPENAI' });
+ await runner[action]({ preventDefault() {}, stopPropagation() {} });
+ expect(fetchMock).toHaveBeenCalledOnce();
+ const body = JSON.parse(fetchMock.mock.calls[0][1].body);
+ expect(body.model_provider).toBe('OPENAI');
+ expect(body.model).toBe('gpt-4.1-mini');
+ },
+);
diff --git a/tests/security/test_settings_egress_and_secrets_fastapi.py b/tests/security/test_settings_egress_and_secrets_fastapi.py
index 02ff23a50f..9df97b543a 100644
--- a/tests/security/test_settings_egress_and_secrets_fastapi.py
+++ b/tests/security/test_settings_egress_and_secrets_fastapi.py
@@ -534,7 +534,10 @@ class TestModelDiscoveryEgressPolicy:
"value": "OLLAMA",
"label": "Ollama",
"disabled": True,
- "disabled_reason": 'Blocked by "Require Local LLM Endpoint"',
+ "disabled_reason": (
+ 'Blocked by egress scope "Private only" '
+ "(endpoint URL is not local)"
+ ),
}
]
# A denied provider is absent from the model map. The option
@@ -620,7 +623,10 @@ class TestModelDiscoveryEgressPolicy:
"value": "OLLAMA",
"label": "Ollama",
"disabled": True,
- "disabled_reason": 'Blocked by "Require Local LLM Endpoint"',
+ "disabled_reason": (
+ 'Blocked by egress scope "Private only" '
+ "(endpoint URL is not local)"
+ ),
}
]
# A denied provider is absent from the model map. The option
@@ -676,6 +682,155 @@ class TestModelDiscoveryEgressPolicy:
finally:
_reset_model_cache(username, password)
+ def test_adaptive_resolved_to_private_only_names_adaptive_not_private(
+ self, settings_user, monkeypatch
+ ):
+ """With no ``LDR_POLICY_EGRESS_SCOPE`` override and the default
+ ``adaptive`` scope resolving to PRIVATE_ONLY (a local primary search
+ engine), the disabled reason must name the "Adaptive" control the
+ user's Egress Scope select actually shows -- not "Private only",
+ a selection they never made.
+
+ Reverting the call site at ``settings.py:2091-2094`` to pass ``None``
+ instead of ``policy_snapshot`` restores the pre-fix bug and this test
+ catches it: ``_configured_egress_scope(None)`` returns ``None``
+ (the env override is also unset here), so the ``== EgressScope.
+ ADAPTIVE`` check fails and the control falls through to naming
+ "Private only" instead -- and the message loses the parenthetical
+ entirely, so the exact-string assertion below fails either way.
+ """
+ client, username, password = settings_user
+ monkeypatch.delenv("LDR_POLICY_EGRESS_SCOPE", raising=False)
+ original_search_tool = client.get("/settings/api/search.tool").json()[
+ "value"
+ ]
+ assert (
+ client.put(
+ "/settings/api/search.tool", json={"value": "paperless"}
+ ).status_code
+ == 200
+ )
+ _reset_model_cache(username, password, rows=[CACHED_LOCAL])
+ try:
+ options = [
+ {"value": "OLLAMA", "label": "Ollama"},
+ {"value": "OPENAI", "label": "OpenAI"},
+ ]
+ with (
+ patch(
+ f"{PROVIDERS}.get_discovered_provider_options",
+ return_value=options,
+ ),
+ patch(f"{PROVIDERS}.discover_providers", return_value={}),
+ ):
+ resp = client.get("/settings/api/available-models")
+
+ assert resp.status_code == 200, resp.text[:300]
+ data = resp.json()
+ blocked = [
+ option
+ for option in data["provider_options"]
+ if option["value"] == "OPENAI"
+ ]
+ assert len(blocked) == 1
+ assert blocked[0]["disabled"] is True
+ assert "Adaptive" in blocked[0]["disabled_reason"]
+ assert blocked[0]["disabled_reason"] == (
+ 'Blocked by egress scope "Adaptive" (resolved to Private '
+ "only from your primary search engine; cloud-only provider)"
+ )
+ finally:
+ _reset_model_cache(username, password)
+ client.put(
+ "/settings/api/search.tool",
+ json={"value": original_search_tool},
+ )
+
+
+ "research_url,evaluation_url,research_allowed,evaluation_allowed",
+ [
+ ("https://8.8.8.8/v1", "http://127.0.0.1:8080/v1", False, True),
+ ("http://127.0.0.1:8080/v1", "https://8.8.8.8/v1", True, False),
+ ("https://8.8.8.8/v1", "http://127.0.0.1 ", False, True),
+ ],
+)
+def test_benchmark_metadata_uses_its_endpoint_without_changing_model_cache(
+ settings_user,
+ monkeypatch,
+ research_url,
+ evaluation_url,
+ research_allowed,
+ evaluation_allowed,
+):
+ client, username, password = settings_user
+ monkeypatch.setenv("LDR_LLM_REQUIRE_LOCAL_ENDPOINT", "true")
+ monkeypatch.setenv("LDR_LLM_OPENAI_ENDPOINT_URL", research_url)
+ monkeypatch.setenv("LDR_BENCHMARK_EVALUATION_ENDPOINT_URL", evaluation_url)
+ _reset_model_cache(
+ username,
+ password,
+ rows=[
+ CACHED_LOCAL,
+ ("OPENAI_ENDPOINT", "endpoint-cached", "Endpoint cached"),
+ ],
+ )
+ list_models = MagicMock(
+ return_value=[{"value": "m1", "label": "Model One"}]
+ )
+
+ def _stub(api_key_setting, url_setting, provider_name):
+ return SimpleNamespace(
+ provider_class=SimpleNamespace(
+ api_key_setting=api_key_setting,
+ url_setting=url_setting,
+ list_models_for_api=list_models,
+ ),
+ provider_name=provider_name,
+ )
+
+ # The stub has to advertise the providers under test. The policy's
+ # user-registered-LLM exemption (``_is_user_registered_llm``) treats a
+ # name that IS in the LLM registry -- every built-in is auto-registered
+ # by the real ``discover_providers()`` -- but is NOT in the discovered
+ # map as in-process code, and allows it WITHOUT classifying its
+ # endpoint. An empty map therefore answers "allowed" for every provider
+ # and makes both directions of this parametrization vacuous.
+ discovered = {
+ "OPENAI_ENDPOINT": _stub(
+ "llm.openai_endpoint.api_key", "llm.openai_endpoint.url", "Endpoint"
+ ),
+ "OLLAMA": _stub("llm.ollama.api_key", "llm.ollama.url", "Ollama"),
+ }
+ try:
+ with (
+ patch(
+ f"{PROVIDERS}.get_discovered_provider_options",
+ return_value=[
+ {"value": "OPENAI_ENDPOINT", "label": "Endpoint"},
+ ],
+ ),
+ patch(f"{PROVIDERS}.discover_providers", return_value=discovered),
+ ):
+ response = client.get("/settings/api/available-models")
+ assert response.status_code == 200, response.text[:300]
+ data = response.json()
+ assert data["provider_options"][0]["disabled"] is not research_allowed
+ assert (
+ data["benchmark_provider_options"][0]["disabled"]
+ is not evaluation_allowed
+ )
+ assert (
+ "openai_endpoint_models" in data["providers"]
+ ) is research_allowed
+ # The seeded cache answers the request, so the benchmark metadata is
+ # built without contacting a provider or refreshing the model cache.
+ # (``discover_providers`` itself is not the guard: the policy calls
+ # it to tell a built-in from an in-process LLM.)
+ list_models.assert_not_called()
+ finally:
+ _reset_model_cache(username, password)
+
# ---------------------------------------------------------------------------
# COVERAGE AREA 2 -- secret write-back / echo redaction
diff --git a/tests/web/routers/test_provider_disabled_reason_port.py b/tests/web/routers/test_provider_disabled_reason_port.py
new file mode 100644
index 0000000000..870d9e412a
--- /dev/null
+++ b/tests/web/routers/test_provider_disabled_reason_port.py
@@ -0,0 +1,201 @@
+"""Unit tests for the reason string attached to blocked provider options.
+
+``require_local_llm`` has three possible origins and the dropdown has to name
+the right one. Naming the checkbox unconditionally (the first cut of #5662)
+sent users who had set the ``private_only`` egress scope hunting for a
+checkbox that was already unticked, and gave users under an operator env lock
+no hint that the control was not theirs to change.
+
+Port of ``tests/web/routes/test_provider_disabled_reason.py`` (#5749).
+``_provider_disabled_reason`` and its ``_model_discovery_provider_decision``
+callers were added to the deleted Flask ``web/routes/settings_routes.py``;
+this ports them onto the FastAPI ``web/routers/settings.py`` module the
+migration left them out of.
+"""
+
+from unittest.mock import patch
+
+import pytest
+
+from local_deep_research.security.egress.policy import (
+ Decision,
+ EgressContext,
+ EgressScope,
+ context_from_snapshot,
+)
+from local_deep_research.web.routers.settings import (
+ _provider_disabled_reason,
+)
+
+
+def _context(scope: EgressScope) -> EgressContext:
+ return EgressContext(
+ scope=scope,
+ primary_engine="searxng",
+ require_local_llm=True,
+ require_local_embeddings=False,
+ username="tester",
+ )
+
+
+def _snapshot(scope: EgressScope) -> dict:
+ """The snapshot the context above would have been built from."""
+ return {"policy.egress_scope": scope.value}
+
+
+def no_env_lock():
+ """Default: the setting is not locked by the server environment."""
+ with patch(
+ "local_deep_research.web.routers.settings.check_env_setting",
+ return_value=None,
+ ) as mock:
+ yield mock
+
+
+class TestProviderDisabledReason:
+ def test_names_the_checkbox_when_the_user_set_it(self, no_env_lock):
+ reason = _provider_disabled_reason(
+ Decision(False, "provider_cloud_only"),
+ _context(EgressScope.ADAPTIVE),
+ _snapshot(EgressScope.ADAPTIVE),
+ )
+
+ assert 'Blocked by "Require Local LLM Endpoint"' in reason
+ assert "egress scope" not in reason
+
+ def test_names_the_scope_when_private_only_forced_the_flag(
+ self, no_env_lock
+ ):
+ # context_from_snapshot() turns private_only into require_local_llm,
+ # so the checkbox the old message named may well be unticked.
+ reason = _provider_disabled_reason(
+ Decision(False, "provider_cloud_only"),
+ _context(EgressScope.PRIVATE_ONLY),
+ _snapshot(EgressScope.PRIVATE_ONLY),
+ )
+
+ assert 'Blocked by egress scope "Private only"' in reason
+
+ def test_says_so_when_the_server_locked_the_setting(self):
+ with patch(
+ "local_deep_research.web.routers.settings.check_env_setting",
+ return_value="true",
+ ):
+ reason = _provider_disabled_reason(
+ Decision(False, "provider_cloud_only"),
+ _context(EgressScope.PRIVATE_ONLY),
+ _snapshot(EgressScope.PRIVATE_ONLY),
+ )
+
+ # The env lock outranks the scope: no user-facing control changes it.
+ # Asserted as the whole string, because "locked by the server" alone
+ # still passes with the ``not env_locked`` guard removed -- the scope
+ # branch would win and name a control the user cannot change.
+ assert reason == (
+ 'Blocked by "Require Local LLM Endpoint" '
+ "(cloud-only provider; locked by the server)"
+ )
+ assert "egress scope" not in reason
+
+ @pytest.mark.parametrize(
+ "policy_reason,expected",
+ [
+ ("provider_cloud_only", "cloud-only provider"),
+ ("provider_url_unset", "no endpoint URL configured"),
+ ("url_malformed", "endpoint URL is malformed"),
+ ("provider_remote", "endpoint URL is not local"),
+ ],
+ )
+ def test_explains_the_cause(self, no_env_lock, policy_reason, expected):
+ reason = _provider_disabled_reason(
+ Decision(False, policy_reason),
+ _context(EgressScope.ADAPTIVE),
+ _snapshot(EgressScope.ADAPTIVE),
+ )
+
+ assert expected in reason
+
+ def test_unmapped_reason_falls_back_to_the_control_alone(self, no_env_lock):
+ # A raw policy token like "no_snapshot" means nothing to a user, and
+ # leaking one into an <option> label would be worse than saying less.
+ reason = _provider_disabled_reason(
+ Decision(False, "no_snapshot"),
+ _context(EgressScope.ADAPTIVE),
+ _snapshot(EgressScope.ADAPTIVE),
+ )
+
+ assert reason == 'Blocked by "Require Local LLM Endpoint"'
+ assert "no_snapshot" not in reason
+
+
+ "env_value",
+ [
+ # Both parsers agree these are falsy.
+ False,
+ "false",
+ "0",
+ "off",
+ # parse_boolean() (HTML-checkbox semantics) calls all of these True,
+ # but context_from_snapshot() coerces require_local_llm with the
+ # policy's own {"true","1","yes","on"} vocabulary, so the policy is
+ # NOT forcing locality and the message must not claim a server lock.
+ "enabled",
+ "T",
+ "y",
+ "disabled",
+ ],
+)
+def test_false_env_lock_does_not_hide_the_private_scope_cause(env_value):
+ """The reported lock must match the lock the policy actually enforces."""
+ with patch(
+ "local_deep_research.web.routers.settings.check_env_setting",
+ return_value=env_value,
+ ):
+ reason = _provider_disabled_reason(
+ Decision(False, "provider_cloud_only"),
+ _context(EgressScope.PRIVATE_ONLY),
+ _snapshot(EgressScope.PRIVATE_ONLY),
+ )
+ assert 'Blocked by egress scope "Private only"' in reason
+ assert "locked by the server" not in reason
+
+
+def test_names_adaptive_when_it_only_resolved_to_private_only():
+ """The resolved scope is not the control the user can see.
+
+ ``adaptive`` is the default scope, and ``context_from_snapshot`` resolves
+ it to PRIVATE_ONLY whenever the primary search engine is local. Naming
+ the resolved value sent a default-scope user hunting for a "Private only"
+ selection their Egress Scope select never showed.
+ """
+ # Flat shape: SettingsManager.get_settings_snapshot() unwraps each
+ # setting to its bare value (manager.py:1215-1219) before this function
+ # ever sees it — production never hands it the nested {"value": ...}
+ # form.
+ snapshot = {
+ "policy.egress_scope": "adaptive",
+ "search.tool": "paperless",
+ }
+ with patch(
+ "local_deep_research.settings.manager.check_env_setting",
+ return_value=None,
+ ):
+ context = context_from_snapshot(snapshot, "paperless")
+ # Production really does hand this function a resolved PRIVATE_ONLY here.
+ assert context.scope == EgressScope.PRIVATE_ONLY
+ assert context.require_local_llm is True
+
+ with patch(
+ "local_deep_research.web.routers.settings.check_env_setting",
+ return_value=None,
+ ):
+ reason = _provider_disabled_reason(
+ Decision(False, "provider_remote"), context, snapshot
+ )
+
+ assert reason == (
+ 'Blocked by egress scope "Adaptive" (resolved to Private only '
+ "from your primary search engine; endpoint URL is not local)"
+ )
diff --git a/tests/web/test_js_fetch_parity.py b/tests/web/test_js_fetch_parity.py
index 86108178fa..5d3d786df0 100644
--- a/tests/web/test_js_fetch_parity.py
+++ b/tests/web/test_js_fetch_parity.py
@@ -955,7 +955,7 @@ LIVE_CASES = (
bad={"val": 0.5},
),
LiveCase(
- js_ref="components/research.js:3008",
+ js_ref="components/research.js:3083",
method="POST",
url="/settings/api/search-favorites/toggle",
good={"engine_id": "zzz_no_such_engine"},