~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix: separate run engine selection from LangGraph tool availability (#7876)
LearningCircuited6aaaf4a006
diff --git a/changelog.d/7873.bugfix.md b/changelog.d/7873.bugfix.mdnew file mode 100644index 0000000000..dfdcb8ec6c--- /dev/null+++ b/changelog.d/7873.bugfix.md@@ -0,0 +1 @@+Allow explicit search-engine selection for a research run even when the engine is excluded from the LangGraph agent's default tools. Show a Settings hint when a required API key is missing, and clarify the collection availability toggle.diff --git a/docs/release_notes/1.10.2.md b/docs/release_notes/1.10.2.mdindex 1cac1d6e55..907fe59f3c 100644--- a/docs/release_notes/1.10.2.md+++ b/docs/release_notes/1.10.2.md@@ -35,7 +35,7 @@migration relaxes the previous per-collection+model uniqueness accordingly.- Add Atlas Cloud as a built-in OpenAI-compatible LLM provider.- The Search Engine dropdown on the New Research form and the news-subscription form is scope-aware: under `Private only` or `Public only` Egress Scopes, engines that would be refused at submit time (`scope_mismatch_*`, `unclassified`) are rendered as disabled entries with `aria-disabled="true"` and a one-line reason label (`Blocked: not a local source under Private only`, etc.), so the user no longer has to click Start Research to discover the mismatch. Under `Adaptive`, `Strict`, and `Unprotected` modes, all primary search engines remain selectable. Switching egress scope automatically reconciles an invalid visible selection to an allowed option (`searxng` preferred / `library` fallback). Disabled entries are skipped in keyboard navigation, blocked on click, and reachable by Tab for screen readers. The dropdown serializes fetches and dropdown callbacks (`onSelect` fires before `updateHiddenField`) so engine changes carry the correct primary, and rapid changes avoid fetch races via an `AbortController` and per-call generation tokens. The backend precheck (PR #4300) and inline-error UX remain the second backstop for direct API callers and auto-expansion paths.-- The Search Engine dropdown on the New Research form now also greys out collections whose “Available to the research agent” flag is off **when the LangGraph research agent is the selected strategy** — the flag is exclusive to the LangGraph agent, so other strategies (source-based, focused-iteration, topic-organization) keep the collection selectable. The dropdown re-evaluates the disabled set on every strategy switch without a server re-fetch, and the run is refused at submit time as a second backstop for direct API callers (`reason: collection_agent_disabled`, `field: strategy`). The collection form's help text now spells out the LangGraph-only scope so the flag isn't mistaken for a privacy / egress control.+- The Search Engine dropdown on the New Research form now also greys out collections whose “Available to the research agent” flag is off **when the LangGraph research agent is the selected strategy** — the flag is exclusive to the LangGraph agent, so other strategies (source-based, focused-iteration, topic-organization) keep the collection selectable. The dropdown re-evaluates the disabled set on every strategy switch without a server re-fetch, and the run is refused at submit time as a second backstop for direct API callers (`reason: collection_agent_disabled`, `field: strategy`). The collection form's help text now spells out the LangGraph-only scope so the flag isn't mistaken for a privacy / egress control. **Superseded (see #7873):** a later change removes both mechanisms — agent-hidden collections are no longer greyed out under LangGraph and can be selected explicitly as a primary engine for an individual run, and there is no longer a submit-time `collection_agent_disabled` refusal; the collection help text now explains the distinction between automatic discovery and primary selection.### 🐛 Bug Fixesdiff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.pyindex 142268ec99..65418d929b 100644--- a/src/local_deep_research/web/routers/research.py+++ b/src/local_deep_research/web/routers/research.py@@ -49,6 +49,7 @@ from ...security import (strip_settings_snapshot,)from ...security.log_sanitizer import redact_and_bound_for_log+from ...security.secure_logging import log_exception_typefrom ...security.url_redaction import redact_url_credentialsfrom ...utilities.type_utils import overlay_runtime_settings, to_boolfrom ...utilities.url_utils import is_safe_custom_llm_endpoint@@ -109,8 +110,6 @@ from ..research_state import ()from ...constants import (DEFAULT_SEARCH_TOOL,- LANGGRAPH_STRATEGY_ALIASES,- LANGGRAPH_STRATEGY_NAME as LANGGRAPH_STRATEGY_NAME,)from ..dependencies.json_body import (is_json_request,@@ -216,15 +215,9 @@ def history_page()-# Request-body fields the start-research path uses with str methods:-# ``model_provider`` goes through ``normalize_provider`` (``.lower()``), the-# engine (``search_engine``, or its ``search_tool`` alias) through-# ``_precheck_collection_agent_enabled`` (``.startswith``), and ``strategy``-# through that precheck's ``.lower()``. JSON null and "" still count as-# unset, so the usual fallbacks apply; any other non-string is a client-# error. The async ``start_research`` wrapper rejects it before dispatch,-# and ``_extract_research_params`` rejects it again for in-process callers-# that skip the wrapper (the news run-now and overdue paths).+# These request fields name providers, engines and strategies. Null and ""+# remain unset so the saved settings apply; every other value must be a string.+# Validate before dispatch and again for in-process callers such as news runs._STRING_REQUEST_FIELDS = ("model_provider","search_engine",@@ -415,100 +408,52 @@ def _extract_research_params(data, settings_manager):}-def _precheck_collection_agent_enabled(- search_engine: str,- strategy: str,- username: str,-) -> Optional[JSONResponse]:- """Reject a run that pairs a LangGraph strategy with an agent-hidden- collection.-- Ported from the Flask ``research_routes`` (#5221). Returns a- ``JSONResponse`` when the run should be rejected, or ``None`` to- continue — the FastAPI shape, where Flask returned a- ``(jsonify, status)`` tuple.-- The per-collection ``agent_enabled`` flag is exclusive to the LangGraph- research agent: it gates which collection engines the agent offers as- specialized tools (see ``AdvancedSearchSystem`` /- ``LangGraphAgentStrategy._load_specialized_engine_tools``). Public- collections also reach the agent via their adapter, but ONLY as- specialized tools — the primary engine path is unaffected, so a- collection marked ``agent_enabled=False`` is effectively unusable for a- LangGraph run: the agent will not pick it as a tool, and the user cannot- pick anything else because the primary was the only way to surface it.-- Mirrors ``_precheck_engine_policy`` below. Fails OPEN (returns None) on- any internal error so a transient DB blip doesn't block the run — the- frontend is the primary UX guarantee and this is the second backstop.- Only fires for ``collection_<uuid>`` engines (the only engines carrying- the flag today), and only when ``strategy`` maps to the LangGraph agent;- other strategies never read the flag.+def _precheck_search_engine_api_key(settings_manager, search_engine, username):+ """Reject an explicit engine choice only when its required key is missing.++ Automatic tool-list availability does not restrict the run's primary.+ The factory still validates credentials when constructing the engine."""- if not search_engine or not search_engine.startswith("collection_"):- return None- # ``strategy`` comes straight from the JSON body, so it may be any JSON- # type. A non-string cannot name the LangGraph agent; leave it to the- # constructor guard downstream instead of crashing on ``.lower()``.- if (- not isinstance(strategy, str)- or strategy.lower() not in LANGGRAPH_STRATEGY_ALIASES- ):- return Nonetry:- from ...database.models.library import Collection-- # Imported locally rather than using the module-level binding, so a- # late patch of ``database.session_context.get_user_db_session``- # takes effect. Main's version does the same and its tests rely on- # it; binding at module import time would silently defeat them.- from ...database.session_context import (- get_user_db_session as _get_user_db_session,+ from ...web_search_engines.search_engines_config import (+ _resolve_api_key,+ search_config,)- # Engine id format: ``collection_<uuid>``. The split is safe because- # the id is constructed the same way in- # ``search_engines_config.search_config``.- collection_id = search_engine[len("collection_") :]- with _get_user_db_session(username) as db_session:- row = (- db_session.query(Collection)- .filter(Collection.id == collection_id)- .first()- )- if row is None:- # Unknown collection id — let the factory PEP produce a clearer- # error rather than masking it with a 400 here.+ snapshot = settings_manager.get_settings_snapshot()+ if not isinstance(snapshot, dict):return None- # Default-on for unrecognised / NULL values keeps the- # behaviour-preserving contract used elsewhere in the codebase.- agent_enabled = getattr(row, "agent_enabled", True) is not False- if agent_enabled:+ config = search_config(+ settings_snapshot=snapshot, username=username+ ).get(search_engine, {})+ if not config.get("requires_api_key", False) or _resolve_api_key(+ search_engine, config, snapshot+ ):return None- display_name = getattr(row, "name", None) or search_engine- logger.bind(policy_audit=True).warning(- "POST /api/start_research collection agent_enabled refused",- search_engine=search_engine,- strategy=strategy,- )+ display_name = config.get("display_name", search_engine)return JSONResponse({"status": "error","message": (- f"Collection '{display_name}' is hidden from the "- "LangGraph research agent (the 'Available to the "- "research agent' flag is off). Re-enable it on the "- "collection's page, or pick a different search "- "engine / strategy."+ f"{display_name} requires an API key. "+ "Configure it in Settings before starting research."),- "reason": "collection_agent_disabled",- "field": "strategy",+ "reason": "search_api_key_missing",+ "field": "search_engine",},status_code=400,)- except Exception: # pragma: no cover - defensive- logger.exception("collection agent_enabled pre-check skipped")- return None+ except SettingsValueError as error:+ return _settings_value_error_response(error)+ except Exception as error:+ log_exception_type("Failed to check search engine credentials", error)+ return JSONResponse(+ {+ "status": "error",+ "message": "Could not verify the search engine's API key configuration.",+ },+ status_code=500,+ )def _precheck_engine_policy(settings_manager, params, search_engine, username):@@ -1164,18 +1109,11 @@ def _start_research_sync(if policy_error is not None:return policy_error- # Per-collection ``agent_enabled`` is exclusive to the LangGraph- # research agent. When the user picks LangGraph + a collection- # hidden from the agent, the run is effectively broken (the- # agent won't pick it as a tool, and the primary was the only- # way to surface it). The frontend already disables the- # combination in the dropdown; this is the second backstop for- # direct API callers and stale-form submissions.- agent_enabled_error = _precheck_collection_agent_enabled(- search_engine, strategy, username+ credential_error = _precheck_search_engine_api_key(+ settings_manager, search_engine, username)- if agent_enabled_error is not None:- return agent_enabled_error+ if credential_error is not None:+ return credential_error# This thread-local session survives the ``with`` block. End its# read transaction before the admission gate below; otherwise thisdiff --git a/src/local_deep_research/web/routers/settings.py b/src/local_deep_research/web/routers/settings.pyindex efc7c7e959..f41aa7cc43 100644--- a/src/local_deep_research/web/routers/settings.py+++ b/src/local_deep_research/web/routers/settings.py@@ -4166,6 +4166,7 @@ def api_get_available_search_engines(# Get search engines using the same approach as search_engines_config.pyfrom ...web_search_engines.search_engines_config import (+ _resolve_api_key,search_config,)from ...web_search_engines.engine_groups import (@@ -4184,6 +4185,10 @@ def api_get_available_search_engines(if not isinstance(favorites, list):favorites = []+ # Use the same effective settings for credentials and policy. Only+ # key presence is returned; credential values stay on the server.+ policy_snapshot = settings_manager.get_settings_snapshot() or {}+# Extract search engines from configengines_dict = {}engine_options = []@@ -4227,6 +4232,12 @@ def api_get_available_search_engines("requires_api_key", False)+ has_api_key = bool(+ _resolve_api_key(+ engine_id, engine_data, policy_snapshot+ )+ )+# Build display name with icon, category, and API key statusbase_name = engine_data.get("display_name", engine_id)if requires_api_key:@@ -4254,6 +4265,7 @@ def api_get_available_search_engines("icon": icon,"category": category,"requires_api_key": requires_api_key,+ "has_api_key": has_api_key,"is_favorite": is_favorite,}@@ -4264,6 +4276,7 @@ def api_get_available_search_engines("icon": icon,"category": category,"requires_api_key": requires_api_key,+ "has_api_key": has_api_key,"is_favorite": is_favorite,"group": shown_group,"group_label": group_label(shown_group),@@ -4271,15 +4284,8 @@ def api_get_available_search_engines("base_group": base_group,"base_group_label": group_label(base_group),"base_group_order": group_order(base_group),- # Surface the per-engine ``agent_enabled`` flag so- # the frontend can disable engines the LangGraph- # research agent hides from its specialized tool- # list. Defaults to True so engines that don't- # carry the flag (only ``collection_*`` sets it- # explicitly) stay selectable — the frontend's- # LangGraph-strategy check is the only consumer- # and short-circuits for other strategies, so a- # True default is safe everywhere.+ # Describes automatic tool discovery only; an+ # explicit primary selection remains independent."agent_enabled": engine_data.get("agent_enabled", True),@@ -4312,8 +4318,6 @@ def api_get_available_search_engines(# the filter and the overlay would then deny nothing, so the# list would be served unfiltered. Let it reach the handlers# below, which return an error instead of a list.- policy_snapshot = settings_manager.get_settings_snapshot()- policy_snapshot = policy_snapshot or {}if apply_egress_filter:# Runs the guarded-URL overlay itself, after the PDP pass._classify_options_for_egress(diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.jsindex 3fc2085ac9..24fb56ca12 100644--- a/src/local_deep_research/web/static/js/components/research.js+++ b/src/local_deep_research/web/static/js/components/research.js@@ -1075,21 +1075,6 @@applyPrivacyPanelScope(policyScopeSelect.value);}- // Search-strategy change — the per-engine ``agent_enabled`` flag- // is exclusive to the LangGraph research agent, so toggling- // strategy in or out of LangGraph reshapes the dropdown's- // disabled set without any server re-fetch (the flag is- // already on every option the API returned). The drop-down- // value is persisted by settings_sync.js's own change listener;- // we only need to re-render the open/closed dropdown.- const strategySelect = document.getElementById('strategy');- if (strategySelect) {- strategySelect.addEventListener('change', function() {- if (typeof applyStrategyToEngines === 'function') {- applyStrategyToEngines();- }- });- }const llmRequireLocalInput = document.getElementById('llm_require_local_endpoint');if (llmRequireLocalInput && llmRequireLocalInput.dataset.envLocked !== "true") {llmRequireLocalInput.addEventListener('change', function() {@@ -2486,22 +2471,6 @@return null;}- // Canonical LangGraph strategy id — mirrors- // ``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.- const LANGGRAPH_STRATEGY_NAME = 'langgraph-agent';-- // Read the currently-selected strategy from the form. Returns '' when- // the select is missing (test envs) so the downstream gateway in- // ``mapEngineOption`` short-circuits and nothing is disabled.- function getCurrentStrategyForDropdown() {- const sel = document.getElementById('strategy');- if (!sel) return '';- return (sel.value || '').toLowerCase().trim();- }-// The user's currently-selected primary engine. The hidden input is the// value that form submission actually sends, so it is authoritative if a// hydration/reconciliation path ever leaves it out of sync with the@@ -2658,79 +2627,19 @@});}- // Re-render the dropdown's disabled set when the user changes the- // selected strategy. The ``agent_enabled`` filter is exclusively- // consulted by the LangGraph agent, so toggling the strategy in or- // out of LangGraph reshapes the disabled set without any server- // re-fetch — the ``agent_enabled`` field is already on each option- // (engine_options API contract) and the egress field is unaffected.- //- // Wire points:- // 1. Strategy change — called from the ``#strategy`` change- // listener (re-renders against the existing- // ``searchEngineOptions``).- // 2. Initial load — implicitly handled by ``mapEngineOption``- // when the options are first mapped in ``loadSearchEngineOptions``- // / ``applyEgressScopeToEngines`` (the strategy is already- // selected server-side, so the first paint is correct).- function applyStrategyToEngines() {- if (- !searchEngineOptions ||- !Array.isArray(searchEngineOptions) ||- searchEngineOptions.length === 0- ) {- // No options yet — the initial load will map them with- // the correct strategy context. Nothing to re-render.- return;- }- // Re-map every cached entry through ``mapEngineOption`` so the- // agent_enabled classification picks up the now-current- // strategy. The egress field is unchanged across a strategy- // switch, so the only thing that needs to recompute is the- // agent_enabled branch. The in-memory array is replaced so the- // ``getOptions()`` closure (re-read on each dropdown open) and- // the ``updateDropdownOptions`` re-render path (open dropdown)- // both see the same shape.- searchEngineOptions = searchEngineOptions.map(mapEngineOption);- if (searchEngineInput && window.updateDropdownOptions) {- try {- window.updateDropdownOptions(- searchEngineInput,- searchEngineOptions- );- } catch (_e) {- // Defensive: never let the strategy reapplier break- // the dropdown. The next open will pick up the- // updated options either way.- }- }-- // Strategy change can re-disable the current selection (a- // ``collection_*`` engine with agent_enabled=false under- // LangGraph, for example). Reconcile so the visible selection- // doesn't carry over a hidden value.- reconcileSearchEngineSelection(searchEngineOptions);- }-// Map a single engine option object from backend format to dropdown formatfunction mapEngineOption(engine) {const egress = engine.egress;const isEgressDenied = !!egress && egress.allowed === false;- // Per-engine ``agent_enabled`` flag — exclusive to the LangGraph- // research agent. Default-on for backward compatibility (only- // ``collection_*`` engines currently set it explicitly), so any- // engine without the field is treated as available. The check is- // gated on the selected strategy because every other strategy- // ignores the flag entirely.- const isLangGraph =- getCurrentStrategyForDropdown() === LANGGRAPH_STRATEGY_NAME;- const agentEnabled = engine.agent_enabled !== false;- const isAgentDisabled = isLangGraph && !agentEnabled;- const disabled = isEgressDenied || isAgentDisabled;+ // Tool-list availability controls automatic discovery, not an explicit+ // primary-engine choice. Only policy and required credentials block it.+ const isApiKeyMissing = engine.requires_api_key === true &&+ engine.has_api_key === false;+ const disabled = isEgressDenied || isApiKeyMissing;const disabledReason = isEgressDenied? egressToDisabledReason(egress.reason, engine)- : isAgentDisabled- ? agentEnabledToDisabledReason(engine)+ : isApiKeyMissing+ ? 'API key required — configure it in Settings.': null;return {value: engine.value || engine.id || '',@@ -2741,9 +2650,9 @@group_order: engine.group_order,base_group_label: engine.base_group_label,base_group_order: engine.base_group_order,- // Preserve raw fields so strategy/scope reappliers can re-classify- // against the same fields on subsequent passes without losing state.- agent_enabled: agentEnabled,+ // Preserve credential and policy decisions across scope refreshes.+ requires_api_key: engine.requires_api_key,+ has_api_key: engine.has_api_key,egress,disabled,disabled_reason: disabledReason,@@ -2783,29 +2692,6 @@}}- // Map a per-engine ``agent_enabled === false`` (LangGraph-only) flag- // onto the same ``disabled`` / ``disabled_reason`` contract the- // dropdown renders. Plain English is fine here: the flag has a- // single consumer (the LangGraph agent) and a single upstream- // surface (the collection details page), so the message can name- // it directly without ambiguity.- function agentEnabledToDisabledReason(_engine) {- // Issue #7359: the previous copy ("Hidden from the LangGraph- // research agent's tool list (check ... on the collection page- // to re-enable).") was ~127 chars and was rendered as a- // second flex item in the same row as the label, which- // squeezed the label to 0 width on the New Research page's- // Search Engine dropdown. The fix is to let the reason wrap- // onto its own line (custom_dropdown.css, with a 1 px label- // floor so the row wraps even without a favorite star) and- // shorten the copy so the second line stays bounded in the- // most common case. The "re-enable on the collection page"- // wording is the user-collection path; built-in engines live- // in settings and are re-enabled there, which the next PR- // will surface as a separate string.- return `Hidden from the LangGraph research agent — re-enable on the collection page.`;- }-// Pre-configured favorites used as the dropdown's default selection// whenever the current selection becomes invalid (e.g. a public// engine under a scope that excludes it). SearXNG is the preferreddiff --git a/src/local_deep_research/web/templates/pages/collection_create.html b/src/local_deep_research/web/templates/pages/collection_create.htmlindex cd812d52d8..52f4f2a400 100644--- a/src/local_deep_research/web/templates/pages/collection_create.html+++ b/src/local_deep_research/web/templates/pages/collection_create.html@@ -67,14 +67,10 @@Checked (default): the LangGraph research agent can search thiscollection as one of its tools. Uncheck to keep the collection outof the agent's tool list when you don't need it for agentic research.- <strong>Exclusive to the LangGraph research agent</strong> — other- strategies (source-based, focused-iteration, topic-organization) ignore- this flag, so leaving it unchecked only hides the collection from the- agent's specialised tool list. The match-in dropdown on the New- Research form greys the collection out when LangGraph is the selected- strategy, and the run is refused at submit time if you try to use it- anyway. This is a usability switch only — it does not change privacy- or egress.+ You can still select this collection as the primary search engine+ for an individual run, including a LangGraph run, when unchecked.+ Other research strategies ignore this setting. It does not change+ privacy or egress.</div></div>diff --git a/src/local_deep_research/web/templates/pages/collection_details.html b/src/local_deep_research/web/templates/pages/collection_details.htmlindex 3b7af183fd..0e96353c84 100644--- a/src/local_deep_research/web/templates/pages/collection_details.html+++ b/src/local_deep_research/web/templates/pages/collection_details.html@@ -75,14 +75,10 @@<div class="ldr-form-help" id="collection-agent-enabled-help">Checked (default): the LangGraph research agent can search this collectionas one of its tools. Uncheck to keep it out of the agent's tool list when- it isn't needed for agentic research. <strong>Exclusive to the LangGraph- research agent</strong> — other strategies (source-based, focused-iteration,- topic-organization) ignore this flag, so leaving it unchecked only hides- the collection from the agent's specialised tool list. The match-in- dropdown on the New Research form greys the collection out when LangGraph- is the selected strategy, and the run is refused at submit time if you- try to use it anyway. Usability switch only — it does not change privacy- or egress.+ it isn't needed for automatic discovery. You can still select this+ collection as the primary search engine for an individual run,+ including a LangGraph run, when unchecked. Other research strategies+ ignore this setting. It does not change privacy or egress.</div></div></div>diff --git a/tests/js/components/research.test.js b/tests/js/components/research.test.jsindex 3646c08d54..bbadac411d 100644--- a/tests/js/components/research.test.js+++ b/tests/js/components/research.test.js@@ -2160,210 +2160,134 @@ describe('research form — scope-aware search engine dropdown (issue #5204)', (});});-describe('research form — LangGraph agent_enabled dropdown filter', () => {- // The per-engine ``agent_enabled`` flag is exclusive to the LangGraph- // research agent — every other strategy ignores it. The dropdown must- // grey out engines that carry ``agent_enabled=false`` when the user- // picks the LangGraph strategy, and re-enable them when they switch- // to a different strategy. The backend's ``_precheck_collection_agent_enabled``- // is the second backstop for direct API callers; this is the UX layer.-+describe('research form — explicit search-engine selection', () => {const FULL_OPTIONS = [{ value: 'collection_disabled', label: 'Indian History (Collection)',- category: 'Local RAG', requires_api_key: false, is_favorite: false,- group: 'local', group_label: 'Local RAG', group_order: 1,- base_group: 'local', base_group_label: 'Local RAG', base_group_order: 1,- agent_enabled: false },- { value: 'collection_enabled', label: 'Sci Papers (Collection)',- category: 'Local RAG', requires_api_key: false, is_favorite: false,- group: 'local', group_label: 'Local RAG', group_order: 1,- base_group: 'local', base_group_label: 'Local RAG', base_group_order: 1,- agent_enabled: true },- { value: 'arxiv', label: 'ArXiv', category: 'Scientific', requires_api_key: false, is_favorite: false,- group: 'scientific', group_label: 'Scientific', group_order: 3,- base_group: 'scientific', base_group_label: 'Scientific', base_group_order: 3 },- { value: 'egress_denied', label: 'Egress Denied Engine', category: 'Scientific', requires_api_key: false, is_favorite: false,- group: 'scientific', group_label: 'Scientific', group_order: 3,- base_group: 'scientific', base_group_label: 'Scientific', base_group_order: 3,- agent_enabled: true, egress: { allowed: false, reason: 'strict_not_primary' } },+ agent_enabled: false, requires_api_key: false, has_api_key: false },+ { value: 'openlibrary', label: 'Open Library',+ agent_enabled: false, requires_api_key: false, has_api_key: false },+ { value: 'gutenberg', label: 'Project Gutenberg',+ agent_enabled: false, requires_api_key: false, has_api_key: false },+ { value: 'github', label: 'GitHub',+ agent_enabled: false, requires_api_key: true, has_api_key: true },+ { value: 'brave', label: 'Brave',+ agent_enabled: false, requires_api_key: true, has_api_key: false },+ { value: 'arxiv', label: 'ArXiv', requires_api_key: false },+ { value: 'egress_denied', label: 'Egress Denied Engine',+ agent_enabled: false, requires_api_key: false,+ egress: { allowed: false, reason: 'scope_mismatch_private_only' } },];- function stubEngines() {- return Promise.resolve({- ok: true,- status: 200,- json: () => Promise.resolve({ engine_options: FULL_OPTIONS, engines: {}, favorites: [] }),- text: () => Promise.resolve(''),- });- }-- function flush() {- return new Promise((r) => setTimeout(r, 0));- }-- function getOption(data_value) {- const input = document.getElementById('search_engine');- input.dispatchEvent(new Event('focus'));- const list = document.getElementById('search-engine-dropdown-list');- return Array.from(list.querySelectorAll('.ldr-custom-dropdown-item'))- .find((el) => el.getAttribute('data-value') === data_value);+ function getOption(value) {+ document.getElementById('search_engine').dispatchEvent(new Event('focus'));+ return Array.from(document.querySelectorAll('#search-engine-dropdown-list .ldr-custom-dropdown-item'))+ .find(el => el.getAttribute('data-value') === value);}function setStrategy(value) {- const sel = document.getElementById('strategy');- sel.value = value;- sel.dispatchEvent(new Event('change'));+ const select = document.getElementById('strategy');+ select.value = value;+ select.dispatchEvent(new Event('change'));}- async function waitForOptionState(value, disabled) {+ async function loadOptions() {+ const wrapper = document.getElementById('search_engine').parentNode;+ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));+ // The preceding test may already have rendered these options with+ // different credential state. Wait for this refresh to finish.await vi.waitFor(() => {- const option = getOption(value);- expect(option).toBeDefined();- expect(- option.classList.contains('ldr-custom-dropdown-item--disabled')- ).toBe(disabled);+ expect(wrapper.classList.contains('ldr-loading')).toBe(false);+ expect(getOption('openlibrary')).toBeDefined();});- return getOption(value);}beforeEach(() => {- // Reset to source-based so each test starts from a known strategy.- const strategy = document.getElementById('strategy');- strategy.value = 'source-based';- const hidden = document.getElementById('search_engine_hidden');- hidden.value = 'arxiv';- const scope = document.getElementById('policy_egress_scope');- scope.value = 'adaptive';- fetchMock.mockClear();- fetchMock.mockImplementation(() => stubEngines());- });-- it('initial load with LangGraph hides the agent_enabled=false collection', async () => {- // Set the strategy to LangGraph BEFORE re-firing the egress- // scope reapplier so the new options get mapped with the right- // strategy context. The reapplier's call to mapEngineOption- // reads #strategy at call time.setStrategy('langgraph-agent');- document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));- const disabled = await waitForOptionState('collection_disabled', true);- const enabled = getOption('collection_enabled');- const arxiv = getOption('arxiv');-- expect(disabled).toBeDefined();- expect(disabled.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);- expect(disabled.getAttribute('aria-disabled')).toBe('true');- const reason = disabled.querySelector('.ldr-dropdown-item-disabled-reason');- expect(reason).not.toBeNull();- expect(reason.textContent).toMatch(/langgraph research agent/i);-- // The other collection (agent_enabled=true) stays enabled.- expect(enabled.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);- // A non-collection engine (no agent_enabled flag) is unaffected.- expect(arxiv.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);- });-- it('initial load with source-based keeps the agent_enabled=false collection enabled', async () => {- // source-based never consults the agent_enabled flag, so the- // collection is selectable regardless of the flag value.- document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));- const disabled = await waitForOptionState('collection_disabled', false);- expect(disabled.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);- expect(disabled.getAttribute('aria-disabled')).toBeNull();+ document.getElementById('search_engine_hidden').value = 'arxiv';+ fetchMock.mockImplementation(() => Promise.resolve({+ ok: true,+ status: 200,+ json: () => Promise.resolve({ engine_options: FULL_OPTIONS, engines: {}, favorites: [] }),+ text: () => Promise.resolve(''),+ }));});- it('switching from source-based to LangGraph disables the collection', async () => {- // 1. Start with source-based: the collection is enabled.- document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));- let coll = await waitForOptionState('collection_disabled', false);- expect(coll.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);+ it.each(['collection_disabled', 'openlibrary', 'gutenberg', 'github'])(+ 'selects and submits %s even when excluded from the default agent tools', async value => {+ await loadOptions();+ const item = getOption(value);+ expect(item.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);+ expect(item.getAttribute('aria-disabled')).toBeNull();+ expect(item.querySelector('.ldr-dropdown-item-disabled-reason')).toBeNull();- // 2. Switch to LangGraph. No server re-fetch needed — the- // strategy reapplier re-maps the existing options in memory.- setStrategy('langgraph-agent');- coll = await waitForOptionState('collection_disabled', true);- expect(coll.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);- expect(coll.getAttribute('aria-disabled')).toBe('true');- });-- it('switching from LangGraph back to source-based re-enables the collection', async () => {- // 1. Start with LangGraph: the collection is disabled.- setStrategy('langgraph-agent');- document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));- let coll = await waitForOptionState('collection_disabled', true);- expect(coll.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);+ item.click();+ expect(document.getElementById('search_engine_hidden').value).toBe(value);+ document.getElementById('model_hidden').value = 'test-model';+ submitForm();+ await vi.waitFor(() => expect(callsTo(START_RESEARCH)).toHaveLength(1));+ const payload = JSON.parse(callsTo(START_RESEARCH)[0][1].body);+ expect(payload.search_engine).toBe(value);+ expect(payload.strategy).toBe('langgraph-agent');+ // Let the submit's error response release submission ownership.+ await new Promise(resolve => setTimeout(resolve, 0));+ }+ );- // 2. Switch back to source-based.+ it('preserves an explicitly chosen engine across strategy changes', async () => {setStrategy('source-based');- coll = await waitForOptionState('collection_disabled', false);- expect(coll.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);- });-- it('option with no agent_enabled field stays enabled under LangGraph', async () => {- // The flag is currently only set on collection_* engines.- // Built-in engines without the field default to enabled so the- // dropdown doesn't accidentally start disabling unrelated- // engines when the backend hasn't been updated.- setStrategy('langgraph-agent');- document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));- await waitForOptionState('collection_disabled', true);+ await loadOptions();+ getOption('openlibrary').click();- const arxiv = getOption('arxiv');- expect(arxiv.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);+ for (const strategy of ['langgraph-agent', 'source-based']) {+ setStrategy(strategy);+ expect(getOption('openlibrary').classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);+ expect(document.getElementById('search_engine_hidden').value).toBe('openlibrary');+ }});- it('engine_options without agent_enabled field default to enabled', async () => {- // The re-mapping path reads ``engine.agent_enabled !== false``,- // so a missing field defaults to enabled. This guards the- // server-side contract: an unfiltered response (no- // ?egress_scope=) MUST still render every option as enabled- // when the strategy isn't LangGraph.- setStrategy('source-based');- document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));- await waitForOptionState('collection_disabled', false);- for (const opt of FULL_OPTIONS.filter(o => !o.egress || o.egress.allowed !== false)) {- const el = getOption(opt.value);- expect(el.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);+ it('blocks a missing required API key with the correct explanation for every strategy', async () => {+ await loadOptions();+ for (const strategy of ['langgraph-agent', 'source-based']) {+ setStrategy(strategy);+ const item = getOption('brave');+ expect(item.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);+ expect(item.getAttribute('aria-disabled')).toBe('true');+ const reason = item.querySelector('.ldr-dropdown-item-disabled-reason').textContent;+ expect(reason).toMatch(/api key.*settings/i);+ expect(reason).not.toMatch(/collection|langgraph/i);+ const previousSelection = document.getElementById('search_engine_hidden').value;+ item.click();+ expect(document.getElementById('search_engine_hidden').value).toBe(previousSelection);}});- it('switching strategy from LangGraph to focused-iteration under Adaptive scope keeps all engines enabled', async () => {- document.getElementById('policy_egress_scope').value = 'adaptive';- setStrategy('langgraph-agent');- document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));- await flush();- await flush();-- // Switch to focused-iteration- setStrategy('focused-iteration');- await flush();-- // Under adaptive scope and focused-iteration, public engines like arxiv and searxng are enabled- const arxiv = getOption('arxiv');- expect(arxiv.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);+ it('keeps policy-denied engines blocked across strategy changes', async () => {+ await loadOptions();+ for (const strategy of ['langgraph-agent', 'source-based']) {+ setStrategy(strategy);+ const item = getOption('egress_denied');+ expect(item.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);+ expect(item.querySelector('.ldr-dropdown-item-disabled-reason').textContent).toMatch(/Private only/);+ const previousSelection = document.getElementById('search_engine_hidden').value;+ item.click();+ expect(document.getElementById('search_engine_hidden').value).toBe(previousSelection);+ }});- it('egress-disabled engine remains disabled across strategy switches', async () => {+ it('refreshes credential availability after a required key is configured', async () => {+ await loadOptions();+ expect(getOption('brave').getAttribute('aria-disabled')).toBe('true');+ fetchMock.mockImplementation(() => Promise.resolve({+ ok: true,+ json: () => Promise.resolve({+ engine_options: FULL_OPTIONS.map(option => (option.value === 'brave'+ ? { ...option, has_api_key: true } : option)),+ }),+ }));document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));- await flush();- await flush();-- let item = getOption('egress_denied');- expect(item).toBeDefined();- expect(item.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);-- // Switch strategy to LangGraph- setStrategy('langgraph-agent');- await flush();-- item = getOption('egress_denied');- expect(item.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);-- // Switch strategy back to source-based- setStrategy('source-based');- await flush();-- item = getOption('egress_denied');- expect(item.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);+ await vi.waitFor(() => expect(getOption('brave').getAttribute('aria-disabled')).toBeNull());+ getOption('brave').click();+ expect(document.getElementById('search_engine_hidden').value).toBe('brave');});});diff --git a/tests/js/search-engine-scope-cleanup.test.js b/tests/js/search-engine-scope-cleanup.test.jsnew file mode 100644index 0000000000..957ab6aac1--- /dev/null+++ b/tests/js/search-engine-scope-cleanup.test.js@@ -0,0 +1,162 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { runInNewContext } from 'node:vm';+import { describe, expect, it, vi } from 'vitest';++const source = readFileSync(resolve(+ __dirname, '../ui_tests/test_search_engine_dropdown_scope_ci.js',+), 'utf8');+const settingPath = '/settings/api/search.tool';+const fixture = { id: 'fixture' };++function deferred() {+ let resolvePromise;+ const promise = new Promise(finish => { resolvePromise = finish; });+ return { promise, resolve: resolvePromise };+}++function setup({ initial = 'collection_fixture', writeGate, writeFails = false, persist = true } = {}) {+ let savedPrimary = initial;+ const events = [];+ const fetch = vi.fn(async (path, options) => {+ expect(path).toBe(settingPath);+ expect(options.credentials).toBe('same-origin');+ const method = options.method || 'GET';+ events.push(method);+ if (method === 'PUT') {+ expect(options.headers['X-CSRFToken']).toBe('test-csrf');+ if (writeGate) await writeGate.promise;+ if (writeFails) return { ok: false, status: 503 };+ if (persist) savedPrimary = JSON.parse(options.body).value;+ }+ return { ok: true, status: 200, json: async () => ({ value: savedPrimary }) };+ });+ const deleteCollection = vi.fn(async () => { events.push('DELETE'); });+ const require = id => {+ if (id === './test_lib') return {};+ if (id === './test_lib/fixtures') return { deleteCollection };+ throw new Error(`Unexpected module: ${id}`);+ };+ require.main = {};+ const module = { exports: {} };+ runInNewContext(source, {+ module,+ require,+ fetch,+ URL,+ document: { querySelector: () => ({ content: 'test-csrf' }) },+ });+ const page = { evaluate: vi.fn((callback, ...args) => callback(...args)) };+ return {+ ...module.exports, page, fetch, deleteCollection, events,+ savedPrimary: () => savedPrimary,+ };+}++describe('search-engine scope suite cleanup', () => {+ it('captures the persisted primary instead of a reconciled form value', async () => {+ const state = setup({ initial: 'collection_original' });+ expect(await state.readSavedPrimaryEngine(state.page)).toBe('collection_original');+ expect(state.fetch).toHaveBeenCalledWith(settingPath, { credentials: 'same-origin' });+ });++ it.each(['searxng', 'collection_original', ''])(+ 'restores the original primary %j before deleting the fixture', async original => {+ const state = setup();+ await state.restorePrimaryAndDeleteCollection(state.page, original, fixture);+ expect(state.savedPrimary()).toBe(original);+ expect(state.events).toEqual(['GET', 'PUT', 'GET', 'DELETE']);+ expect(state.deleteCollection).toHaveBeenCalledWith(state.page, fixture.id);+ },+ );++ it('waits for restoration to finish before deleting the collection', async () => {+ const writeGate = deferred();+ const state = setup({ writeGate });+ const cleanup = state.restorePrimaryAndDeleteCollection(state.page, 'searxng', fixture);+ await vi.waitFor(() => expect(state.events).toContain('PUT'));+ expect(state.deleteCollection).not.toHaveBeenCalled();+ expect(state.savedPrimary()).toBe('collection_fixture');++ writeGate.resolve();+ await cleanup;+ expect(state.savedPrimary()).toBe('searxng');+ expect(state.events.at(-1)).toBe('DELETE');+ });++ it('keeps the collection if restoring the setting fails', async () => {+ const state = setup({ writeFails: true });+ await expect(state.restorePrimaryAndDeleteCollection(state.page, 'searxng', fixture))+ .rejects.toThrow('Could not restore primary engine (HTTP 503)');+ expect(state.deleteCollection).not.toHaveBeenCalled();+ expect(state.savedPrimary()).toBe('collection_fixture');+ });++ it('verifies persistence before deleting the collection', async () => {+ const state = setup({ persist: false });+ await expect(state.restorePrimaryAndDeleteCollection(state.page, 'searxng', fixture))+ .rejects.toThrow('Original primary engine was not restored');+ expect(state.deleteCollection).not.toHaveBeenCalled();+ });++ it('does not rewrite an unchanged primary', async () => {+ const state = setup({ initial: 'searxng' });+ await state.restorePrimaryAndDeleteCollection(state.page, 'searxng', fixture);+ expect(state.events).toEqual(['GET', 'DELETE']);+ });++ it('leaves the fixture intact if the original primary was not captured', async () => {+ const state = setup();+ await expect(state.restorePrimaryAndDeleteCollection(state.page, undefined, fixture))+ .rejects.toThrow('Original primary engine was not captured');+ expect(state.fetch).not.toHaveBeenCalled();+ expect(state.deleteCollection).not.toHaveBeenCalled();+ });++ it('does not change settings after setup fails before a fixture exists', async () => {+ const state = setup();+ await state.restorePrimaryAndDeleteCollection(state.page, undefined, null);+ expect(state.fetch).not.toHaveBeenCalled();+ expect(state.deleteCollection).not.toHaveBeenCalled();+ });++ it('waits for the selected fixture save before allowing restoration', async () => {+ const state = setup();+ const saved = deferred();+ const events = [];+ let matches;+ const page = {+ $: vi.fn(async () => ({ click: async () => { events.push('click'); } })),+ waitForResponse: vi.fn(predicate => {+ matches = predicate;+ events.push('watch');+ return saved.promise;+ }),+ };+ const selection = state.selectPrimaryEngineAndWaitForSave(page, 'collection_fixture')+ .then(() => { events.push('done'); });+ await vi.waitFor(() => expect(events).toEqual(['watch', 'click']));+ const response = (method, path, body) => ({+ url: () => `http://localhost${path}`,+ request: () => ({ method: () => method, postData: () => body }),+ });+ expect(matches(response('PUT', settingPath, '{"value":"collection_fixture"}'))).toBe(true);+ expect(matches(response('GET', settingPath, '{"value":"collection_fixture"}'))).toBe(false);+ expect(matches(response('PUT', settingPath, '{"value":"another_engine"}'))).toBe(false);+ expect(matches(response('PUT', '/settings/api/search.search_strategy', '{"value":"collection_fixture"}'))).toBe(false);+ expect(matches(response('PUT', settingPath, 'invalid-json'))).toBe(false);+ saved.resolve({ ok: () => true });+ await selection;+ expect(events).toEqual(['watch', 'click', 'done']);+ });++ it('reports a rejected selection save', async () => {+ const state = setup();+ const page = {+ $: vi.fn(async () => ({ click: async () => {} })),+ waitForResponse: vi.fn(async () => ({ ok: () => false })),+ };+ await expect(state.selectPrimaryEngineAndWaitForSave(page, 'collection_fixture'))+ .rejects.toThrow('Primary-engine selection was not saved');+ });+});diff --git a/tests/security/test_noncollection_agent_enabled.py b/tests/security/test_noncollection_agent_enabled.pyindex 68fd25a83d..e860f30c5f 100644--- a/tests/security/test_noncollection_agent_enabled.py+++ b/tests/security/test_noncollection_agent_enabled.py@@ -206,7 +206,11 @@ def test_setting_independent_of_egress_scope():# -- search.tool primary-engine carve-out ------------------------------------def test_primary_engine_stays_reachable_via_web_search_when_disabled():+ "primary",+ ["arxiv", "openlibrary", "gutenberg", "github", "collection_hidden"],+)+def test_primary_engine_stays_reachable_via_web_search_when_disabled(primary):"""The engine selected as ``search.tool`` always wins: even with``agent_enabled=False`` it must remain reachable via the agent's generic``web_search`` tool (the one specialised tool the agent always gets for@@ -226,7 +230,7 @@ def test_primary_engine_stays_reachable_via_web_search_when_disabled():"local_deep_research.web_search_engines.search_engines_config"".list_eligible_engine_configs",return_value={- "arxiv": _engine("arxiv", agent_enabled=False),+ primary: _engine(primary, agent_enabled=False),},),patch(@@ -243,21 +247,21 @@ def test_primary_engine_stays_reachable_via_web_search_when_disabled():settings_snapshot={"policy.egress_scope": "both","search.fetch.mode": "disabled",- "search.tool": "arxiv",+ "search.tool": primary,},)- assert strategy._search_engine_name == "arxiv"+ assert strategy._search_engine_name == primarytools = strategy._build_tools("overall query")names = {t.name for t in tools}assert "web_search" in names, ("Primary engine must remain reachable via web_search even when its ""agent_enabled is False — see PR #5087")- assert "arxiv" not in names, (+ assert primary not in names, ("Primary engine is never added as a specialized tool — that path ""is reserved for ADDITIONAL engines")- assert "arxiv" not in {c.args[0] for c in spec.call_args_list}+ assert primary not in {c.args[0] for c in spec.call_args_list}# -- Collection path still wins (#4453 regression guard) --------------------diff --git a/tests/strategies/test_langgraph_primary_run_selection.py b/tests/strategies/test_langgraph_primary_run_selection.pynew file mode 100644index 0000000000..5df4c4f10c--- /dev/null+++ b/tests/strategies/test_langgraph_primary_run_selection.py@@ -0,0 +1,163 @@+"""An explicit primary remains usable without enabling automatic discovery."""++from copy import deepcopy+from unittest.mock import MagicMock++import pytest++from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (+ LangGraphAgentStrategy,+)+from local_deep_research.security import clear_active_context+from local_deep_research.security import module_whitelist+from local_deep_research.web_search_engines import (+ search_engine_factory,+ search_engines_config,+)+from local_deep_research.web_search_engines.search_engine_base import (+ BaseSearchEngine,+ Exposure,+ Sensitivity,+)+++ "primary", ["openlibrary", "gutenberg", "github", "collection_hidden"]+)+def test_hidden_primary_executes_without_enabling_other_hidden_engines(+ monkeypatch, primary+):+ clear_active_context()+ snapshot = {+ "search.tool": primary,+ "policy.egress_scope": "public_only",+ "search.fetch.mode": "disabled",+ "search.engine.web.wayback.agent_enabled": False,+ f"search.engine.web.{primary}.agent_enabled": False,+ f"search.engine.web.{primary}.use_in_auto_search": False,+ "search.engine.web.github.api_key": "configured-test-credential",+ }+ configs = {}+ for name, enabled in ((primary, False), ("pubmed", False), ("arxiv", True)):+ configs[name] = {+ "module_path": ".engines.search_engine_openlibrary",+ "class_name": "OpenLibrarySearchEngine",+ "is_public": True,+ "is_local": False,+ "is_retriever": False,+ "agent_enabled": enabled,+ "use_in_auto_search": False,+ "requires_api_key": name == "github",+ "description": f"{name} source",+ "strengths": [],+ }+ original_snapshot, original_configs = deepcopy(snapshot), deepcopy(configs)+ queries = []++ class RecordingEngine(BaseSearchEngine):+ """Replace only the external engine; retain the real factory and tools."""++ is_public = True+ egress_sensitivity = Sensitivity.NON_SENSITIVE+ egress_exposure = Exposure.EXPOSING++ def __init__(+ self,+ settings_snapshot=None,+ api_key=None,+ programmatic_mode=False,+ **kwargs,+ ):+ super().__init__(+ settings_snapshot=settings_snapshot,+ programmatic_mode=programmatic_mode,+ **kwargs,+ )+ self.api_key = api_key++ def run(self, query):+ queries.append((self._engine_name, query))+ return [+ {+ "title": "Primary result",+ "link": "https://example.org/primary-result",+ "snippet": "Evidence from the explicitly selected source.",+ }+ ]++ def close(self):+ pass++ def _get_previews(self, query):+ raise AssertionError("The recording engine handles run directly")++ monkeypatch.setattr(+ search_engines_config, "search_config", lambda **kwargs: configs+ )+ monkeypatch.setattr(+ search_engine_factory, "search_config", lambda **kwargs: configs+ )+ monkeypatch.setattr(+ search_engine_factory,+ "get_safe_module_class",+ lambda *args: RecordingEngine,+ )+ monkeypatch.setattr(+ module_whitelist, "get_safe_module_class", lambda *args: RecordingEngine+ )++ try:+ search = search_engine_factory.create_search_engine(+ primary, settings_snapshot=snapshot, programmatic_mode=True+ )+ assert search is not None+ if primary == "github":+ assert search.api_key == "configured-test-credential"+ strategy = LangGraphAgentStrategy(+ model=MagicMock(),+ search=search,+ citation_handler=object(),+ include_sub_research=False,+ settings_snapshot=snapshot,+ programmatic_mode=True,+ )+ tools = {+ tool.name: tool for tool in strategy._build_tools("A question")+ }+ assert set(tools) == {"web_search", "search_arxiv"}++ result = tools["web_search"].invoke({"query": "A question"})++ assert queries == [(primary, "A question")]+ assert "Primary result" in result+ assert len(strategy.collector.results) == 1+ assert snapshot == original_snapshot+ assert configs == original_configs++ # A later run with another primary must not inherit this selection+ # as an additional tool or enable either excluded engine.+ next_snapshot = {**snapshot, "search.tool": "arxiv"}+ next_strategy = LangGraphAgentStrategy(+ model=MagicMock(),+ search=search_engine_factory.create_search_engine(+ "arxiv", settings_snapshot=next_snapshot, programmatic_mode=True+ ),+ citation_handler=object(),+ include_sub_research=False,+ settings_snapshot=next_snapshot,+ programmatic_mode=True,+ )+ next_tools = {+ tool.name: tool+ for tool in next_strategy._build_tools("Another question")+ }+ assert set(next_tools) == {"web_search"}+ next_tools["web_search"].invoke({"query": "Another question"})+ assert queries == [+ (primary, "A question"),+ ("arxiv", "Another question"),+ ]+ assert snapshot == original_snapshot+ assert configs == original_configs+ finally:+ clear_active_context()diff --git a/tests/ui_tests/test_search_engine_dropdown_scope_ci.js b/tests/ui_tests/test_search_engine_dropdown_scope_ci.jsindex 100533e426..e7004f4515 100644--- a/tests/ui_tests/test_search_engine_dropdown_scope_ci.js+++ b/tests/ui_tests/test_search_engine_dropdown_scope_ci.js@@ -3,33 +3,9 @@* Search-Engine Dropdown: Scope + Strategy Awareness (CI-safe)* =============================================================*- * Covers the "scope- and strategy-aware search engine dropdown" feature- * (#5221 / issue #5204). Its frontend (research.js, custom_dropdown.js)- * merged cleanly from main; its backend (`_classify_options_for_egress`,- * the `agent_enabled` field on GET /settings/api/available-search-engines)- * was dropped by the Flask->FastAPI migration merge and hand-ported into- * web/routers/settings.py. The two halves have never been exercised- * together in a browser before this suite.- *- * What this proves, end to end (server response -> DOM):- * 1. GET /settings/api/available-search-engines?egress_scope=private_only&primary=searxng- * stamps every option with egress:{allowed,reason}, and the rendered- * dropdown disables exactly the denied ones (aria-disabled + a- * visible reason), never more, never fewer.- * 2. The same endpoint WITHOUT those query params (or with them blank)- * skips scope classification but still marks unapproved private- * instance URLs, and the adaptive dropdown disables exactly those.- * 3. An engine option carrying agent_enabled:false (collections only)- * is disabled precisely when the LangGraph Agent strategy is- * selected, and re-enabled the instant a different strategy is- * picked — no page reload, no server re-fetch (the flag travels on- * the already-loaded option list).- * 4. Changing the egress scope live re-fetches and updates the- * dropdown's disabled set without a reload, and if the- * currently-selected primary engine becomes disallowed under the- * new scope, the selection is reconciled to an allowed engine- * instead of being silently left in place (which would otherwise- * submit a value the backend precheck would reject).+ * Checks that the picker follows egress decisions and required-key presence,+ * reconciles selections after scope changes, and accepts an explicit primary+ * engine even when it is excluded from LangGraph's default tool list.** Run: node test_search_engine_dropdown_scope_ci.js*/@@ -38,6 +14,7 @@ const { setupTest, teardownTest, TestResults, log, withTimeout } = require('./teconst { seedCollection, deleteCollection } = require('./test_lib/fixtures');const ENGINES_PATH_SUFFIX = '/settings/api/available-search-engines';+const PRIMARY_SETTING_PATH = '/settings/api/search.tool';// research.js's dropdown-refresh logic (getCurrentEgressScopeForDropdown) only// treats these two as "filterable" scopes and appends ?egress_scope=<scope> to@@ -152,20 +129,7 @@ async function forceRefreshEngineList(page) {);}-/**- * Set #strategy to a NON-LangGraph value and verify the dropdown's- * agent_enabled classification actually reflects it (no item left disabled- * for a LangGraph-only reason).- *- * Why this needs verifying rather than trusting one select+refresh: custom_dropdown.js's- * updateDropdownOptions() freezes the dropdown registry's getOptions() to a snapshot- * of whatever array was passed at that call. applyStrategyToEngines() (the #strategy- * 'change' listener) and loadSearchEngineOptions() (triggered by the refresh button)- * can each push a snapshot; depending on their exact completion order the LAST one to- * call updateDropdownOptions wins, and it isn't always the one holding the freshest- * strategy mapping. Retrying — each attempt driven by a real DOM read, never a fixed- * sleep — converges deterministically without asserting on that internal ordering.- */+/** Set a known strategy and refresh before scope-focused assertions. */async function setNonLangGraphBaselineAndVerify(page, strategy, attempts = 6) {for (let attempt = 1; attempt <= attempts; attempt++) {await page.select('#strategy', strategy);@@ -182,21 +146,9 @@ async function setNonLangGraphBaselineAndVerify(page, strategy, attempts = 6) {);}-/**- * Select #strategy and verify (via the OPEN dropdown's live DOM) that the given- * engine's disabled state settles to `expectDisabled` — retried for the same- * registry-snapshot-ordering reason documented on setNonLangGraphBaselineAndVerify,- * without the forced refresh (this path is specifically proving the LIVE,- * no-refetch re-render works, so a refresh here would defeat the assertion).- */+/** Verify strategy changes preserve the expected engine availability. */async function selectStrategyLiveAndVerify(page, value, engineValue, expectDisabled, attempts = 5) {for (let attempt = 1; attempt <= attempts; attempt++) {- // updateDropdownOptions() only re-renders into the DOM when the list's- // computed style is visible at that instant — otherwise it silently- // just updates the registry for the NEXT open, leaving stale (already-- // rendered) items in place. Re-assert the dropdown is open immediately- // before selecting so the live re-render this assertion depends on- // actually has somewhere to paint into.await openSearchEngineDropdown(page);await page.select('#strategy', value);const ok = await page@@ -232,6 +184,66 @@ async function selectScopeAndWait(page, value) {);}+async function readSavedPrimaryEngine(page) {+ return page.evaluate(async (path) => {+ const response = await fetch(path, { credentials: 'same-origin' });+ if (!response.ok) throw new Error(`Could not read primary engine (HTTP ${response.status})`);+ const setting = await response.json();+ if (!setting || !Object.prototype.hasOwnProperty.call(setting, 'value')) {+ throw new Error('Primary-engine setting response has no value');+ }+ return setting.value;+ }, PRIMARY_SETTING_PATH);+}++async function selectPrimaryEngineAndWaitForSave(page, value) {+ const item = await page.$(`#search-engine-dropdown-list .ldr-custom-dropdown-item[data-value="${value}"]`);+ if (!item) throw new Error('Primary-engine option was not found');+ const saved = page.waitForResponse((response) => {+ try {+ const request = response.request();+ return request.method() === 'PUT' &&+ new URL(response.url()).pathname === PRIMARY_SETTING_PATH &&+ JSON.parse(request.postData() || '{}').value === value;+ } catch {+ return false;+ }+ }, { timeout: 20000 }).catch(() => null);+ try {+ await item.click();+ } catch (error) {+ await saved;+ throw error;+ }+ const response = await saved;+ if (!response || !response.ok()) {+ throw new Error('Primary-engine selection was not saved');+ }+}++async function restorePrimaryAndDeleteCollection(page, originalPrimary, collection) {+ if (originalPrimary === undefined) {+ if (collection) throw new Error('Original primary engine was not captured');+ return;+ }+ if (await readSavedPrimaryEngine(page) !== originalPrimary) {+ await page.evaluate(async (path, value) => {+ const csrf = document.querySelector('meta[name="csrf-token"]')?.content;+ const response = await fetch(path, {+ method: 'PUT',+ credentials: 'same-origin',+ headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrf || '' },+ body: JSON.stringify({ value }),+ });+ if (!response.ok) throw new Error(`Could not restore primary engine (HTTP ${response.status})`);+ }, PRIMARY_SETTING_PATH, originalPrimary);+ if (await readSavedPrimaryEngine(page) !== originalPrimary) {+ throw new Error('Original primary engine was not restored');+ }+ }+ if (collection) await deleteCollection(page, collection.id);+}+async function main() {log.section('Search-Engine Dropdown: Scope + Strategy Awareness');const ctx = await setupTest({ authenticate: true });@@ -258,10 +270,13 @@ async function main() {let deniedUnderPrivateOnly = null; // { value, reason }let deniedValuesUnderPrivateOnly = null; // Set<string>let allowedUnderPrivateOnly = null; // Set<string>- let deniedUnderAdaptive = null; // Set<string> blocked by the guarded URL overlay+ let deniedUnderAdaptive = null; // Set<string> blocked by URL guard or missing keyslet seededCollection = null;let restoreScopeTo = 'adaptive';let restoreStrategyTo = null;+ let restorePrimaryTo;+ let primarySelectionSave = null;+ let cleanupStarted = false;try {// ---------------------------------------------------------------@@ -275,18 +290,14 @@ async function main() {await page.waitForSelector('#strategy', { timeout: 15000 });await initialLoadP;+ restorePrimaryTo = await readSavedPrimaryEngine(page);restoreScopeTo = await page.$eval('#policy_egress_scope', (el) => el.value);if (restoreScopeTo !== 'adaptive') {await selectScopeAndWait(page, 'adaptive');}restoreStrategyTo = await page.$eval('#strategy', (el) => el.value);- // The account's saved default strategy may already be LangGraph Agent- // (agent_enabled filtering is orthogonal to, and stacks with, egress- // filtering — e.g. the built-in "github" engine ships agent_enabled:- // false). Pin a non-LangGraph baseline for every scope-focused test- // below so their assertions aren't polluted by the agent_enabled- // filter; the dedicated Strategy-awareness test switches deliberately.+ // Use a known strategy for the scope-focused assertions.const nonLangGraphStrategy = await page.$$eval('#strategy option', (els) =>els.map((e) => e.value).find((v) => v !== 'langgraph-agent'),);@@ -303,7 +314,9 @@ async function main() {return { passed: false, message: `Bad/empty response: ${JSON.stringify(r).slice(0, 200)}` };}const marked = r.data.engine_options.filter((o) => 'egress' in o);- deniedUnderAdaptive = new Set(marked.map((o) => o.value));+ deniedUnderAdaptive = new Set(r.data.engine_options+ .filter(o => o.egress?.allowed === false || (o.requires_api_key && !o.has_api_key))+ .map(o => o.value));const unexpected = marked.filter((o) => o.egress?.allowed !== false || o.egress?.reason !== 'private_url_unapproved');return {passed: unexpected.length === 0,@@ -315,7 +328,9 @@ async function main() {const r = await fetchEngineOptions(page, '?egress_scope=&primary=');if (!r.ok) return { passed: false, message: `HTTP ${r.status}` };const marked = r.data.engine_options.filter((o) => 'egress' in o);- const markedValues = new Set(marked.map((o) => o.value));+ const markedValues = new Set(r.data.engine_options+ .filter(o => o.egress?.allowed === false || (o.requires_api_key && !o.has_api_key))+ .map(o => o.value));const unexpected = marked.filter((o) => o.egress?.allowed !== false || o.egress?.reason !== 'private_url_unapproved');const sameSet = sameValueSet(markedValues, deniedUnderAdaptive);return {@@ -330,7 +345,7 @@ async function main() {const opts = r.data.engine_options;const missing = opts.filter((o) => !o.egress || typeof o.egress.allowed !== 'boolean');const denied = opts.filter((o) => o.egress && o.egress.allowed === false);- const allowed = opts.filter((o) => o.egress && o.egress.allowed === true);+ const allowed = opts.filter(o => o.egress?.allowed === true && !(o.requires_api_key && !o.has_api_key));const deniedWithoutReason = denied.filter((o) => !o.egress.reason);// A guarded private URL is denied even in adaptive scope. Choose@@ -339,7 +354,9 @@ async function main() {if (reconcilable) {deniedUnderPrivateOnly = { value: reconcilable.value, reason: reconcilable.egress.reason };}- deniedValuesUnderPrivateOnly = new Set(denied.map((o) => o.value));+ deniedValuesUnderPrivateOnly = new Set(opts+ .filter(o => o.egress?.allowed === false || (o.requires_api_key && !o.has_api_key))+ .map(o => o.value));allowedUnderPrivateOnly = new Set(allowed.map((o) => o.value));const passed = missing.length === 0 && denied.length > 0 && allowed.length > 0 && deniedWithoutReason.length === 0;@@ -356,9 +373,8 @@ async function main() {// ===============================================================// 2. DOM: dropdown rendering matches the API classification// ===============================================================- await run('Dropdown DOM', 'Adaptive scope disables exactly the guarded private URLs', async () => {- // Same registry-snapshot race as setNonLangGraphBaselineAndVerify: a- // still-in-flight refresh from setup can occasionally paint one more+ await run('Dropdown DOM', 'Adaptive scope disables guarded private URLs and missing required keys', async () => {+ // A still-in-flight refresh from setup can occasionally paint one more// stale frame after this test's own read. Re-verify via a forced// refresh (bounded, no fixed sleep) rather than assume one read is// final — this is about test synchronization, not the assertion.@@ -499,7 +515,7 @@ async function main() {// ===============================================================// 4. agent_enabled + LangGraph strategy// ===============================================================- await run('Strategy awareness', 'agent_enabled:false collection is disabled only under the LangGraph strategy', async () => {+ await run('Explicit selection', 'agent-hidden collection stays selectable under LangGraph and other strategies', async () => {await selectScopeAndWait(page, 'adaptive');seededCollection = await seedCollection(page, { agentEnabled: false });if (!seededCollection) {@@ -532,26 +548,28 @@ async function main() {}const enabledUnderNonLangGraph = !beforeItem.disabled;- // Flip to LangGraph while the dropdown stays open — proves the re-render is live,- // no reload / no re-fetch (the flag was already on the loaded option list).- await selectStrategyLiveAndVerify(page, 'langgraph-agent', engineValue, true);+ await selectStrategyLiveAndVerify(page, 'langgraph-agent', engineValue, false);const afterItems = await readDropdownItems(page);const afterItem = afterItems.find((i) => i.value === engineValue);- const disabledUnderLangGraph = !!afterItem?.disabled;- const reasonMentionsLangGraph = /langgraph/i.test(afterItem?.reason || '');+ const enabledUnderLangGraph = !!afterItem && !afterItem.disabled;+ if (cleanupStarted) throw new Error('Selection check ended before primary selection');+ primarySelectionSave = selectPrimaryEngineAndWaitForSave(page, engineValue);+ await primarySelectionSave;+ await page.waitForFunction(+ value => document.getElementById('search_engine_hidden')?.value === value,+ { timeout: 10000 }, engineValue,+ );- // Flip back — must re-enable without a reload.+ // Switching strategy must preserve the explicitly selected engine.await selectStrategyLiveAndVerify(page, nonLangGraphOption, engineValue, false);await closeOpenDropdown(page);- const passed = enabledUnderNonLangGraph && disabledUnderLangGraph && reasonMentionsLangGraph;+ const selected = await page.$eval('#search_engine_hidden', el => el.value);+ const passed = enabledUnderNonLangGraph && enabledUnderLangGraph && selected === engineValue;return {passed,- message: passed- ? `enabled under "${nonLangGraphOption}", disabled under langgraph-agent (reason: "${afterItem.reason}"), ` +- 're-enabled on switching back — all without a reload'- : `enabledUnderNonLangGraph=${enabledUnderNonLangGraph} disabledUnderLangGraph=${disabledUnderLangGraph} ` +- `reason="${afterItem?.reason}"`,+ message: `enabledUnderNonLangGraph=${enabledUnderNonLangGraph} ` ++ `enabledUnderLangGraph=${enabledUnderLangGraph} selectionPreserved=${selected === engineValue}`,};});} catch (error) {@@ -559,13 +577,14 @@ async function main() {console.error(error.stack);results.add('Suite', 'Unexpected Suite Error', false, error.message);} finally {- // Best-effort cleanup — never let a cleanup failure mask the test results above.+ // Restore the persisted primary before deleting a selected fixture.+ // A failed restore must leave the collection intact and fail the suite.+ cleanupStarted = true;+ if (primarySelectionSave) await primarySelectionSave.catch(() => {});try {- if (seededCollection) {- await deleteCollection(page, seededCollection.id);- }- } catch {- /* ignore */+ await restorePrimaryAndDeleteCollection(page, restorePrimaryTo, seededCollection);+ } catch (error) {+ results.add('Cleanup', 'Restore original primary engine', false, error.message);}try {const currentScope = await page.$eval('#policy_egress_scope', (el) => el.value).catch(() => null);@@ -591,7 +610,11 @@ async function main() {}}-main().catch((error) => {- console.error('Test runner failed:', error);- process.exit(1);-});+module.exports = { readSavedPrimaryEngine, selectPrimaryEngineAndWaitForSave, restorePrimaryAndDeleteCollection };++if (require.main === module) {+ main().catch((error) => {+ console.error('Test runner failed:', error);+ process.exit(1);+ });+}diff --git a/tests/web/routers/test_invalid_setting_responses.py b/tests/web/routers/test_invalid_setting_responses.pyindex cd3e130c0f..7c45ce70ce 100644--- a/tests/web/routers/test_invalid_setting_responses.py+++ b/tests/web/routers/test_invalid_setting_responses.py@@ -252,7 +252,7 @@ def test_invalid_concurrency_limit_does_not_skip_admission()monkeypatch.setattr(research,- "_precheck_collection_agent_enabled",+ "_precheck_search_engine_api_key",Mock(return_value=None),)monkeypatch.setattr(diff --git a/tests/web/routers/test_provider_request_types.py b/tests/web/routers/test_provider_request_types.pyindex 0de2dbaceb..6022e5c792 100644--- a/tests/web/routers/test_provider_request_types.py+++ b/tests/web/routers/test_provider_request_types.py@@ -1,10 +1,13 @@"""JSON types of the research-start string fields are checked before use.-``model_provider``, ``search_engine``, its ``search_tool`` alias and-``strategy`` are used with str methods once a start request is dispatched-(``normalize_provider``'s ``.lower()``, and ``.startswith`` / ``.lower()``-in ``_precheck_collection_agent_enabled``), so any other JSON type except-null is a 400 that names the field:+``model_provider``, ``search_engine`` and its ``search_tool`` alias are+used with str methods once a start request is dispatched (including+``normalize_provider``'s ``.lower()``). ``strategy`` is type-checked the+same way as an explicit boundary rejection: ``AdvancedSearchSystem``+already coerces a non-string ``strategy_name`` to ``source-based`` with+a warning (#7610), so without this check an API caller requesting a+non-string strategy would silently run a different strategy than asked;+instead, any other JSON type except null is a 400 that names the field:* at the async ``start_research`` boundary, before ``run_db_sync``dispatches any database work, and ahead of the missing-query checkdiff --git a/tests/web/routers/test_search_engine_run_selection.py b/tests/web/routers/test_search_engine_run_selection.pynew file mode 100644index 0000000000..1fbc9edf43--- /dev/null+++ b/tests/web/routers/test_search_engine_run_selection.py@@ -0,0 +1,275 @@+"""Explicit engine choices are independent of automatic agent discovery."""++import json+from contextlib import nullcontext+from types import SimpleNamespace+from unittest.mock import Mock++import pytest+from loguru import logger++from local_deep_research.settings.exceptions import SettingsValueError+from local_deep_research.web.routers import research, settings+from local_deep_research.web_search_engines import search_engines_config+++def engine_config(monkeypatch):+ config = {+ "collection_hidden": {+ "display_name": "Hidden collection",+ "agent_enabled": False,+ "requires_api_key": False,+ },+ "openlibrary": {+ "display_name": "Open Library",+ "agent_enabled": False,+ "requires_api_key": False,+ },+ "github": {+ "display_name": "GitHub",+ "agent_enabled": False,+ "requires_api_key": True,+ },+ }+ monkeypatch.setattr(+ search_engines_config, "search_config", lambda **kwargs: config+ )+ return config+++def manager():+ manager = Mock()+ manager.get_settings_snapshot.return_value = {}+ manager.get_setting.side_effect = lambda key, default=None: default+ return manager++[email protected]("key", [None, "", " ", "YOUR_API_KEY", "none"])+def test_required_key_is_reported_as_a_credential_problem(+ engine_config, manager, key+):+ manager.get_settings_snapshot.return_value = {+ "search.engine.web.github.api_key": {"value": key}+ }++ response = research._precheck_search_engine_api_key(+ manager, "github", "alice"+ )++ assert response.status_code == 400+ body = json.loads(response.body)+ assert body["reason"] == "search_api_key_missing"+ assert body["field"] == "search_engine"+ assert "GitHub requires an API key" in body["message"]+ assert "Settings" in body["message"]+ assert "collection" not in body["message"].lower()++[email protected]("wrapped", [False, True])+def test_configured_required_key_allows_an_agent_hidden_engine(+ engine_config, manager, wrapped+):+ key = "configured-test-credential"+ manager.get_settings_snapshot.return_value = {+ "search.engine.web.github.api_key": {"value": key} if wrapped else key+ }++ assert (+ research._precheck_search_engine_api_key(manager, "github", "alice")+ is None+ )+ assert engine_config["github"]["agent_enabled"] is False++[email protected]("engine", ["collection_hidden", "openlibrary"])+def test_optional_or_absent_credentials_do_not_block_selection(+ engine_config, manager, engine+):+ assert (+ research._precheck_search_engine_api_key(manager, engine, "alice")+ is None+ )+ assert engine_config[engine]["agent_enabled"] is False+++def test_engine_config_credential_is_recognized(engine_config, manager):+ engine_config["github"]["api_key"] = "configured-test-credential"+ assert (+ research._precheck_search_engine_api_key(manager, "github", "alice")+ is None+ )+++def test_credential_check_preserves_setting_diagnostics(engine_config, manager):+ error = SettingsValueError(+ "search.engine.web.github.requires_api_key",+ source="environment",+ reason="expected a valid checkbox value",+ )+ manager.get_settings_snapshot.side_effect = error+ response = research._precheck_search_engine_api_key(+ manager, "github", "alice"+ )+ assert response.status_code == 500+ assert json.loads(response.body)["message"] == str(error)+++def test_credential_check_reports_an_internal_failure(engine_config, manager):+ manager.get_settings_snapshot.side_effect = RuntimeError("internal detail")+ response = research._precheck_search_engine_api_key(+ manager, "github", "alice"+ )+ assert response.status_code == 500+ assert "internal detail" not in response.body.decode()++[email protected]("diagnose", [False, True])[email protected]("failure_stage", ["settings", "catalog"])+def test_credential_check_logs_unexpected_failure_by_type(+ monkeypatch, engine_config, manager, diagnose, failure_stage+):+ failure = RuntimeError("Configuration unavailable")+ if failure_stage == "settings":+ manager.get_settings_snapshot.side_effect = failure+ else:+ monkeypatch.setattr(+ search_engines_config, "search_config", Mock(side_effect=failure)+ )+ records = []+ logger.enable(research.__name__)+ sink = logger.add(+ lambda message: records.append(message.record),+ filter=lambda record: record["name"] == research.__name__,+ diagnose=diagnose,+ )+ try:+ response = research._precheck_search_engine_api_key(+ manager, "github", "alice"+ )+ finally:+ logger.remove(sink)+ logger.disable(research.__name__)++ assert response.status_code == 500+ assert "Configuration unavailable" not in response.body.decode()+ assert len(records) == 1+ assert records[0]["level"].name == "ERROR"+ assert records[0]["message"] == (+ "Failed to check search engine credentials (RuntimeError)"+ )+ assert records[0]["exception"] is None+++ "key", [None, "YOUR_API_KEY", "configured-test-credential"]+)[email protected]("query", [{}, {"egress_scope": "private_only"}])+def test_picker_exposes_only_credential_presence(+ monkeypatch, engine_config, manager, key, query+):+ manager.get_settings_snapshot.return_value = {+ "search.engine.web.github.api_key": {"value": key}+ }+ monkeypatch.setattr(+ settings, "get_user_db_session", lambda *a, **k: nullcontext(Mock())+ )+ monkeypatch.setattr(settings, "get_settings_manager", lambda *a: manager)+ # Other tests cover policy decisions; this pins the credential contract+ # both with and without the scope-aware response overlay.+ monkeypatch.setattr(settings, "_apply_guarded_url_overlay", Mock())+ monkeypatch.setattr(settings, "_classify_options_for_egress", Mock())++ result = settings.api_get_available_search_engines(+ SimpleNamespace(query_params=query), "alice"+ )++ options = {option["value"]: option for option in result["engine_options"]}+ assert options["github"]["has_api_key"] is (+ key == "configured-test-credential"+ )+ assert options["github"]["agent_enabled"] is False+ assert options["openlibrary"]["has_api_key"] is False+ assert options["openlibrary"]["requires_api_key"] is False+ assert (+ result["engines"]["github"]["has_api_key"]+ is options["github"]["has_api_key"]+ )+ if key:+ assert key not in json.dumps(result)+++ "strategy",+ ["langgraph-agent", "langgraph_agent", "mcp", "agentic", "source-based"],+)+ ("engine", "key", "expected_status"),+ [+ ("collection_hidden", None, 401),+ ("openlibrary", None, 401),+ ("github", "configured-test-credential", 401),+ ("github", None, 400),+ ],+)+def test_start_checks_keys_independently_of_agent_tool_membership(+ monkeypatch, engine_config, manager, strategy, engine, key, expected_status+):+ from local_deep_research import settings as settings_package+ from local_deep_research.database import session_context++ manager.get_settings_snapshot.return_value = {+ "search.engine.web.github.api_key": key+ }+ # Stop at the normal expired-session guard, before creating any research+ # records or starting a worker. The old collection check returned 400.+ session = Mock()+ session.query.return_value.filter.return_value.first.return_value = (+ SimpleNamespace(name="Hidden collection", agent_enabled=False)+ )+ session.query.return_value.filter_by.return_value.count.return_value = 0+ monkeypatch.setattr(+ research, "get_user_db_session", lambda *a: nullcontext(session)+ )+ monkeypatch.setattr(+ session_context, "get_user_db_session", lambda *a: nullcontext(session)+ )+ monkeypatch.setattr(+ settings_package, "SettingsManager", lambda *a, **k: manager+ )+ policy = Mock(return_value=None)+ monkeypatch.setattr(research, "_precheck_engine_policy", policy)+ monkeypatch.setattr(+ research, "user_research_start_gate", lambda *a: nullcontext()+ )+ password = Mock(return_value=(None, True))+ monkeypatch.setattr(research, "resolve_user_password", password)+ monkeypatch.setattr(+ "local_deep_research.web.routes.globals.reclaim_stale_user_active_research",+ Mock(return_value=False),+ )++ response = research._start_research_sync(+ {+ "query": "A test question",+ "model_provider": "ollama",+ "model": "test-model",+ "search_engine": engine,+ "iterations": 1,+ "questions_per_iteration": 1,+ "strategy": strategy,+ },+ "alice",+ "http://testserver",+ None,+ )++ assert response.status_code == expected_status+ if expected_status == 401:+ password.assert_called_once_with("alice")+ else:+ password.assert_not_called()+ assert json.loads(response.body)["reason"] == "search_api_key_missing"+ policy.assert_called_once()+ assert engine_config[engine]["agent_enabled"] is Falsediff --git a/tests/web/routes/test_research_routes_policy.py b/tests/web/routes/test_research_routes_policy.pyindex 691ab5d555..ac0c52c735 100644--- a/tests/web/routes/test_research_routes_policy.py+++ b/tests/web/routes/test_research_routes_policy.py@@ -19,9 +19,7 @@ import pytestfrom local_deep_research.security.egress.policy import PolicyDeniedErrorfrom local_deep_research.web.routers.research import (- LANGGRAPH_STRATEGY_NAME,_apply_policy_overrides,- _precheck_collection_agent_enabled,_precheck_engine_policy,)@@ -454,174 +452,3 @@ class TestPrecheckEnginePolicy:body["message"]== "Egress policy refused this run due to an invalid policy configuration.")---# ----------------------------------------------------------------------------# _precheck_collection_agent_enabled (LangGraph-only usability flag)-# ------------------------------------------------------------------------------def _collection_row(id="abc", name="Indian History", agent_enabled=True):- """Build a stand-in for a ``Collection`` ORM row.-- The precheck only reads ``id``, ``name`` and ``agent_enabled`` so a- MagicMock with the right attributes is enough — we don't need a- real SQLAlchemy session. Keeps the test independent of the- ``library`` schema migration history.- """- row = MagicMock()- row.id = id- row.name = name- row.agent_enabled = agent_enabled- return row---def _session_with_row(row):- """Mock the ``get_user_db_session()`` context manager so a given- row is returned by ``session.query(Collection).filter(...).first()``."""- session = MagicMock()- session.query.return_value.filter.return_value.first.return_value = row- cm = MagicMock()- cm.__enter__.return_value = session- cm.__exit__.return_value = False- return cm---class TestPrecheckCollectionAgentEnabled:- def test_langgraph_plus_hidden_collection_returns_400(self):- # LangGraph + a collection whose agent_enabled is False =>- # the agent will not pick it as a tool, so the run is broken.- # The precheck must surface a 400 with a field hint so the- # frontend can flash the strategy dropdown.- row = _collection_row(agent_enabled=False)- with patch(- "local_deep_research.database.session_context.get_user_db_session",- return_value=_session_with_row(row),- ):- result = _precheck_collection_agent_enabled(- "collection_abc", LANGGRAPH_STRATEGY_NAME, "user"- )- assert result is not None- body = json.loads(result.body)- assert result.status_code == 400- assert body["reason"] == "collection_agent_disabled"- # The message names the collection so the user knows which one- # to re-enable (matches the dropdown's inline reason).- assert "Indian History" in body["message"]- # Field hint points at the strategy dropdown so the form can- # flash the offender inline.- assert body["field"] == "strategy"-- def test_langgraph_plus_available_collection_returns_none(self):- # Same strategy, but the collection IS available to the agent =>- # no reason to refuse the run.- row = _collection_row(agent_enabled=True)- with patch(- "local_deep_research.database.session_context.get_user_db_session",- return_value=_session_with_row(row),- ):- result = _precheck_collection_agent_enabled(- "collection_abc", LANGGRAPH_STRATEGY_NAME, "user"- )- assert result is None-- def test_non_langgraph_strategy_ignores_agent_enabled(self):- # source-based never consults ``agent_enabled``, so pairing it- # with a hidden collection is fine — the precheck must NOT- # block. This is the canonical "usability, not security" case.- row = _collection_row(agent_enabled=False)- with patch(- "local_deep_research.database.session_context.get_user_db_session",- return_value=_session_with_row(row),- ):- for strategy in (- "source-based",- "focused-iteration",- "topic-organization",- "",- ):- result = _precheck_collection_agent_enabled(- "collection_abc", strategy, "user"- )- assert result is None, (- f"strategy {strategy!r} must not be blocked by "- f"agent_enabled=False"- )-- @pytest.mark.parametrize("strategy", [None, 123, True, ["mcp"], {"a": 1}])- def test_non_string_strategy_is_ignored_not_a_crash(self, strategy):- # ``strategy`` is read straight from the JSON body, so it can be any- # JSON type. A non-string can't name the LangGraph agent: the- # precheck must return None rather than raise AttributeError from- # ``.lower()`` (the constructor guard handles it downstream).- result = _precheck_collection_agent_enabled(- "collection_abc", strategy, "user"- )- assert result is None-- def test_non_collection_engine_is_skipped(self):- # The flag is only carried by collection_* engines in the- # current model. A static engine (or a misspelled id) must- # short-circuit before hitting the DB.- result = _precheck_collection_agent_enabled(- "arxiv", LANGGRAPH_STRATEGY_NAME, "user"- )- assert result is None-- def test_unknown_collection_id_defers_to_factory_pep(self):- # If the user submits a collection id that doesn't exist in- # the DB, the precheck should NOT mask it with- # ``collection_agent_disabled`` — the factory PEP / engine- # instantiation will produce a clearer error.- with patch(- "local_deep_research.database.session_context.get_user_db_session",- return_value=_session_with_row(None),- ):- result = _precheck_collection_agent_enabled(- "collection_missing", LANGGRAPH_STRATEGY_NAME, "user"- )- assert result is None-- def test_internal_error_is_swallowed_fails_open(self):- # A DB blip or internal exception must not block the run — the- # frontend is the primary UX guarantee, this is the second backstop.- # The LangGraph factory PEP / agent's tool loader will still filter- # the hidden collection at instantiation time.- with patch(- "local_deep_research.database.session_context.get_user_db_session",- side_effect=RuntimeError("transient internal error"),- ):- result = _precheck_collection_agent_enabled(- "collection_abc", LANGGRAPH_STRATEGY_NAME, "user"- )- assert result is None-- def test_engine_id_pattern_strips_collection_prefix_only(self):- # Defensive: the ``collection_<uuid>`` prefix is the only- # format ``search_engines_config.search_config`` produces. A- # bare ``collection_`` without a uuid should still be skipped- # silently (no DB hit, no 400) — the factory PEP will reject.- result = _precheck_collection_agent_enabled(- "collection_", LANGGRAPH_STRATEGY_NAME, "user"- )- assert result is None-- def test_langgraph_strategy_aliases_return_400(self):- # Strategy aliases ("langgraph_agent", "mcp", "agentic") must also- # be prechecked against agent_enabled=False collections.- row = _collection_row(agent_enabled=False)- with patch(- "local_deep_research.database.session_context.get_user_db_session",- return_value=_session_with_row(row),- ):- for alias in (- "langgraph-agent",- "langgraph_agent",- "mcp",- "agentic",- ):- result = _precheck_collection_agent_enabled(- "collection_abc", alias, "user"- )- assert result is not None- assert result.status_code == 400