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: advertise all model providers, mark blocked ones disabled in the New Research dropdown (#5662)

S1b2d15df065d
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index b978d16a26..cea5cc08f8 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -1594,22 +1594,35 @@ def api_get_available_models():
policy_context, policy_snapshot = _resolve_model_discovery_policy()
- # Get all auto-discovered providers (show all so users can discover
- # and configure providers they haven't set up yet)
+ # Get all auto-discovered providers. Every provider is advertised to
+ # the UI; the egress policy marks blocked ones as disabled (with a
+ # reason) instead of removing them. Removing them silently made the
+ # "Model Provider" dropdown look short after configuring a cloud API
+ # key, leading users to assume the key wasn't picked up. The
+ # per-provider MODELS list below is still filtered so we never
+ # actually call a blocked provider.
from ...llm.providers import get_discovered_provider_options
# LlamaCppProvider is auto-discovered (provider_name="llama.cpp"), so
# it is already included here. The previous hardcoded LLAMACPP append
# produced a duplicate entry in the dropdown.
- provider_options = get_discovered_provider_options()
- if policy_context.require_local_llm:
- provider_options = [
- option
- for option in provider_options
- if _model_discovery_provider_allowed(
+ 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)
# Available models by provider
providers: dict[str, Any] = {}
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 80c6be86c8..6791d8b355 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -980,6 +980,24 @@
if (typeof applyEgressScopeToEngines === 'function') {
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.
policyScopeSaveQueue = policyScopeSaveQueue
.catch(() => undefined)
.then(() => saveSearchSetting(
@@ -995,7 +1013,16 @@
this.dataset.savedValue = selectedValue;
}
}
- ));
+ ))
+ .then(() => {
+ if (typeof invalidateCacheKey === 'function') {
+ invalidateCacheKey(CACHE_KEYS.MODELS);
+ }
+ if (typeof loadModelOptions === 'function') {
+ return loadModelOptions(false).catch(() => undefined);
+ }
+ return undefined;
+ });
});
// Apply the initial cue on page load (the data-scope attribute is
// already set server-side from settings; this just keeps the icon
@@ -1021,7 +1048,32 @@
const llmRequireLocalInput = document.getElementById('llm_require_local_endpoint');
if (llmRequireLocalInput && llmRequireLocalInput.dataset.envLocked !== "true") {
llmRequireLocalInput.addEventListener('change', function() {
- saveSearchSetting('llm.require_local_endpoint', this.checked);
+ // 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.
+ .catch(() => undefined);
});
}
const embRequireLocalInput = document.getElementById('embeddings_require_local');
@@ -1175,26 +1227,58 @@
// Clear existing options
modelProviderSelect.innerHTML = '';
- // Add options
+ // Add options. Cloud providers that the egress policy blocks are kept in
+ // the dropdown but rendered as <option disabled> with the policy
+ // reason appended to the label — so the user sees that the
+ // provider exists, that their API key was saved, and exactly why
+ // it can't be selected right now.
MODEL_PROVIDERS.forEach(provider => {
const option = document.createElement('option');
option.value = provider.value;
- option.textContent = provider.label;
+ const isDisabled = provider.disabled === true;
+ option.disabled = isDisabled;
+ let label = provider.label || provider.value;
+ if (isDisabled && provider.disabled_reason) {
+ label += ' — ' + provider.disabled_reason;
+ }
+ option.textContent = label;
modelProviderSelect.appendChild(option);
});
- // Restore previous value if it exists in new options, otherwise use initial value
- const initialProvider = modelProviderSelect.getAttribute('data-initial-value') || 'OLLAMA';
- if (currentValue && Array.from(modelProviderSelect.options).some(opt => opt.value === currentValue)) {
- modelProviderSelect.value = currentValue;
- } else {
+ // Restore previous value if it exists in new options and is not disabled,
+ // otherwise fall back to initial provider or the first enabled provider.
+ const optionsList = Array.from(modelProviderSelect.options);
+ const currentOpt = currentValue
+ ? optionsList.find(opt => opt.value === currentValue)
+ : null;
+ const initialProvider = (
+ modelProviderSelect.getAttribute('data-initial-value') || 'OLLAMA'
+ ).toUpperCase();
+ const initialOpt = optionsList.find(
+ opt => opt.value.toUpperCase() === initialProvider
+ );
+
+ if (currentOpt && !currentOpt.disabled) {
+ modelProviderSelect.value = currentOpt.value;
+ } else if (initialOpt && !initialOpt.disabled) {
SafeLogger.log('Initial provider from data attribute:', initialProvider);
- modelProviderSelect.value = initialProvider.toUpperCase();
+ 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;
+ }
}
+ const selectedProvider = modelProviderSelect.value || initialProvider;
+
// Show custom endpoint input if OpenAI endpoint is selected
if (endpointContainer) {
- const selectedProvider = modelProviderSelect.value || initialProvider.toUpperCase();
SafeLogger.log('Setting endpoint container display for provider:', selectedProvider);
endpointContainer.style.display = selectedProvider === 'OPENAI_ENDPOINT' ? 'block' : 'none';
} else {
@@ -1203,30 +1287,25 @@
// Show Anthropic endpoint input if Anthropic endpoint is selected
if (anthropicEndpointContainer) {
- const selectedProvider = modelProviderSelect.value || initialProvider.toUpperCase();
anthropicEndpointContainer.style.display = selectedProvider === 'ANTHROPIC_ENDPOINT' ? 'block' : 'none';
}
// Show Ollama URL input if Ollama is selected
if (ollamaUrlContainer) {
- const selectedProvider = modelProviderSelect.value || initialProvider.toUpperCase();
ollamaUrlContainer.style.display = selectedProvider === 'OLLAMA' ? 'block' : 'none';
}
// Show LM Studio URL input if LMSTUDIO is selected
if (lmstudioUrlContainer) {
- const selectedProvider = modelProviderSelect.value || initialProvider.toUpperCase();
lmstudioUrlContainer.style.display = selectedProvider === 'LMSTUDIO' ? 'block' : 'none';
}
// Show context window for local providers
if (contextWindowContainer) {
- const selectedProvider = modelProviderSelect.value || initialProvider.toUpperCase();
contextWindowContainer.style.display = isLocalProvider(selectedProvider) ? 'block' : 'none';
}
- // Show API key containers based on initial provider
- const selectedProvider = modelProviderSelect.value || initialProvider.toUpperCase();
+ // Show API key containers based on active/reconciled provider
if (openaiApiKeyContainer) {
openaiApiKeyContainer.style.display = selectedProvider === 'OPENAI' ? 'block' : 'none';
}
@@ -1265,8 +1344,7 @@
}
// Initial update of model options
- const providerToUpdate = modelProviderSelect.value || initialProvider.toUpperCase();
- updateModelOptionsForProvider(providerToUpdate);
+ updateModelOptionsForProvider(selectedProvider);
}
/**
@@ -1571,16 +1649,18 @@
option => option.value.toUpperCase() === providerValue
);
- if (matchingOption) {
+ if (matchingOption && !matchingOption.disabled) {
SafeLogger.log('Found matching provider option:', matchingOption.value);
modelProviderSelect.value = matchingOption.value;
// Also save to localStorage
// Provider saved to DB: matchingOption.value);
- } else {
- // If no match, try to find case-insensitive or partial match
+ } 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.value.toUpperCase().includes(providerValue) ||
- providerValue.includes(option.value.toUpperCase())
+ option => !option.disabled && (
+ option.value.toUpperCase().includes(providerValue) ||
+ providerValue.includes(option.value.toUpperCase())
+ )
);
if (caseInsensitiveMatch) {
@@ -1591,71 +1671,75 @@
} else {
SafeLogger.warn(`No matching provider option found for '${providerValue}'`);
}
+ } else {
+ SafeLogger.log('Configured provider is disabled by egress policy; keeping enabled fallback:', modelProviderSelect.value);
}
modelProviderSelect.disabled = !providerSetting.editable;
+ const activeProvider = modelProviderSelect.value || providerValue;
+
// Display endpoint container if using custom endpoint
if (endpointContainer) {
endpointContainer.style.display =
- providerValue === 'OPENAI_ENDPOINT' ? 'block' : 'none';
+ activeProvider === 'OPENAI_ENDPOINT' ? 'block' : 'none';
}
// Display Anthropic endpoint container if using Anthropic endpoint
if (anthropicEndpointContainer) {
anthropicEndpointContainer.style.display =
- providerValue === 'ANTHROPIC_ENDPOINT' ? 'block' : 'none';
+ activeProvider === 'ANTHROPIC_ENDPOINT' ? 'block' : 'none';
}
// Display Ollama URL container if using Ollama
if (ollamaUrlContainer) {
ollamaUrlContainer.style.display =
- providerValue === 'OLLAMA' ? 'block' : 'none';
+ activeProvider === 'OLLAMA' ? 'block' : 'none';
}
// Display LM Studio URL container if using LMSTUDIO
if (lmstudioUrlContainer) {
lmstudioUrlContainer.style.display =
- providerValue === 'LMSTUDIO' ? 'block' : 'none';
+ activeProvider === 'LMSTUDIO' ? 'block' : 'none';
}
// Display context window container for local providers
if (contextWindowContainer) {
- contextWindowContainer.style.display = isLocalProvider(providerValue) ? 'block' : 'none';
+ contextWindowContainer.style.display = isLocalProvider(activeProvider) ? 'block' : 'none';
}
// Display API key containers based on provider
if (openaiApiKeyContainer) {
- openaiApiKeyContainer.style.display = providerValue === 'OPENAI' ? 'block' : 'none';
+ openaiApiKeyContainer.style.display = activeProvider === 'OPENAI' ? 'block' : 'none';
}
if (anthropicApiKeyContainer) {
- anthropicApiKeyContainer.style.display = providerValue === 'ANTHROPIC' ? 'block' : 'none';
+ anthropicApiKeyContainer.style.display = activeProvider === 'ANTHROPIC' ? 'block' : 'none';
}
if (googleApiKeyContainer) {
- googleApiKeyContainer.style.display = providerValue === 'GOOGLE' ? 'block' : 'none';
+ googleApiKeyContainer.style.display = activeProvider === 'GOOGLE' ? 'block' : 'none';
}
if (openrouterApiKeyContainer) {
- openrouterApiKeyContainer.style.display = providerValue === 'OPENROUTER' ? 'block' : 'none';
+ openrouterApiKeyContainer.style.display = activeProvider === 'OPENROUTER' ? 'block' : 'none';
}
if (atlascloudApiKeyContainer) {
- atlascloudApiKeyContainer.style.display = providerValue === 'ATLASCLOUD' ? 'block' : 'none';
+ atlascloudApiKeyContainer.style.display = activeProvider === 'ATLASCLOUD' ? 'block' : 'none';
}
if (xaiApiKeyContainer) {
- xaiApiKeyContainer.style.display = providerValue === 'XAI' ? 'block' : 'none';
+ xaiApiKeyContainer.style.display = activeProvider === 'XAI' ? 'block' : 'none';
}
if (ionosApiKeyContainer) {
- ionosApiKeyContainer.style.display = providerValue === 'IONOS' ? 'block' : 'none';
+ ionosApiKeyContainer.style.display = activeProvider === 'IONOS' ? 'block' : 'none';
}
if (openaiEndpointApiKeyContainer) {
- openaiEndpointApiKeyContainer.style.display = providerValue === 'OPENAI_ENDPOINT' ? 'block' : 'none';
+ openaiEndpointApiKeyContainer.style.display = activeProvider === 'OPENAI_ENDPOINT' ? 'block' : 'none';
}
if (anthropicEndpointApiKeyContainer) {
- anthropicEndpointApiKeyContainer.style.display = providerValue === 'ANTHROPIC_ENDPOINT' ? 'block' : 'none';
+ anthropicEndpointApiKeyContainer.style.display = activeProvider === 'ANTHROPIC_ENDPOINT' ? 'block' : 'none';
}
if (ollamaApiKeyContainer) {
- ollamaApiKeyContainer.style.display = providerValue === 'OLLAMA' ? 'block' : 'none';
+ ollamaApiKeyContainer.style.display = activeProvider === 'OLLAMA' ? 'block' : 'none';
}
if (lmstudioApiKeyContainer) {
- lmstudioApiKeyContainer.style.display = providerValue === 'LMSTUDIO' ? 'block' : 'none';
+ lmstudioApiKeyContainer.style.display = activeProvider === 'LMSTUDIO' ? 'block' : 'none';
}
}
@@ -2015,16 +2099,25 @@
if (data.provider_options) {
MODEL_PROVIDERS = data.provider_options;
SafeLogger.log('Updated MODEL_PROVIDERS from API:', MODEL_PROVIDERS);
- // Re-populate the provider dropdown with new options
- populateModelProviders();
}
- // Format the data for our dropdown
+ // Format the data for our dropdown and cache BEFORE
+ // populateModelProviders() runs. populateModelProviders
+ // calls updateModelOptionsForProvider() at the end of
+ // its body, and that helper falls back to a
+ // loadModelOptions() round-trip when the cache is
+ // empty — which, on a same-page refresh after the
+ // user toggled a policy, would be the very call we
+ // just made (waste) or, worse, a fresh force-refresh
+ // for a cloud provider that just got re-enabled.
const formattedModels = formatModelsFromAPI(data);
-
- // Cache in memory (5-minute expiration to reduce database calls)
cacheData(CACHE_KEYS.MODELS, formattedModels);
+ // Re-populate the provider dropdown with new options
+ if (data.provider_options) {
+ populateModelProviders();
+ }
+
resolve(formattedModels);
} else {
throw new Error('Invalid model data format');
diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.js
index 3126f42db3..421da1a352 100644
--- a/src/local_deep_research/web/static/js/components/settings.js
+++ b/src/local_deep_research/web/static/js/components/settings.js
@@ -3466,6 +3466,13 @@
discoveredProviderOptions = data.provider_options.map(opt => ({
value: opt.value,
label: opt.label,
+ // Preserve the disabled flag + reason the route attaches
+ // when the egress policy blocks a provider — the
+ // custom-dropdown widget renders greyed entries with the
+ // reason on hover / inline so the user can see why a
+ // configured cloud provider isn't selectable right now.
+ disabled: opt.disabled === true,
+ disabled_reason: opt.disabled_reason || null,
}));
}
diff --git a/tests/js/components/research-model-provider.test.js b/tests/js/components/research-model-provider.test.js
new file mode 100644
index 0000000000..522c5b13fd
--- /dev/null
+++ b/tests/js/components/research-model-provider.test.js
@@ -0,0 +1,601 @@
+/**
+ * Tests for the Model Provider dropdown on the New Research page.
+ *
+ * This file is intentionally a separate module from research.test.js so it
+ * gets a fresh IIFE instance of research.js with an empty
+ * ``policyScopeSaveQueue``. The egress-scope denial tests in research.test.js
+ * dispatch many change events that queue saves in the IIFE-scoped queue;
+ * running alongside them would leave our tests waiting behind tens of stale
+ * queued fetches. A separate module runs them in isolation against a clean
+ * queue.
+ *
+ * The dropdown is populated from GET /settings/api/available-models where
+ * each entry carries { value, label, disabled, disabled_reason }. The
+ * change handlers for the egress-scope select and the local-only checkbox
+ * must save the new setting first and re-fetch afterwards — otherwise the
+ * backend reads the OLD policy and the dropdown stays stale. We invalidate
+ * the client-side 5-minute cache before the re-fetch so it actually
+ * round-trips the server (the server rebuilds provider_options from the
+ * current policy on every request, so the bare cached endpoint is enough
+ * — the slow force_refresh=true path is reserved for cases where the
+ * model *lists* themselves need to be re-discovered).
+ */
+
+import '@js/config/urls.js'; // window.URLS (URLS.SETTINGS_API.AVAILABLE_MODELS)
+import '@js/utils/alert-helpers.js'; // window.LdrAlertHelpers (used by showSafeAlert)
+import '@js/security/xss-protection.js';
+import '@js/utils/form-validation.js'; // FormValidator, formValidators
+import '@js/components/custom_dropdown.js';
+
+const AVAILABLE_MODELS = '/settings/api/available-models';
+
+function buildForm() {
+ 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>
+ <div class="ldr-privacy-panel" data-scope="adaptive">
+ <i id="ldr-privacy-panel-icon"></i>
+ <select id="policy_egress_scope" name="policy_egress_scope">
+ <option value="adaptive" selected>Adaptive</option>
+ <option value="public_only">Public only</option>
+ <option value="private_only">Private only</option>
+ <option value="strict">Primary only</option>
+ </select>
+ <input type="checkbox" id="llm_require_local_endpoint">
+ <input type="checkbox" id="embeddings_require_local">
+ </div>
+
+ <label class="ldr-mode-option"><input type="radio" name="research_mode" value="quick" checked></label>
+
+ <button type="button" class="ldr-advanced-options-toggle ldr-open" aria-expanded="true">
+ <i class="fas fa-chevron-up"></i><span class="sr-only"></span>
+ </button>
+ <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>
+
+ <select id="strategy"><option value="source-based" selected>source-based</option><option value="langgraph-agent">LangGraph Agent</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>
+ `;
+}
+
+let fetchMock;
+let initAvailableModelsUrl;
+
+beforeAll(async () => {
+ fetchMock = vi.fn(() =>
+ Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () =>
+ Promise.resolve({
+ status: 'ok',
+ provider_options: [],
+ providers: {},
+ engines: [],
+ }),
+ text: () => Promise.resolve(''),
+ })
+ );
+ // Use vi.spyOn instead of direct reassignment so this file doesn't
+ // clobber the fetchMock installed by research.test.js's beforeAll
+ // when both files run in the same vitest worker. (Direct
+ // ``globalThis.fetch = fetchMock`` would leave research.test.js's
+ // fetchMock empty and break its regression test.)
+ vi.spyOn(globalThis, 'fetch').mockImplementation(fetchMock);
+ window.api = { getCsrfToken: () => 'test-csrf' };
+ window.RESEARCH_STATUS = { QUEUED: 'queued', IN_PROGRESS: 'in_progress' };
+
+ buildForm();
+ await import('@js/components/research.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ // Capture the URL of the synchronous-init /available-models request
+ // so we can assert it does NOT use force_refresh=true. beforeEach calls
+ // mockClear() which would wipe this otherwise.
+ initAvailableModelsUrl =
+ fetchMock.mock.calls
+ .filter(([u]) => typeof u === 'string' && u.startsWith(AVAILABLE_MODELS))
+ .map(([u]) => u)[0] ?? null;
+ await Promise.resolve();
+ await Promise.resolve();
+});
+
+const SAMPLE_PROVIDERS = [
+ { value: 'OLLAMA', label: 'Ollama 💻 Local' },
+ { value: 'LMSTUDIO', label: 'LM Studio 💻 Local' },
+ {
+ value: 'DEEPSEEK',
+ label: 'DeepSeek ☁️ Cloud',
+ disabled: true,
+ disabled_reason: 'Blocked by "Require Local LLM Endpoint"',
+ },
+ {
+ value: 'OPENAI',
+ label: 'OpenAI ☁️ Cloud',
+ disabled: true,
+ disabled_reason: 'Blocked by "Require Local LLM Endpoint"',
+ },
+];
+
+function stubModelsResponse(providerOptions) {
+ fetchMock.mockImplementation((url) => {
+ if (typeof url !== 'string') {
+ return Promise.reject(new Error('unexpected fetch'));
+ }
+ if (url.startsWith(AVAILABLE_MODELS)) {
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () =>
+ Promise.resolve({
+ status: 'ok',
+ provider_options: providerOptions,
+ providers: {},
+ }),
+ text: () => Promise.resolve(''),
+ });
+ }
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ status: 'ok' }),
+ text: () => Promise.resolve(''),
+ });
+ });
+}
+
+function getProviderOption(value) {
+ return Array.from(
+ document.getElementById('model_provider').options
+ ).find((o) => o.value === value);
+}
+
+function flush() {
+ return new Promise((r) => setTimeout(r, 0));
+}
+
+beforeEach(() => {
+ // Reset the model_provider select so each test starts from the
+ // fixture's lone <option value="OLLAMA">.
+ const sel = document.getElementById('model_provider');
+ sel.innerHTML = '<option value="OLLAMA" selected>Ollama</option>';
+ // Reset privacy controls.
+ const policyScope = document.getElementById('policy_egress_scope');
+ policyScope.value = 'adaptive';
+ policyScope.disabled = false;
+ policyScope.dataset.savedValue = 'adaptive';
+ ['llm_require_local_endpoint', 'embeddings_require_local'].forEach((id) => {
+ const control = document.getElementById(id);
+ control.checked = false;
+ control.disabled = false;
+ control.title = '';
+ delete control.dataset.envLocked;
+ delete control.dataset.envValue;
+ delete control.dataset.envTitle;
+ delete control.dataset.userChecked;
+ delete control.dataset.userCheckedSaved;
+ });
+ // Reset fetchMock to the default (the beforeAll stub). Tests that
+ // want a specific response install their own implementation.
+ fetchMock.mockImplementation((url) => {
+ if (typeof url !== 'string') {
+ return Promise.reject(new Error('unexpected fetch'));
+ }
+ if (url.startsWith(AVAILABLE_MODELS)) {
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () =>
+ Promise.resolve({
+ status: 'ok',
+ provider_options: [],
+ providers: {},
+ }),
+ text: () => Promise.resolve(''),
+ });
+ }
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ status: 'ok' }),
+ text: () => Promise.resolve(''),
+ });
+ });
+ fetchMock.mockClear();
+});
+
+describe('research form — model provider dropdown', () => {
+ it('mounts WITHOUT force_refresh so the page load stays fast (server builds provider_options per request anyway)', () => {
+ // initAvailableModelsUrl is captured synchronously right after
+ // dispatching DOMContentLoaded (see beforeAll), before any
+ // beforeEach clears the mock — so we can assert the exact URL
+ // the mount-time loadModelOptions used. Using the cached
+ // endpoint is fine because the server rebuilds provider_options
+ // from the current policy on every request; force_refresh=true
+ // would re-discover every provider's models (~1s+ wall clock)
+ // for no benefit on mount.
+ expect(initAvailableModelsUrl).not.toBeNull();
+ expect(initAvailableModelsUrl.startsWith(AVAILABLE_MODELS)).toBe(true);
+ expect(initAvailableModelsUrl).not.toContain('force_refresh=true');
+ });
+
+ it('renders disabled <option> with the policy reason appended to the label', async () => {
+ stubModelsResponse(SAMPLE_PROVIDERS);
+
+ // Trigger a force-refresh by toggling the egress scope — the
+ // change listener saves the new value and then force-refreshes
+ // the providers list.
+ 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();
+ },
+ { timeout: 1000 }
+ );
+
+ const deepseek = getProviderOption('DEEPSEEK');
+ expect(deepseek.disabled).toBe(true);
+ expect(deepseek.textContent).toContain('DeepSeek');
+ expect(deepseek.textContent).toContain('Blocked by');
+
+ const openai = getProviderOption('OPENAI');
+ expect(openai).toBeDefined();
+ expect(openai.disabled).toBe(true);
+ expect(openai.textContent).toContain('Blocked by');
+
+ const ollama = getProviderOption('OLLAMA');
+ expect(ollama).toBeDefined();
+ expect(ollama.disabled).toBe(false);
+ expect(ollama.textContent).not.toContain('Blocked by');
+ });
+
+ it('egress-scope change saves before re-fetching so the backend sees the new policy', async () => {
+ stubModelsResponse(SAMPLE_PROVIDERS);
+ fetchMock.mockClear();
+
+ const scope = document.getElementById('policy_egress_scope');
+ scope.value = 'private_only';
+ scope.dispatchEvent(new Event('change'));
+
+ // Wait for the PUT to land.
+ await vi.waitFor(
+ () => {
+ const saves = fetchMock.mock.calls.filter(
+ ([u, init]) =>
+ u === '/settings/api/policy.egress_scope' &&
+ init?.method === 'PUT'
+ );
+ expect(saves.length).toBeGreaterThanOrEqual(1);
+ },
+ { timeout: 1000 }
+ );
+
+ // And a re-fetch of the providers list (cache miss because we
+ // invalidated after the PUT). The URL is the bare cached
+ // endpoint — the server rebuilds provider_options from the
+ // current policy every request, so force_refresh=true is
+ // unnecessary here.
+ await vi.waitFor(
+ () => {
+ const refreshes = fetchMock.mock.calls.filter(
+ ([u]) =>
+ typeof u === 'string' &&
+ u.startsWith(AVAILABLE_MODELS)
+ );
+ expect(refreshes.length).toBeGreaterThanOrEqual(1);
+ },
+ { timeout: 1000 }
+ );
+
+ // Ordering: the PUT must appear in the call log BEFORE the GET.
+ const allCalls = fetchMock.mock.calls;
+ const putIndex = allCalls.findIndex(
+ ([u, init]) =>
+ u === '/settings/api/policy.egress_scope' &&
+ init?.method === 'PUT'
+ );
+ const getIndex = allCalls.findIndex(
+ ([u]) =>
+ typeof u === 'string' && u.startsWith(AVAILABLE_MODELS)
+ );
+ expect(putIndex).toBeGreaterThanOrEqual(0);
+ expect(getIndex).toBeGreaterThanOrEqual(0);
+ expect(putIndex).toBeLessThan(getIndex);
+
+ // And specifically NOT the slow force_refresh=true path —
+ // its ~1s+ wall-clock cost is what motivated this regression.
+ const forceRefreshCalls = allCalls.filter(
+ ([u]) =>
+ typeof u === 'string' &&
+ u.startsWith(AVAILABLE_MODELS) &&
+ u.includes('force_refresh=true')
+ );
+ expect(forceRefreshCalls).toHaveLength(0);
+ });
+
+ it('local-only checkbox change saves before re-fetching', async () => {
+ stubModelsResponse(SAMPLE_PROVIDERS);
+ fetchMock.mockClear();
+
+ const cb = document.getElementById('llm_require_local_endpoint');
+ cb.checked = true;
+ cb.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).toBeGreaterThanOrEqual(1);
+ },
+ { timeout: 1000 }
+ );
+
+ await vi.waitFor(
+ () => {
+ const refreshes = fetchMock.mock.calls.filter(
+ ([u]) =>
+ typeof u === 'string' &&
+ u.startsWith(AVAILABLE_MODELS)
+ );
+ expect(refreshes.length).toBeGreaterThanOrEqual(1);
+ },
+ { timeout: 1000 }
+ );
+
+ const allCalls = fetchMock.mock.calls;
+ const putIndex = allCalls.findIndex(
+ ([u, init]) =>
+ u === '/settings/api/llm.require_local_endpoint' &&
+ init?.method === 'PUT'
+ );
+ const getIndex = allCalls.findIndex(
+ ([u]) =>
+ typeof u === 'string' && u.startsWith(AVAILABLE_MODELS)
+ );
+ expect(putIndex).toBeGreaterThanOrEqual(0);
+ expect(getIndex).toBeGreaterThanOrEqual(0);
+ expect(putIndex).toBeLessThan(getIndex);
+
+ const forceRefreshCalls = allCalls.filter(
+ ([u]) =>
+ typeof u === 'string' &&
+ u.startsWith(AVAILABLE_MODELS) &&
+ u.includes('force_refresh=true')
+ );
+ 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.
+ fetchMock.mockImplementation((url, init) => {
+ if (
+ url === '/settings/api/policy.egress_scope' &&
+ init?.method === 'PUT'
+ ) {
+ return Promise.resolve({
+ ok: false,
+ status: 500,
+ json: () =>
+ Promise.resolve({
+ status: 'error',
+ error: 'simulated save failure',
+ }),
+ text: () => Promise.resolve('simulated save failure'),
+ });
+ }
+ if (typeof url === 'string' && url.startsWith(AVAILABLE_MODELS)) {
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () =>
+ Promise.resolve({
+ status: 'ok',
+ provider_options: SAMPLE_PROVIDERS,
+ providers: {},
+ }),
+ text: () => Promise.resolve(''),
+ });
+ }
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ status: 'ok' }),
+ text: () => Promise.resolve(''),
+ });
+ });
+ fetchMock.mockClear();
+
+ // Track unhandled rejections on the global so a swallowed failure
+ // can still be observed if the chain ever lets one through.
+ const rejections = [];
+ const handler = (e) => {
+ rejections.push(e?.reason?.message || e?.reason || String(e));
+ };
+ process.on('unhandledRejection', handler);
+
+ try {
+ const scope = document.getElementById('policy_egress_scope');
+ scope.value = 'private_only';
+ scope.dispatchEvent(new Event('change'));
+
+ await vi.waitFor(
+ () => {
+ const saves = fetchMock.mock.calls.filter(
+ ([u, init]) =>
+ u === '/settings/api/policy.egress_scope' &&
+ init?.method === 'PUT'
+ );
+ expect(saves.length).toBeGreaterThanOrEqual(1);
+ },
+ { timeout: 1000 }
+ );
+
+ await flush();
+ await flush();
+
+ expect(rejections).toEqual([]);
+ } finally {
+ process.off('unhandledRejection', handler);
+ }
+ });
+
+ it('clears stale <option>s before re-rendering, so a provider that disappeared between fetches is gone', async () => {
+ let call = 0;
+ fetchMock.mockImplementation((url) => {
+ if (typeof url !== 'string') {
+ return Promise.reject(new Error('unexpected'));
+ }
+ if (url.startsWith(AVAILABLE_MODELS)) {
+ call += 1;
+ const provider_options =
+ call === 1 ? SAMPLE_PROVIDERS : [SAMPLE_PROVIDERS[0]];
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () =>
+ Promise.resolve({
+ status: 'ok',
+ provider_options,
+ providers: {},
+ }),
+ text: () => Promise.resolve(''),
+ });
+ }
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ status: 'ok' }),
+ text: () => Promise.resolve(''),
+ });
+ });
+
+ const scope = document.getElementById('policy_egress_scope');
+
+ scope.value = 'private_only';
+ scope.dispatchEvent(new Event('change'));
+ await vi.waitFor(
+ () => {
+ expect(getProviderOption('DEEPSEEK')).toBeDefined();
+ expect(getProviderOption('OPENAI')).toBeDefined();
+ },
+ { timeout: 1000 }
+ );
+
+ scope.value = 'adaptive';
+ scope.dispatchEvent(new Event('change'));
+ await vi.waitFor(
+ () => {
+ const sel = document.getElementById('model_provider');
+ const values = Array.from(sel.options).map((o) => o.value);
+ expect(values).toEqual(['OLLAMA']);
+ },
+ { timeout: 1000 }
+ );
+ });
+
+ it('resets selection to an enabled fallback when the currently selected provider becomes disabled after policy toggle', async () => {
+ // First load with DEEPSEEK enabled
+ const initialProviders = [
+ { value: 'OLLAMA', label: 'Ollama 💻 Local', disabled: false },
+ { value: 'DEEPSEEK', label: 'DeepSeek ☁️ Cloud', disabled: false },
+ { value: 'OPENAI', label: 'OpenAI ☁️ Cloud', disabled: false },
+ ];
+ stubModelsResponse(initialProviders);
+
+ const scope = document.getElementById('policy_egress_scope');
+ scope.value = 'adaptive';
+ scope.dispatchEvent(new Event('change'));
+
+ await vi.waitFor(
+ () => {
+ const deepseek = getProviderOption('DEEPSEEK');
+ expect(deepseek).toBeDefined();
+ expect(deepseek.disabled).toBe(false);
+ },
+ { timeout: 1000 }
+ );
+
+ // Select DEEPSEEK
+ const sel = document.getElementById('model_provider');
+ sel.value = 'DEEPSEEK';
+ expect(sel.value).toBe('DEEPSEEK');
+
+ // Now toggle policy to private_only where DEEPSEEK is disabled
+ stubModelsResponse(SAMPLE_PROVIDERS);
+ 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 }
+ );
+
+ // 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);
+ });
+
+ it('falls back to the first enabled provider when initialProvider is also disabled', async () => {
+ 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
+ const providers = [
+ { value: 'OPENAI', label: 'OpenAI ☁️ Cloud', disabled: true, disabled_reason: 'Blocked by policy' },
+ { value: 'LMSTUDIO', label: 'LM Studio 💻 Local', disabled: false },
+ { value: 'OLLAMA', label: 'Ollama 💻 Local', disabled: false },
+ ];
+ stubModelsResponse(providers);
+
+ const scope = document.getElementById('policy_egress_scope');
+ scope.value = 'private_only';
+ scope.dispatchEvent(new Event('change'));
+
+ await vi.waitFor(
+ () => {
+ const openai = getProviderOption('OPENAI');
+ expect(openai).toBeDefined();
+ expect(openai.disabled).toBe(true);
+ },
+ { 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);
+
+ // Clean up data-initial-value
+ sel.removeAttribute('data-initial-value');
+ });
+});
diff --git a/tests/js/components/research.test.js b/tests/js/components/research.test.js
index 59c4660867..85b3999c90 100644
--- a/tests/js/components/research.test.js
+++ b/tests/js/components/research.test.js
@@ -120,8 +120,10 @@ beforeAll(async () => {
document.dispatchEvent(new Event('DOMContentLoaded'));
// Capture the model-list request count synchronously, before any async
// reload path can add to it (see initAvailableModelsCalls above).
+ // Use startsWith (not ===) so any query parameter variant (e.g.
+ // ?force_refresh=true) is counted alongside reads against the bare URL.
initAvailableModelsCalls = fetchMock.mock.calls.filter(
- ([u]) => u === AVAILABLE_MODELS
+ ([u]) => typeof u === 'string' && u.startsWith(AVAILABLE_MODELS)
).length;
// Let the fire-and-forget model/search-engine loads settle.
await Promise.resolve();
diff --git a/tests/web/routes/test_settings_routes_gaps_coverage.py b/tests/web/routes/test_settings_routes_gaps_coverage.py
index 44cf7b1758..744d37bc26 100644
--- a/tests/web/routes/test_settings_routes_gaps_coverage.py
+++ b/tests/web/routes/test_settings_routes_gaps_coverage.py
@@ -1025,10 +1025,21 @@ class TestApiGetAvailableModelsEgressPolicy:
# When the cache is read.
response = client.get("/settings/api/available-models")
- # Then only local provider data is returned.
+ # Then only the *cached models* for the blocked cloud provider are
+ # filtered out (so we never expose a model the backend would refuse
+ # to call). The provider-options list still advertises every
+ # provider so the dropdown can show, e.g., OpenAI as disabled with
+ # the policy reason — silently dropping the entry made the dropdown
+ # look short after a user configured a cloud API key, leading them
+ # to assume the key wasn't being read.
assert response.status_code == 200
payload = response.get_json()
- assert payload["provider_options"] == [provider_options[0]]
+ assert len(payload["provider_options"]) == 2
+ assert payload["provider_options"][0]["value"] == "OLLAMA"
+ assert payload["provider_options"][0]["disabled"] is False
+ assert payload["provider_options"][1]["value"] == "OPENAI"
+ assert payload["provider_options"][1]["disabled"] is True
+ assert "Blocked" in payload["provider_options"][1]["disabled_reason"]
assert payload["providers"] == {
"ollama_models": [
{"value": "llama3", "label": "llama3", "provider": "OLLAMA"}
@@ -1081,10 +1092,18 @@ class TestApiGetAvailableModelsEgressPolicy:
"/settings/api/available-models?force_refresh=true"
)
- # Then that endpoint is never called or returned.
+ # Then the provider is never actually called and no models are
+ # returned, but the option is still surfaced in the dropdown
+ # marked as disabled with the policy reason so the user can see
+ # why their configured LM Studio URL isn't selectable.
assert response.status_code == 200
payload = response.get_json()
- assert payload["provider_options"] == []
+ assert len(payload["provider_options"]) == 2
+ assert payload["provider_options"][0]["value"] == "LMSTUDIO"
+ assert payload["provider_options"][0]["disabled"] is True
+ assert "Blocked" in payload["provider_options"][0]["disabled_reason"]
+ assert payload["provider_options"][1]["value"] == "OPENAI"
+ assert payload["provider_options"][1]["disabled"] is True
assert payload["providers"] == {}
provider_class.list_models_for_api.assert_not_called()
@@ -1199,10 +1218,19 @@ class TestApiGetAvailableModelsEgressPolicy:
# When model discovery reads the cache.
response = client.get("/settings/api/available-models")
- # Then both the provider option and its stale cached model are filtered.
+ # Then the stale cached model is filtered out so we never serve
+ # it to a UI that would have to refuse to use it. The provider
+ # option itself is still advertised (disabled, with the policy
+ # reason) so the user understands why their configured endpoint
+ # isn't selectable.
resolve.assert_called_once_with("mixed.inference.example")
assert response.status_code == 200
- assert response.get_json() == {"provider_options": [], "providers": {}}
+ payload = response.get_json()
+ assert len(payload["provider_options"]) == 1
+ assert payload["provider_options"][0]["value"] == "LMSTUDIO"
+ assert payload["provider_options"][0]["disabled"] is True
+ assert "Blocked" in payload["provider_options"][0]["disabled_reason"]
+ assert payload["providers"] == {}
def test_disabled_unprotected_scope_rejects_before_cache_return(
self, monkeypatch