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.

make search engine dropdown scope- and strategy-aware (#5221)

S54b4a352e3e1
diff --git a/changelog.d/+5204-scope-aware-search-dropdown.feature.md b/changelog.d/+5204-scope-aware-search-dropdown.feature.md
new file mode 100644
index 0000000000..aed0866439
--- /dev/null
+++ b/changelog.d/+5204-scope-aware-search-dropdown.feature.md
@@ -0,0 +1 @@
+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.
diff --git a/changelog.d/+5221-agent-enabled-dropdown-filter.feature.md b/changelog.d/+5221-agent-enabled-dropdown-filter.feature.md
new file mode 100644
index 0000000000..38f807f0e4
--- /dev/null
+++ b/changelog.d/+5221-agent-enabled-dropdown-filter.feature.md
@@ -0,0 +1 @@
+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.
diff --git a/docs/egress-modes.md b/docs/egress-modes.md
index f1c8fd659a..85d48e47d6 100644
--- a/docs/egress-modes.md
+++ b/docs/egress-modes.md
@@ -136,6 +136,15 @@ per-run dropdown / checkbox overrides. Values set there apply **only to that
research run** and do **not** persist to the settings database, so you can do a
one-off private run without changing your defaults.
+Under `Private only` or `Public only` Egress Scopes, the **Search Engine** dropdown
+is scope-aware: engines that would be refused at submit time under the active scope are rendered disabled
+with `aria-disabled="true"` and a one-line inline reason (e.g. *"Blocked: not a local
+source under Private only"*), so the mismatch is visible before you click Start Research. Under `Adaptive`,
+`Primary only (single engine)` (`Strict`), and `Unprotected` modes, all primary search engines remain enabled
+and selectable. Switching the scope automatically reconciles the selected engine value to an allowed option
+if the current engine is disallowed under the new scope. Switching the scope or strategy re-evaluates the
+dropdown state without a page reload. The backend precheck remains the enforcement boundary and second backstop.
+
## Audit log
Changes to any `policy.*` key, `llm.require_local_endpoint`,
diff --git a/src/local_deep_research/constants.py b/src/local_deep_research/constants.py
index 340bef1a60..5b8804e61c 100644
--- a/src/local_deep_research/constants.py
+++ b/src/local_deep_research/constants.py
@@ -148,6 +148,14 @@ AVAILABLE_STRATEGIES: List[Dict[str, str]] = [
},
]
+LANGGRAPH_STRATEGY_NAME = "langgraph-agent"
+LANGGRAPH_STRATEGY_ALIASES = (
+ "langgraph-agent",
+ "langgraph_agent",
+ "mcp",
+ "agentic",
+)
+
# --- Journal quality scoring thresholds ---
# Used by journal_quality.scoring.derive_quality_score and
diff --git a/src/local_deep_research/news/web.py b/src/local_deep_research/news/web.py
index 608b3fe203..a5689f368d 100644
--- a/src/local_deep_research/news/web.py
+++ b/src/local_deep_research/news/web.py
@@ -62,6 +62,11 @@ def create_news_blueprint():
"model_provider": "ollama",
"model": "",
"search_strategy": "source-based",
+ # Issue #5204: scope key for the egress-aware search-engine
+ # dropdown. ``load_user_settings`` overwrites this with the
+ # user's saved value; the hardcoded default is the
+ # safe-by-default ``adaptive`` for anonymous / no-DB paths.
+ "egress_scope": "adaptive",
}
# Only try to get settings if user is logged in
@@ -99,6 +104,10 @@ def create_news_blueprint():
"model_provider": "ollama",
"model": "",
"search_strategy": "source-based",
+ # Issue #5204: scope key for the egress-aware search-engine
+ # dropdown. Same rationale as in the new-subscription path
+ # above.
+ "egress_scope": "adaptive",
}
try:
@@ -220,6 +229,15 @@ def load_user_settings(
"custom_endpoint": settings_manager.get_setting(
"llm.openai_endpoint.url", ""
),
+ # Issue #5204: the news-subscription form's search
+ # engine dropdown is now scope-aware (it loads the
+ # engine list with the user's saved egress scope
+ # so incompatible options render disabled). Pull
+ # the saved values so the template can build the
+ # egress-aware API URL.
+ "egress_scope": settings_manager.get_setting(
+ "policy.egress_scope", "adaptive"
+ ),
}
)
except Exception:
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index e70f5f9002..05e51f0049 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -19,6 +19,7 @@ from loguru import logger
from ...settings.logger import log_settings
from sqlalchemy import case, func
from sqlalchemy.orm import Session
+from typing import Optional, Tuple
# Security imports
from ...config.constants import DEFAULT_OLLAMA_URL
@@ -77,7 +78,11 @@ from .globals import (
is_research_active,
set_termination_flag,
)
-from ...constants import DEFAULT_SEARCH_TOOL
+from ...constants import (
+ DEFAULT_SEARCH_TOOL,
+ LANGGRAPH_STRATEGY_ALIASES,
+ LANGGRAPH_STRATEGY_NAME as LANGGRAPH_STRATEGY_NAME,
+)
# Create a Blueprint for the research application
research_bp = Blueprint("research", __name__)
@@ -440,6 +445,91 @@ def _precheck_engine_policy(settings_manager, params, search_engine, username):
return None
+def _precheck_collection_agent_enabled(
+ search_engine: str,
+ strategy: str,
+ username: str,
+) -> Optional[Tuple]:
+ """Reject a run that pairs a LangGraph strategy with an agent-hidden
+ collection.
+
+ 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 the existing scope-vs-engine precheck
+ (``_precheck_engine_policy``): returns a Flask ``(response, status)``
+ tuple when the run should be rejected, or ``None`` to continue. 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, this
+ is the second backstop. Only fires for ``collection_<uuid>`` engines
+ (the only engines that carry the flag in the current model), and only
+ when ``strategy`` maps to the LangGraph agent — other strategies don't read
+ the flag at all.
+ """
+ if not search_engine or not search_engine.startswith("collection_"):
+ return None
+ if not strategy or strategy.lower() not in LANGGRAPH_STRATEGY_ALIASES:
+ return None
+ try:
+ from ...database.models.library import Collection
+ from ...database.session_context import get_user_db_session
+
+ # Engine id format: ``collection_<uuid>``. The split is safe
+ # because the id is constructed the same way in
+ # ``search_engines_config.search_config`` (line 211).
+ 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.
+ return None
+ # Default-on for unrecognised / NULL values keeps the
+ # behaviour-preserving contract used by the rest of the codebase
+ # (``_agent_enabled_default_on`` in rag_routes.py).
+ agent_enabled = getattr(row, "agent_enabled", True) is not False
+ if agent_enabled:
+ 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,
+ )
+ return (
+ jsonify(
+ {
+ "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."
+ ),
+ "reason": "collection_agent_disabled",
+ "field": "strategy",
+ }
+ ),
+ 400,
+ )
+ except Exception: # pragma: no cover - defensive
+ logger.exception("collection agent_enabled pre-check skipped")
+ return None
+
+
def _apply_policy_overrides(settings_snapshot, params):
"""Overlay form-supplied egress policy values onto the snapshot.
@@ -653,6 +743,19 @@ def start_research():
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
+ )
+ if agent_enabled_error is not None:
+ return agent_enabled_error
+
# Debug logging for model parameter specifically
logger.debug(
f"Extracted model value: '{model}' (type: {type(model).__name__})"
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index cd6a26a17d..a14fca630f 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -1847,13 +1847,151 @@ def _get_engine_icon_and_category(
return "🔍", "Search"
+def _classify_options_for_egress(
+ engine_options: list,
+ *,
+ egress_scope: str,
+ primary_engine: str,
+ settings_snapshot: dict,
+ username: Optional[str],
+ search_engines: Optional[dict] = None,
+) -> None:
+ """Stamp each engine option with an ``egress: {allowed, reason}`` field.
+
+ Used by ``api_get_available_search_engines`` when the caller passes
+ ``?egress_scope=…&primary=…``: the frontend needs to know which
+ options are selectable under the active scope so it can disable
+ (or hide) the rest in the dropdown. Issue #5204.
+
+ The decision is taken through the same PDP the request-boundary
+ precheck uses (``evaluate_engine``) so the dropdown's disabled set
+ and the server's 400 denials stay perfectly aligned. Dropdown filtering
+ strictly reflects PDP allowed decisions; frontend selection reconciliation
+ handles updating any invalid primary selection when scope changes. The factory PEP
+ still enforces at instantiation time; this is a UX filter, not a security boundary.
+
+ Operates in place; safe to call on a freshly built option list.
+ Failures are swallowed per option (logged) — a single bad engine
+ must not blank the whole dropdown.
+ """
+ try:
+ from ...security.egress.policy import (
+ context_from_snapshot,
+ evaluate_engine,
+ resolve_run_primary_engine,
+ )
+ except Exception: # pragma: no cover - defensive
+ logger.exception(
+ "egress policy unavailable; emitting unfiltered options"
+ )
+ return
+
+ if not isinstance(settings_snapshot, dict):
+ # Programming error: the route always passes a snapshot. Log it
+ # loudly so a future caller-side change is debuggable instead of
+ # silently falling back to the unfiltered list (PR #5221 review).
+ logger.error(
+ "_classify_options_for_egress received a non-dict "
+ "settings_snapshot (type={}); emitting unfiltered options",
+ type(settings_snapshot).__name__,
+ )
+ return
+
+ # Build an evaluation snapshot that reflects the requested scope and
+ # primary engine parameter overrides sent by the frontend (issue #5204).
+ eval_snapshot = dict(settings_snapshot)
+ if egress_scope:
+ eval_snapshot["policy.egress_scope"] = egress_scope
+ if primary_engine:
+ eval_snapshot["search.tool"] = primary_engine
+
+ # The precheck builds an EgressContext via context_from_snapshot; the
+ # adaptive resolution requires a primary, so fall back to the supplied
+ # primary and ultimately the saved search.tool.
+ try:
+ try:
+ primary = primary_engine or resolve_run_primary_engine(
+ eval_snapshot
+ )
+ except ValueError:
+ # ``resolve_run_primary_engine`` raises ValueError when
+ # ``search.tool`` is missing/blank/non-string and no
+ # ``default`` is given. That's the only documented failure
+ # mode — narrow the catch so unrelated bugs (e.g. an
+ # AttributeError on a future code path) surface instead of
+ # being silently swallowed (PR #5221 review).
+ primary = primary_engine or eval_snapshot.get("search.tool", "")
+ try:
+ ctx = context_from_snapshot(
+ eval_snapshot,
+ primary,
+ username=username,
+ )
+ except Exception:
+ # ``context_from_snapshot`` raises ``PolicyDeniedError`` for
+ # an unknown scope (``unknown_egress_scope``) and ``ValueError``
+ # for a malformed snapshot; either way the precheck would
+ # 400 the run. Stamp a permissive decision so the frontend
+ # falls back to the precheck instead of a half-blanked
+ # dropdown. Use logger.exception (dev-only traceback, no
+ # exc_info kwarg on logger.warning which would expose a
+ # full traceback at WARNING level in production — PR #5221
+ # review).
+ logger.exception(
+ "_classify_options_for_egress: context build failed; "
+ "emitting permissive policy_unavailable decisions"
+ )
+ for opt in engine_options:
+ opt["egress"] = {
+ "allowed": True,
+ "reason": "policy_unavailable",
+ }
+ return
+ except Exception: # pragma: no cover - defensive
+ logger.exception(
+ "egress context build failed; emitting unfiltered options"
+ )
+ return
+
+ for opt in engine_options:
+ engine_id = opt.get("value")
+ try:
+ metadata = search_engines.get(engine_id) if search_engines else None
+ decision = evaluate_engine(
+ engine_id,
+ ctx,
+ settings_snapshot=eval_snapshot,
+ metadata=metadata,
+ )
+ opt["egress"] = {
+ "allowed": bool(decision.allowed),
+ "reason": decision.reason,
+ }
+ except Exception: # pragma: no cover - defensive
+ logger.exception(f"egress decision failed for engine {engine_id}")
+ opt["egress"] = {"allowed": True, "reason": "decision_error"}
+
+
@settings_bp.route("/api/available-search-engines", methods=["GET"])
@login_required
@with_user_session()
def api_get_available_search_engines(
db_session: Optional[Session] = None, settings_manager=None
):
- """Get available search engines"""
+ """Get available search engines.
+
+ Optional query params (issue #5204):
+ ``egress_scope`` — when set, each option gets an
+ ``egress: {allowed, reason}`` field matching the same PDP the
+ request-boundary precheck uses. The frontend uses this to disable
+ (or hide) options that would be refused under the active scope.
+ ``primary`` — the user's saved primary search tool, used by the
+ PDP for strict / adaptive scope resolution.
+
+ When ``egress_scope`` is absent the response shape is unchanged
+ (zero behavior impact on existing callers — the settings page,
+ the news form, etc.).
+ """
try:
# Get search engines using the same approach as search_engines_config.py
from ...web_search_engines.search_engines_config import search_config
@@ -1872,6 +2010,18 @@ def api_get_available_search_engines(
if not isinstance(favorites, list):
favorites = []
+ # Issue #5204: optional egress-scope filter. The scope/primary
+ # query params opt INTO a per-option egress decision; without
+ # them the response is the historical, unfiltered list.
+ requested_scope = (
+ (request.args.get("egress_scope") or "").strip().lower()
+ )
+ requested_primary = (request.args.get("primary") or "").strip()
+ apply_egress_filter = requested_scope in (
+ "private_only",
+ "public_only",
+ )
+
# Extract search engines from config
engines_dict = {}
engine_options = []
@@ -1954,6 +2104,16 @@ 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 that the LangGraph
+ # research agent hides from its specialized tool list.
+ # Defaults to True so engines that don't carry the
+ # flag (only ``collection_*`` currently sets it
+ # explicitly) stay selectable — the frontend's
+ # LangGraph-strategy check is the only consumer, and
+ # it short-circuits when the strategy isn't
+ # LangGraph, so a True default is safe everywhere.
+ "agent_enabled": engine_data.get("agent_enabled", True),
}
)
@@ -1966,6 +2126,28 @@ def api_get_available_search_engines(
)
)
+ # Issue #5204: when the caller opts in via ?egress_scope=&primary=,
+ # stamp each option with the PDP's per-engine decision so the
+ # frontend can disable/hide the ones that would be refused at
+ # submit time. UNPROTECTED and missing-scope callers get the
+ # unfiltered list (the historical shape).
+ if apply_egress_filter:
+ try:
+ policy_snapshot = settings_manager.get_settings_snapshot()
+ except Exception: # pragma: no cover - defensive
+ logger.exception(
+ "settings snapshot unavailable for egress filter"
+ )
+ policy_snapshot = {}
+ _classify_options_for_egress(
+ engine_options,
+ egress_scope=requested_scope,
+ primary_engine=requested_primary,
+ settings_snapshot=policy_snapshot or {},
+ username=username,
+ search_engines=search_engines,
+ )
+
# If no engines found, log the issue but return empty list
if not engine_options:
logger.warning("No search engines found in configuration")
diff --git a/src/local_deep_research/web/static/css/custom_dropdown.css b/src/local_deep_research/web/static/css/custom_dropdown.css
index b721f0c7ab..18aca18216 100644
--- a/src/local_deep_research/web/static/css/custom_dropdown.css
+++ b/src/local_deep_research/web/static/css/custom_dropdown.css
@@ -79,6 +79,34 @@ body.ldr-dropdown-active {
background-color: rgba(var(--accent-primary-rgb), 0.1);
}
+/* Issue #5204: scope-aware disabled entries. Mirrors the native
+ <option disabled> contract: greyed label, no hover/active cue, the
+ inline reason is dimmer so it doesn't compete with the label for
+ attention. The cursor stays default (not pointer) so the user gets
+ the same "this is unselectable" cue they get from native selects. */
+.ldr-custom-dropdown-item--disabled,
+.ldr-custom-dropdown-item--disabled.active {
+ cursor: default;
+ opacity: 0.55;
+ background-color: transparent;
+}
+
+.ldr-custom-dropdown-item--disabled:hover {
+ /* Disable the active/hover background cue so the user can't be
+ tricked into thinking a click will do anything. The native
+ <option disabled> shows no hover affordance for the same
+ reason. */
+ background-color: transparent;
+}
+
+.ldr-custom-dropdown-item--disabled .ldr-dropdown-item-disabled-reason {
+ display: block;
+ margin-top: 2px;
+ font-size: 0.8em;
+ color: var(--text-muted, #8a8aa0);
+ font-style: italic;
+}
+
.ldr-custom-dropdown-item .ldr-highlight {
background-color: rgba(var(--accent-primary-rgb), 0.3);
border-radius: 2px;
diff --git a/src/local_deep_research/web/static/js/components/custom_dropdown.js b/src/local_deep_research/web/static/js/components/custom_dropdown.js
index d823b23cc9..74a0128864 100644
--- a/src/local_deep_research/web/static/js/components/custom_dropdown.js
+++ b/src/local_deep_research/web/static/js/components/custom_dropdown.js
@@ -158,6 +158,11 @@
const div = document.createElement('div');
div.className = 'ldr-custom-dropdown-item';
+ const isDisabled = item.disabled === true;
+ if (isDisabled) {
+ div.classList.add('ldr-custom-dropdown-item--disabled');
+ div.setAttribute('aria-disabled', 'true');
+ }
// Add ARIA role and unique ID for accessibility
div.setAttribute('role', 'option');
@@ -178,23 +183,45 @@
window.safeSetTextContent(labelSpan, item.label);
div.appendChild(labelSpan);
+ // Disabled reason label + aria-describedby (see the
+ // matching block in updateDropdown — kept inline to
+ // avoid the render branching out into a shared helper
+ // for the two near-duplicate render paths).
+ if (isDisabled && item.disabled_reason) {
+ const reasonId = `${dropdownInfo.dropdownId}-option-${index}-reason`;
+ const reasonSpan = document.createElement('span');
+ reasonSpan.className = 'ldr-dropdown-item-disabled-reason';
+ reasonSpan.id = reasonId;
+ reasonSpan.textContent = item.disabled_reason;
+ div.appendChild(reasonSpan);
+ div.setAttribute('aria-describedby', reasonId);
+ }
+
div.setAttribute('data-value', item.value);
div.addEventListener('click', (e) => {
if (e.target.classList.contains('ldr-dropdown-favorite-star')) {
return;
}
+ // Disabled entries: no selection, no onSelect, no
+ // hidden-input change — same contract as the
+ // matching block in updateDropdown.
+ if (isDisabled) {
+ e.preventDefault();
+ e.stopPropagation();
+ return;
+ }
// Set display value
input.value = item.label;
+ // Call original onSelect callback FIRST so any change listener sees the new selection
+ if (dropdownInfo.onSelect) {
+ dropdownInfo.onSelect(item.value, item);
+ }
// Update hidden input if exists
const hiddenInput = document.getElementById(`${input.id}_hidden`);
if (hiddenInput) {
hiddenInput.value = item.value;
hiddenInput.dispatchEvent(new Event('change', { bubbles: true }));
}
- // Call original onSelect callback
- if (dropdownInfo.onSelect) {
- dropdownInfo.onSelect(item.value, item);
- }
// Hide dropdown properly via hideDropdown to reset aria-expanded and state
dropdownInfo.hideDropdown?.();
});
@@ -402,6 +429,14 @@
const div = document.createElement('div');
div.className = 'ldr-custom-dropdown-item';
+ const isDisabled = item.disabled === true;
+ if (isDisabled) {
+ // Mirrors the visual contract of a native <option
+ // disabled> entry: greyed label, the OS does not
+ // activate it on click, keyboard nav skips it.
+ div.classList.add('ldr-custom-dropdown-item--disabled');
+ div.setAttribute('aria-disabled', 'true');
+ }
// Add ARIA role and unique ID for accessibility
div.setAttribute('role', 'option');
@@ -424,6 +459,22 @@
window.safeSetInnerHTML(labelSpan, highlightedText, true);
div.appendChild(labelSpan);
+ // Disabled reason label: surfaces "Blocked: not a local
+ // source under Private only" etc. inline with the entry
+ // so the user can see WHY a familiar engine is greyed
+ // out (issue #5204: the teaching cue the egress-modes
+ // doc keeps reaching for). Also exposed to screen
+ // readers via aria-describedby + a hidden span.
+ if (isDisabled && item.disabled_reason) {
+ const reasonId = `${dropdownId}-option-${index}-reason`;
+ const reasonSpan = document.createElement('span');
+ reasonSpan.className = 'ldr-dropdown-item-disabled-reason';
+ reasonSpan.id = reasonId;
+ reasonSpan.textContent = item.disabled_reason;
+ div.appendChild(reasonSpan);
+ div.setAttribute('aria-describedby', reasonId);
+ }
+
div.setAttribute('data-value', item.value);
// Handle item click (on the label span or the whole item minus the star)
@@ -432,14 +483,31 @@
if (e.target.classList.contains('ldr-dropdown-favorite-star')) {
return;
}
+ // Disabled entries mirror the native <option disabled>
+ // contract: click is a no-op (no selection, no
+ // change event, no onSelect).
+ if (isDisabled) {
+ e.preventDefault();
+ e.stopPropagation();
+ return;
+ }
e.preventDefault();
e.stopPropagation();
// Set display value
input.value = item.label;
- // Update hidden input value
- updateHiddenField(item.value);
- // Call onSelect callback
+ // IMPORTANT: invoke the onSelect callback BEFORE
+ // dispatching the hidden input change event. The
+ // change listener in research.js calls
+ // applyEgressScopeToEngines() which reads the
+ // just-selected primary via
+ // getCurrentPrimaryForDropdown(); if the change
+ // event fires first while the in-memory selection
+ // is still stale, the re-fetch carries the previous
+ // primary and the new selection is briefly marked
+ // unavailable (issue #5204 follow-up review).
onSelect(item.value, item);
+ // Update hidden input value (dispatches change)
+ updateHiddenField(item.value);
// Set flag to prevent immediate reopening
justSelected = true;
// Hide dropdown
@@ -516,6 +584,25 @@
input.addEventListener('keydown', (e) => {
let items = dropdownList.querySelectorAll('.ldr-custom-dropdown-item');
+ // Helper: find the next non-disabled index in `items` starting
+ // from `from`, wrapping at the ends. Returns -1 if every
+ // entry is disabled (mirrors a native <select> with only
+ // disabled options). Disabled entries stay reachable via
+ // the DOM (so screen readers / Tab key still find them
+ // and the inline reason is visible), they just can't be
+ // *selected* — the same contract native UIs use.
+ function nextEnabledIndex(from, direction) {
+ if (items.length === 0) return -1;
+ let i = ((from % items.length) + items.length) % items.length;
+ for (let step = 0; step < items.length; step++) {
+ if (!items[i].classList.contains('ldr-custom-dropdown-item--disabled')) {
+ return i;
+ }
+ i = (i + direction + items.length) % items.length;
+ }
+ return -1;
+ }
+
if (e.key === 'ArrowDown') {
e.preventDefault();
if (!isOpen) {
@@ -524,9 +611,10 @@
updateDropdown();
// Re-query after DOM rebuild
items = dropdownList.querySelectorAll('.ldr-custom-dropdown-item');
- selectedIndex = items.length > 0 ? 0 : -1;
+ selectedIndex = nextEnabledIndex(0, 1);
} else if (items.length > 0) {
- selectedIndex = (selectedIndex + 1) % items.length;
+ const start = selectedIndex < 0 ? 0 : selectedIndex + 1;
+ selectedIndex = nextEnabledIndex(start % items.length, 1);
}
} else if (e.key === 'ArrowUp') {
e.preventDefault();
@@ -536,16 +624,23 @@
updateDropdown();
// Re-query after DOM rebuild
items = dropdownList.querySelectorAll('.ldr-custom-dropdown-item');
- selectedIndex = items.length > 0 ? items.length - 1 : -1;
+ selectedIndex = nextEnabledIndex(items.length - 1, -1);
} else if (items.length > 0) {
- selectedIndex = (selectedIndex - 1 + items.length) % items.length;
+ const start = selectedIndex <= 0 ? items.length - 1 : selectedIndex - 1;
+ selectedIndex = nextEnabledIndex(start, -1);
}
} else if (e.key === 'Enter') {
e.preventDefault();
if (selectedIndex >= 0 && selectedIndex < items.length) {
- // Select the highlighted item
+ // Select the highlighted item, but only if it's
+ // enabled. A disabled entry that's been Tab'd
+ // into (highlighted via click) cannot be selected
+ // via Enter — matches the native contract.
const selectedItem = items[selectedIndex];
+ if (selectedItem.classList.contains('ldr-custom-dropdown-item--disabled')) {
+ return;
+ }
const value = selectedItem.getAttribute('data-value');
const item = getOptions().find(o => o.value === value);
if (!item) {
@@ -554,30 +649,41 @@
}
// Update display value
input.value = item.label;
- // Update hidden input
- updateHiddenField(value);
- // Call callback
+ // onSelect first so any change listener sees the
+ // new primary, then update the hidden input (which
+ // dispatches the change event). See the matching
+ // note in handleItemClick above.
onSelect(value, item);
+ // Update hidden input (dispatches change)
+ updateHiddenField(value);
} else if (items.length > 0 && selectedIndex === -1) {
// No item explicitly selected, but there are filtered results
- // Auto-select the first item in the filtered list
- const firstItem = items[0];
- const value = firstItem.getAttribute('data-value');
- const item = getOptions().find(o => o.value === value);
- if (item) {
- // Update display value
- input.value = item.label;
- // Update hidden input
- updateHiddenField(value);
- // Call callback
- onSelect(value, item);
+ // Auto-select the first ENABLED item in the filtered
+ // list. Skipping the disabled head keeps the Enter
+ // shortcut consistent with the arrow-key flow.
+ const firstEnabledIndex = nextEnabledIndex(0, 1);
+ if (firstEnabledIndex >= 0) {
+ const firstItem = items[firstEnabledIndex];
+ const value = firstItem.getAttribute('data-value');
+ const item = getOptions().find(o => o.value === value);
+ if (item) {
+ // Update display value
+ input.value = item.label;
+ // onSelect first, then hidden-field update
+ // (dispatches change). See the matching note
+ // in handleItemClick above.
+ onSelect(value, item);
+ // Update hidden input (dispatches change)
+ updateHiddenField(value);
+ }
}
} else if (allowCustomValues && input.value.trim()) {
// Use the custom value
const customValue = input.value.trim();
- // Update hidden input with custom value
- updateHiddenField(customValue);
+ // onSelect first so any change listener sees the
+ // new value, then update the hidden input.
onSelect(customValue, null);
+ updateHiddenField(customValue);
}
hideDropdown();
} else if (e.key === 'Escape') {
@@ -586,16 +692,14 @@
} else if (e.key === 'Home') {
if (isOpen) {
e.preventDefault();
- if (items.length > 0) {
- selectedIndex = 0;
- }
+ // Jump to the first ENABLED entry, not just index 0
+ // (which may be a band-spanning disabled head).
+ selectedIndex = nextEnabledIndex(0, 1);
}
} else if (e.key === 'End') {
if (isOpen) {
e.preventDefault();
- if (items.length > 0) {
- selectedIndex = items.length - 1;
- }
+ selectedIndex = nextEnabledIndex(items.length - 1, -1);
}
}
@@ -693,13 +797,16 @@
}
if (triggerChange) {
- updateHiddenField(value);
- // Also call onSelect if triggerChange is true
+ // onSelect first so any change listener sees the
+ // new value, then update the hidden input
+ // (dispatches change). See the matching note in
+ // handleItemClick above.
if (matchedOption) {
onSelect(value, matchedOption);
} else {
onSelect(value, { value, label: value });
}
+ updateHiddenField(value);
} else if (hiddenInput) {
// Even if we don't trigger events, we should update the hidden field
hiddenInput.value = value;
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 0bb76d0232..b5a3c1150c 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -92,6 +92,15 @@
let selectedSearchEngineValue = '';
const searchEngineSelectedIndex = -1;
+ // Generation token + AbortController for the egress-scope
+ // reapplier. Rapid scope/primary changes would otherwise race:
+ // every response unconditionally overwrites searchEngineOptions,
+ // so an older response completing last could render
+ // classifications for a scope/primary that is no longer current.
+ // Issue #5204 follow-up review.
+ let applyEgressScopeSeq = 0;
+ let applyEgressScopeController = null;
+
// Track initialization to prevent unwanted saves during initial setup
let isInitializing = true;
@@ -388,24 +397,26 @@
handleSearchEngineFavoriteToggle
);
- // If we have a last selected search engine, try to select it
+ // If we have a last selected search engine, try to select it if allowed
const lastSearchEngine = searchEngineInput?.getAttribute('data-initial-value') ||
localStorage.getItem('selected_search_engine');
if (lastSearchEngine) {
- // Find the matching engine
const matchingEngine = searchEngineOptions.find(engine =>
- engine.value === lastSearchEngine || engine.id === lastSearchEngine);
+ (engine.value === lastSearchEngine || engine.id === lastSearchEngine) && !engine.disabled);
if (matchingEngine) {
searchEngineInput.value = matchingEngine.label;
selectedSearchEngineValue = matchingEngine.value;
- // Update hidden input if exists
const hiddenInput = document.getElementById('search_engine_hidden');
if (hiddenInput) {
hiddenInput.value = matchingEngine.value;
}
+ } else {
+ reconcileSearchEngineSelection(searchEngineOptions);
}
+ } else {
+ reconcileSearchEngineSelection(searchEngineOptions);
}
}
}
@@ -627,28 +638,26 @@
}
}
- // Set initial search engine value if available
+ // Set initial search engine value if available and allowed
if (searchEngineInput) {
const initialSearchEngine = searchEngineInput.getAttribute('data-initial-value');
if (initialSearchEngine) {
- // Find the matching search engine in the options
const matchingEngine = searchEngineOptions.find(e =>
- e.value === initialSearchEngine || e.id === initialSearchEngine
+ (e.value === initialSearchEngine || e.id === initialSearchEngine) && !e.disabled
);
if (matchingEngine) {
searchEngineInput.value = matchingEngine.label;
selectedSearchEngineValue = matchingEngine.value;
+ const hiddenInput = document.getElementById('search_engine_hidden');
+ if (hiddenInput) {
+ hiddenInput.value = selectedSearchEngineValue;
+ }
} else {
- searchEngineInput.value = initialSearchEngine;
- selectedSearchEngineValue = initialSearchEngine;
- }
-
- // Update hidden input
- const hiddenInput = document.getElementById('search_engine_hidden');
- if (hiddenInput) {
- hiddenInput.value = selectedSearchEngineValue;
+ reconcileSearchEngineSelection(searchEngineOptions);
}
+ } else {
+ reconcileSearchEngineSelection(searchEngineOptions);
}
}
}
@@ -918,6 +927,11 @@
const searchEngine = this.value;
SafeLogger.log('Search engine changed to:', searchEngine);
saveSearchSetting('search.tool', searchEngine);
+ // Issue #5204: re-apply the egress-scope filter now
+ // that the selected primary changed.
+ if (typeof applyEgressScopeToEngines === 'function') {
+ applyEgressScopeToEngines();
+ }
});
}
@@ -953,6 +967,19 @@
const selectedValue = this.value;
const generation = ++policyScopeSaveGeneration;
applyPrivacyPanelScope(selectedValue);
+ // Issue #5204: re-fetch the search-engine list under the
+ // new scope so the dropdown's disabled set reflects
+ // what would actually be accepted at submit time. The
+ // backend's precheck stays as the security guarantee;
+ // this is the UX layer that makes the form impossible
+ // to misconfigure by default. Fired on change rather
+ // than on save success because submit reads the scope
+ // from the form, not from the saved setting; if the
+ // save is rejected, refreshPolicyScopeFromServer
+ // reverts the select and re-mirrors the dropdown.
+ if (typeof applyEgressScopeToEngines === 'function') {
+ applyEgressScopeToEngines();
+ }
policyScopeSaveQueue = policyScopeSaveQueue
.catch(() => undefined)
.then(() => saveSearchSetting(
@@ -975,6 +1002,22 @@
// in sync without requiring a roundtrip).
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() {
@@ -1768,18 +1811,15 @@
}
});
- // Update search engine if we have a valid value
+ // Update search engine if we have a valid allowed value
const searchEngineSetting = data.settings["search.tool"];
if (searchEngineSetting && searchEngineSetting.value && searchEngineInput) {
const engineValue = searchEngineSetting.value;
SafeLogger.log('Setting search engine to:', engineValue);
- // Save to localStorage
- // Search engine saved to DB
-
- // Find the engine in our loaded options
+ // Find the engine in our loaded options (must not be disabled)
const matchingEngine = searchEngineOptions.find(e =>
- e.value === engineValue || e.id === engineValue
+ (e.value === engineValue || e.id === engineValue) && !e.disabled
);
if (matchingEngine) {
@@ -1795,16 +1835,7 @@
hiddenInput.value = engineValue;
}
} else {
- // If no matching engine found, just set the raw value
- SafeLogger.warn(`No matching search engine found for '${engineValue}'`);
- searchEngineInput.value = engineValue;
- selectedSearchEngineValue = engineValue;
-
- // Also update hidden input if it exists
- const hiddenInput = document.getElementById('search_engine_hidden');
- if (hiddenInput) {
- hiddenInput.value = engineValue;
- }
+ reconcileSearchEngineSelection(searchEngineOptions);
}
searchEngineInput.disabled = !searchEngineSetting.editable;
@@ -2122,11 +2153,427 @@
}
}
+ // Read the current egress scope for the dropdown's egress-aware
+ // API call. Returns null when the form is in "no filtering"
+ // mode (no scope set, or Unprotected — the escape hatch where
+ // every engine is allowed). Mirrors the backend's
+ // ``apply_egress_filter`` branch in
+ // ``api_get_available_search_engines`` (issue #5204).
+ function getCurrentEgressScopeForDropdown() {
+ const sel = document.getElementById('policy_egress_scope');
+ if (!sel) return null;
+ const val = (sel.value || '').toLowerCase().trim();
+ if (val === 'private_only' || val === 'public_only') return val;
+ return null;
+ }
+
+ // Canonical LangGraph strategy id — mirrors
+ // ``LANGGRAPH_STRATEGY_NAME`` in web/routes/research_routes.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. Prefer the in-memory
+ // selection (the most recent value the form has); fall back to
+ // the hidden input for the initial-load case.
+ function getCurrentPrimaryForDropdown() {
+ if (selectedSearchEngineValue) return selectedSearchEngineValue;
+ const hidden = document.getElementById('search_engine_hidden');
+ if (hidden && hidden.value) return hidden.value;
+ return '';
+ }
+
+ // Build the egress-aware URL for GET /api/available-search-engines.
+ // Centralised so the initial load, the refresh button, and the
+ // scope-change reapplier all ask the same question.
+ function buildEgressAwareEnginesURL(scope, primary) {
+ const base = URLS.SETTINGS_API.AVAILABLE_SEARCH_ENGINES;
+ try {
+ const u = new URL(base, window.location.origin);
+ u.searchParams.set('egress_scope', scope);
+ if (primary) u.searchParams.set('primary', primary);
+ return u.toString();
+ } catch (_e) {
+ // window.location.origin is missing in some test envs
+ // (jsdom, happy-dom). Fall back to a relative URL with
+ // manual query-string construction.
+ const sep = base.indexOf('?') >= 0 ? '&' : '?';
+ const parts = [`egress_scope=${encodeURIComponent(scope)}`];
+ if (primary) parts.push(`primary=${encodeURIComponent(primary)}`);
+ return base + sep + parts.join('&');
+ }
+ }
+
+ // Re-fetch the search engine list under the current egress scope
+ // and re-render the dropdown so disabled markers reflect the new
+ // scope. The backend's precheck (web/routes/research_routes.py::
+ // _precheck_engine_policy) is the security guarantee; this is the
+ // UX guarantee that keeps the user from having to submit to
+ // discover the mismatch (issue #5204).
+ //
+ // Wire points:
+ // 1. Initial load — called once after loadSearchEngineOptions
+ // resolves in initializeResearch / initializeDropdowns (the
+ // load already uses the right scope via the egress-aware URL,
+ // so this is a no-op for the initial pass; the function
+ // exists for the post-scope-change reapplier).
+ // 2. Egress Scope change — called from the policy_egress_scope
+ // change listener (re-fetches with the new scope).
+ // 3. search.tool change — called when the user picks a different
+ // engine.
+ //
+ // If the active scope renders the current selection disallowed (e.g.
+ // switching to private_only with a public engine selected),
+ // reconcileSearchEngineSelection updates the selection to an allowed
+ // engine (searxng preferred / library fallback).
+ function applyEgressScopeToEngines() {
+ // The dropdown instance is registered globally by
+ // setupCustomDropdown; refresh its options source + nudge a
+ // re-render if the dropdown is currently open so disabled
+ // markers appear without the user having to close + reopen.
+ const apiURL = (() => {
+ const scope = getCurrentEgressScopeForDropdown();
+ const primary = getCurrentPrimaryForDropdown();
+ return scope
+ ? buildEgressAwareEnginesURL(scope, primary)
+ : URLS.SETTINGS_API.AVAILABLE_SEARCH_ENGINES;
+ })();
+
+ // Issue #5204 follow-up review: a rapid burst of scope/primary
+ // changes fires overlapping fetches. Without cancellation, the
+ // last response to arrive wins — and it may not match the
+ // scope/primary currently selected. Track a per-instance
+ // generation token + AbortController so superseded requests
+ // are dropped before they mutate the dropdown's options.
+ const token = ++applyEgressScopeSeq;
+ if (applyEgressScopeController) {
+ try {
+ applyEgressScopeController.abort();
+ } catch (_e) {
+ // Defensive: abort() should never throw, but if it does
+ // (some test envs stub AbortController) we still want
+ // the new fetch to proceed.
+ }
+ }
+ const controller = new AbortController();
+ applyEgressScopeController = controller;
+
+ if (searchEngineInput && searchEngineInput.parentNode) {
+ searchEngineInput.parentNode.classList.add('ldr-loading');
+ }
+
+ return fetch(apiURL, { signal: controller.signal })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((data) => {
+ // If a newer call has started since this fetch began,
+ // drop the response on the floor — the newer fetch's
+ // URL represents the current scope/primary.
+ if (token !== applyEgressScopeSeq) return;
+ if (searchEngineInput && searchEngineInput.parentNode) {
+ searchEngineInput.parentNode.classList.remove('ldr-loading');
+ }
+ if (!data || !Array.isArray(data.engine_options)) return;
+ // Reuse the shared mapEngineOption helper so the
+ // disabled/disabled_reason mapping stays in one place.
+ searchEngineOptions = data.engine_options.map(mapEngineOption);
+
+ // If the dropdown is currently open, push the new
+ // options through updateDropdownOptions so the user
+ // sees the change without a close + reopen cycle. If
+ // it's closed, the next open reads searchEngineOptions
+ // via the registered getOptions() closure — no extra
+ // work needed.
+ if (searchEngineInput && window.updateDropdownOptions) {
+ try {
+ window.updateDropdownOptions(
+ searchEngineInput,
+ searchEngineOptions
+ );
+ } catch (_e) {
+ // Defensive: never let the scope reapplier
+ // break the dropdown. The next open will pick
+ // up the updated searchEngineOptions either
+ // way.
+ }
+ }
+
+ // A scope change can re-disable the previously selected
+ // engine (e.g. a public primary now under
+ // private_only). Switch the visible selection to a
+ // pre-configured favorite (SearXNG, then "Search All
+ // Collections") so the form can't submit a hidden
+ // engine by default. UI-only — the saved search.tool
+ // is not changed.
+ reconcileSearchEngineSelection(searchEngineOptions);
+ })
+ .catch((err) => {
+ // AbortError is expected when a newer call supersedes
+ // this one — log it as debug, not as a failure.
+ if (err && err.name === 'AbortError') {
+ SafeLogger.log(
+ 'applyEgressScopeToEngines: superseded by newer request'
+ );
+ return;
+ }
+ // If this fetch was already superseded, ignore the
+ // failure too — the newer fetch will report (or not)
+ // for itself.
+ if (token !== applyEgressScopeSeq) return;
+ if (searchEngineInput && searchEngineInput.parentNode) {
+ searchEngineInput.parentNode.classList.remove('ldr-loading');
+ }
+ SafeLogger.log(
+ 'applyEgressScopeToEngines: fetch failed; keeping existing list',
+ err && err.message
+ );
+ });
+ }
+
+ // 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 format
+ function 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;
+ const disabledReason = isEgressDenied
+ ? egressToDisabledReason(egress.reason, engine)
+ : isAgentDisabled
+ ? agentEnabledToDisabledReason(engine)
+ : null;
+ return {
+ value: engine.value || engine.id || '',
+ label: engine.label || engine.name || engine.value || '',
+ type: engine.type || 'search',
+ is_favorite: engine.is_favorite || false,
+ group_label: engine.group_label,
+ 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,
+ egress,
+ disabled,
+ disabled_reason: disabledReason,
+ egress_reason: egress ? egress.reason : null,
+ };
+ }
+
+ // Map a backend ``egress: {allowed, reason}`` decision onto the
+ // ``disabled`` / ``disabled_reason`` contract the custom dropdown
+ // renders. Reason text mirrors the human language the backend's
+ // ``denial_guidance`` uses (PR #5126) so the dropdown's inline
+ // reason and the precheck's 400 message stay in sync.
+ function egressToDisabledReason(reason, engine) {
+ if (!reason) return null;
+ const display = (engine && (engine.display_name || engine.label)) ||
+ (engine && engine.value) || 'engine';
+ switch (reason) {
+ case 'scope_mismatch_private_only':
+ return `Blocked: not a local source under Private only`;
+ case 'scope_mismatch_public_only':
+ return `Blocked: local source under Public only`;
+ case 'strict_not_primary':
+ return `Blocked: only the primary search engine is allowed under Strict`;
+ case 'unclassified':
+ case 'engine_unknown':
+ return `Blocked: ${display} is not recognized by the egress policy`;
+ case 'engine_denied':
+ return `Blocked: ${display} is denied by the egress policy`;
+ default:
+ return `Blocked by egress policy (${reason})`;
+ }
+ }
+
+ // 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) {
+ return `Hidden from the LangGraph research agent's tool list (check “Available to the research agent” on the collection page to re-enable).`;
+ }
+
+ // 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 preferred
+ // default because it is the recommended general-purpose engine and
+ // it has the broadest coverage; "Search All Collections" (the
+ // library engine) is the local-only fallback so a run never starts
+ // with an empty selection.
+ const PREFERRED_DEFAULT_ENGINES = ['searxng', 'library'];
+
+ // Pick the preferred default from a list of mapped engine options.
+ // Returns the first option whose value matches a PREFERRED_DEFAULT
+ // entry AND is not disabled, or null if no preferred default is
+ // available. Order matters: SearXNG wins over the library engine
+ // when both are eligible.
+ function pickPreferredSearchEngine(options) {
+ if (!Array.isArray(options)) return null;
+ for (const value of PREFERRED_DEFAULT_ENGINES) {
+ const match = options.find(
+ (o) => o && o.value === value && !o.disabled
+ );
+ if (match) return match;
+ }
+ return null;
+ }
+
+ // Reconcile the current search-engine selection against the latest
+ // option list. Called after every options refresh (initial load,
+ // scope change, strategy change, refresh button) so the dropdown
+ // never carries a selection that the new options have hidden.
+ //
+ // Rules:
+ // 1. If the current selection is still in the new options AND
+ // not disabled, keep it (the user's last pick is preserved).
+ // 2. Otherwise, fall back to a pre-configured favorite:
+ // SearXNG first, then "Search All Collections" (library).
+ // 3. If neither is available, fall back to the first non-disabled
+ // option so the form is never submitted with a value the
+ // backend would refuse.
+ // 4. If nothing is selectable, clear the selection.
+ //
+ // This is a UI-only change — the user's saved search.tool in the
+ // settings DB is not touched, so a returning user still sees their
+ // saved primary on the next page load.
+ function reconcileSearchEngineSelection(options) {
+ const list = Array.isArray(options) ? options : searchEngineOptions;
+ if (!Array.isArray(list)) return;
+
+ const input = searchEngineInput || document.getElementById('search_engine');
+ const hidden = document.getElementById('search_engine_hidden');
+ const current = selectedSearchEngineValue || (hidden ? hidden.value : '') || (input ? input.getAttribute('data-initial-value') : '');
+ const currentOpt = current
+ ? list.find((o) => o && o.value === current)
+ : null;
+
+ if (currentOpt && !currentOpt.disabled) {
+ // The previously selected value is still visible/enabled;
+ // keep it (rule 1). Keep inputs in sync.
+ selectedSearchEngineValue = currentOpt.value;
+ if (input) input.value = currentOpt.label || currentOpt.value;
+ if (hidden) hidden.value = currentOpt.value;
+ return;
+ }
+
+ const preferred = pickPreferredSearchEngine(list);
+ const next = preferred || list.find((o) => o && !o.disabled) || null;
+
+ if (!next) {
+ // No selectable options at all — clear the selection so the
+ // form can't submit a hidden/disabled engine. The form
+ // submit precheck will surface the empty-engine error.
+ SafeLogger.log(
+ 'reconcileSearchEngineSelection: no selectable options; clearing selection'
+ );
+ selectedSearchEngineValue = '';
+ if (input) input.value = '';
+ if (hidden) hidden.value = '';
+ return;
+ }
+
+ const previous = current || '(unset)';
+ SafeLogger.log(
+ `reconcileSearchEngineSelection: ${previous} -> ${next.value} (preferred=${preferred ? 'yes' : 'fallback'})`
+ );
+ selectedSearchEngineValue = next.value;
+ if (input) input.value = next.label || next.value;
+ if (hidden) hidden.value = next.value;
+ }
+
// Load search engine options
function loadSearchEngineOptions(forceRefresh = false) {
return new Promise((resolve) => {
- // Check in-memory cache first if not forcing refresh (5-minute expiration)
- if (!forceRefresh) {
+ // Issue #5204: when the active egress scope is set, ask the
+ // endpoint to stamp a per-option egress decision onto each
+ // entry so the dropdown can disable the ones that would be
+ // refused at submit time. The unfiltered path (no scope
+ // set) is unchanged — existing callers (settings page,
+ // news-subscription form) keep using the same cached list.
+ const egressScope = getCurrentEgressScopeForDropdown();
+ const primary = getCurrentPrimaryForDropdown();
+ const egressFiltered = !!egressScope;
+
+ // Check in-memory cache first if not forcing refresh (5-minute expiration).
+ // The cache only ever holds the UNFILTERED list: a scope-tagged
+ // response is small and changes on every scope switch, so caching
+ // it would just give us stale data on the next toggle.
+ if (!egressFiltered && !forceRefresh) {
const cachedData = getCachedData(CACHE_KEYS.SEARCH_ENGINES);
if (cachedData) {
SafeLogger.log('Using cached search engine data');
@@ -2143,8 +2590,29 @@
SafeLogger.log('Fetching search engines from API...');
+ // Build the egress-aware URL. Kept in one place so every
+ // code path (initial load, refresh, scope-change reapplier)
+ // asks for the same shape and the cache slot above is
+ // consistent.
+ const apiURL = egressFiltered
+ ? buildEgressAwareEnginesURL(egressScope, primary)
+ : URLS.SETTINGS_API.AVAILABLE_SEARCH_ENGINES;
+
+ // Thread the shared sequence token + AbortController so rapid interactions
+ // don't race and a late load response cannot overwrite a newer scope-aware fetch.
+ const token = ++applyEgressScopeSeq;
+ if (applyEgressScopeController) {
+ try {
+ applyEgressScopeController.abort();
+ } catch (_e) {
+ // Defensive: abort() should never throw
+ }
+ }
+ const controller = new AbortController();
+ applyEgressScopeController = controller;
+
// Fetch from API
- fetch(URLS.SETTINGS_API.AVAILABLE_SEARCH_ENGINES)
+ fetch(apiURL, { signal: controller.signal })
.then(response => {
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
@@ -2152,6 +2620,10 @@
return response.json();
})
.then(data => {
+ if (token !== applyEgressScopeSeq) {
+ resolve(searchEngineOptions);
+ return;
+ }
// Remove loading class
if (searchEngineInput && searchEngineInput.parentNode) {
searchEngineInput.parentNode.classList.remove('ldr-loading');
@@ -2171,16 +2643,12 @@
// group_* fields drive the band headers/ordering; the
// base_group_* fields let a favorite toggle move an
// engine back to its category band without re-fetching.
- formattedEngines = data.engine_options.map(engine => ({
- value: engine.value || engine.id || '',
- label: engine.label || engine.name || engine.value || '',
- type: engine.type || 'search',
- is_favorite: engine.is_favorite || false,
- group_label: engine.group_label,
- group_order: engine.group_order,
- base_group_label: engine.base_group_label,
- base_group_order: engine.base_group_order
- }));
+ // When the endpoint was called with egress_scope=
+ // (issue #5204) each option also carries an
+ // ``egress: {allowed, reason}`` field; we surface
+ // that as the disabled / disabled_reason contract
+ // the custom dropdown already understands.
+ formattedEngines = data.engine_options.map(mapEngineOption);
}
// Also try adding engines from engines object if it exists
if (data && data.engines) {
@@ -2232,12 +2700,35 @@
// Update global searchEngineOptions
searchEngineOptions = formattedEngines;
+ // Reconcile the visible selection against the
+ // freshly loaded options. On the very first
+ // load ``selectedSearchEngineValue`` is still
+ // empty, so this picks a pre-configured
+ // favorite (SearXNG, then library) as the
+ // visible default; setInitialFormValues will
+ // then overwrite with the saved primary if
+ // it is still in the list. The precheck
+ // reconciliation runs again in
+ // applyEgressScopeToEngines for the
+ // egress-aware shape on the first user-driven
+ // scope change.
+ reconcileSearchEngineSelection(searchEngineOptions);
+
resolve(formattedEngines);
} else {
throw new Error('No valid search engines found in API response');
}
})
.catch(error => {
+ if (error && error.name === 'AbortError') {
+ SafeLogger.log('loadSearchEngineOptions: superseded by newer request');
+ resolve(searchEngineOptions);
+ return;
+ }
+ if (token !== applyEgressScopeSeq) {
+ resolve(searchEngineOptions);
+ return;
+ }
SafeLogger.error('Error loading search engines:', error.message || error);
// Remove loading class on error
@@ -2540,6 +3031,12 @@
select.dataset.savedValue = select.value;
select.disabled = data.editable === false;
applyPrivacyPanelScope(select.value);
+ // Issue #5204: the revert changed the form's effective
+ // scope without firing a change event, so re-mirror
+ // the search-engine dropdown's disabled set too.
+ if (typeof applyEgressScopeToEngines === 'function') {
+ applyEgressScopeToEngines();
+ }
})
.catch(error => {
SafeLogger.error("Unable to refresh effective egress scope:", error);
diff --git a/src/local_deep_research/web/templates/pages/collection_create.html b/src/local_deep_research/web/templates/pages/collection_create.html
index 18cbfb6ff7..cd812d52d8 100644
--- a/src/local_deep_research/web/templates/pages/collection_create.html
+++ b/src/local_deep_research/web/templates/pages/collection_create.html
@@ -67,7 +67,14 @@
Checked (default): the LangGraph research agent can search this
collection as one of its tools. Uncheck to keep the collection out
of the agent's tool list when you don't need it for agentic research.
- This is a usability switch only — it does not change privacy or egress.
+ <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.
</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.html
index cf85ed14cb..cfe0cdff87 100644
--- a/src/local_deep_research/web/templates/pages/collection_details.html
+++ b/src/local_deep_research/web/templates/pages/collection_details.html
@@ -70,8 +70,14 @@
<div class="ldr-form-help" id="collection-agent-enabled-help">
Checked (default): the LangGraph research agent can search this collection
as one of its tools. Uncheck to keep it out of the agent's tool list when
- it isn't needed for agentic research. Usability switch only — it does not
- change privacy or egress.
+ 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.
</div>
</div>
</div>
diff --git a/src/local_deep_research/web/templates/pages/news-subscription-form.html b/src/local_deep_research/web/templates/pages/news-subscription-form.html
index 1e3b5acafc..46e4261688 100644
--- a/src/local_deep_research/web/templates/pages/news-subscription-form.html
+++ b/src/local_deep_research/web/templates/pages/news-subscription-form.html
@@ -182,10 +182,10 @@
<script defer src="/static/js/components/custom_dropdown.js"></script>
<script>
// Global variables
-let currentProvider = '{{ subscription.model_provider if subscription else default_settings.model_provider }}';
-let defaultModel = '{{ subscription.model if subscription else default_settings.model }}';
-let defaultSearchEngine = '{{ subscription.search_engine if subscription else default_settings.search_engine }}';
-let defaultCustomEndpoint = '{{ subscription.custom_endpoint if subscription else default_settings.custom_endpoint }}';
+let currentProvider = {{ (subscription.model_provider if subscription else default_settings.model_provider) | tojson }};
+let defaultModel = {{ (subscription.model if subscription else default_settings.model) | tojson }};
+let defaultSearchEngine = {{ (subscription.search_engine if subscription else default_settings.search_engine) | tojson }};
+let defaultCustomEndpoint = {{ (subscription.custom_endpoint if subscription else default_settings.custom_endpoint) | tojson }};
let modelOptions = [];
let modelDropdownInstance = null;
let searchEngineOptions = [];
@@ -294,13 +294,67 @@ function initializeDropdowns() {
// Load search engines
async function loadSearchEngines() {
try {
- const response = await fetch('/settings/api/available-search-engines', {
+ // Issue #5204: ask the endpoint for the scope-aware variant
+ // of the engine list when the user has a saved egress scope.
+ // The news-subscription form has no per-form scope selector,
+ // so the filter follows the user's saved setting — picking an
+ // engine that conflicts with it is impossible by default, and
+ // the subscribe-time backend check stays as the second backstop.
+ const scope = {{ (default_settings.egress_scope or "adaptive") | tojson }};
+ const primary = {{ (subscription.search_engine if subscription else default_settings.search_engine) | tojson }};
+ const filterScope = (scope && scope !== 'unprotected') ? scope : null;
+ let url = '/settings/api/available-search-engines';
+ if (filterScope) {
+ const parts = [`egress_scope=${encodeURIComponent(filterScope)}`];
+ if (primary) parts.push(`primary=${encodeURIComponent(primary)}`);
+ url += '?' + parts.join('&');
+ }
+
+ const response = await fetch(url, {
credentials: 'same-origin'
});
const data = await response.json();
if (data.engine_options) {
- searchEngineOptions = data.engine_options;
+ // Map the egress annotation onto the disabled contract
+ // the custom dropdown already understands (same contract
+ // the research.js loader uses). Unprotected / no-scope
+ // responses have no egress field, so the option is left
+ // enabled.
+ searchEngineOptions = data.engine_options.map((engine) => {
+ const egress = engine.egress;
+ const isDenied = !!egress && egress.allowed === false;
+ const display = engine.display_name || engine.label || engine.value || 'engine';
+ let disabledReason = null;
+ if (isDenied && egress) {
+ switch (egress.reason) {
+ case 'scope_mismatch_private_only':
+ disabledReason = 'Blocked: not a local source under Private only';
+ break;
+ case 'scope_mismatch_public_only':
+ disabledReason = 'Blocked: local source under Public only';
+ break;
+ case 'strict_not_primary':
+ disabledReason = 'Blocked: only the primary search engine is allowed under Strict';
+ break;
+ case 'unclassified':
+ case 'engine_unknown':
+ disabledReason = `Blocked: ${display} is not recognized by the egress policy`;
+ break;
+ case 'engine_denied':
+ disabledReason = `Blocked: ${display} is denied by the egress policy`;
+ break;
+ default:
+ disabledReason = `Blocked by egress policy (${egress.reason})`;
+ break;
+ }
+ }
+ return {
+ ...engine,
+ disabled: isDenied,
+ disabled_reason: disabledReason,
+ };
+ });
// Update dropdown if it exists
if (window.updateDropdownOptions) {
diff --git a/tests/js/components/custom-dropdown.test.js b/tests/js/components/custom-dropdown.test.js
index 09af7859d3..b664199dc5 100644
--- a/tests/js/components/custom-dropdown.test.js
+++ b/tests/js/components/custom-dropdown.test.js
@@ -110,6 +110,67 @@ describe('setupCustomDropdown', () => {
dd.destroy();
});
+ it('invokes onSelect BEFORE dispatching the hidden input change event (issue #5204 follow-up)', () => {
+ // The order matters: any change listener that reclassifies
+ // the dropdown (research.js: applyEgressScopeToEngines) needs
+ // the in-memory selection to be authoritative when it runs,
+ // otherwise the re-fetch carries the previous primary and the
+ // newly selected engine is briefly marked unavailable.
+ //
+ // Use a mock onSelect that flips a sentinel flag the change
+ // listener can observe — the change listener must see the flag
+ // already set (proving onSelect ran first), not still false
+ // (which would mean the change event fired before onSelect).
+ let onSelectRan = false;
+ const trackingOnSelect = vi.fn((_value, _item) => {
+ onSelectRan = true;
+ });
+ let onSelectStateAtChange = null;
+ hiddenInput.addEventListener('change', () => {
+ onSelectStateAtChange = onSelectRan;
+ });
+
+ const dd = setupCustomDropdown(input, dropdownList, () => options, trackingOnSelect);
+
+ input.click();
+ const items = dropdownList.querySelectorAll('.ldr-custom-dropdown-item');
+ items[1].click(); // Click "Claude"
+
+ // 1. onSelect fired with the clicked value.
+ expect(trackingOnSelect).toHaveBeenCalledWith('claude', options[1]);
+ // 2. By the time the change event fires, onSelect has already
+ // run. The bug would dispatch the change event first; the
+ // change listener would observe onSelectStateAtChange=false.
+ expect(onSelectStateAtChange).toBe(true);
+ // 3. The hidden input reflects the new value.
+ expect(hiddenInput.value).toBe('claude');
+ dd.destroy();
+ });
+
+ it('Enter on a highlighted item invokes onSelect before dispatching the hidden input change event', () => {
+ let onSelectRan = false;
+ const trackingOnSelect = vi.fn((_value, _item) => {
+ onSelectRan = true;
+ });
+ let onSelectStateAtChange = null;
+ hiddenInput.addEventListener('change', () => {
+ onSelectStateAtChange = onSelectRan;
+ });
+
+ const dd = setupCustomDropdown(input, dropdownList, () => options, trackingOnSelect);
+
+ input.dispatchEvent(new Event('focus'));
+ // First ArrowDown highlights the first item.
+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown' }));
+ // Enter selects the highlighted item.
+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter' }));
+
+ expect(trackingOnSelect).toHaveBeenCalledWith('gpt4', options[0]);
+ expect(onSelectStateAtChange).toBe(true);
+ expect(hiddenInput.value).toBe('gpt4');
+ dd.destroy();
+ });
+
it('updates input value on selection', () => {
const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);
input.click();
@@ -337,4 +398,231 @@ describe('updateDropdownOptions', () => {
it('does nothing for null input', () => {
expect(() => updateDropdownOptions(null, [])).not.toThrow();
});
+
+ it('invokes onSelect BEFORE dispatching the hidden input change event when selecting after re-render', () => {
+ const input = document.createElement('input');
+ input.type = 'text';
+ input.id = 'update-test-input';
+
+ const hiddenInput = document.createElement('input');
+ hiddenInput.type = 'hidden';
+ hiddenInput.id = 'update-test-input_hidden';
+
+ const dropdownList = document.createElement('div');
+ dropdownList.id = 'update-test-list';
+
+ const wrapper = document.createElement('div');
+ wrapper.appendChild(input);
+ wrapper.appendChild(hiddenInput);
+ wrapper.appendChild(dropdownList);
+ document.body.appendChild(wrapper);
+
+ let onSelectRan = false;
+ const trackingOnSelect = vi.fn((_value, _item) => {
+ onSelectRan = true;
+ });
+ let onSelectStateAtChange = null;
+ hiddenInput.addEventListener('change', () => {
+ onSelectStateAtChange = onSelectRan;
+ });
+
+ const initialOptions = [
+ { value: 'gpt4', label: 'GPT-4' },
+ ];
+ const dd = setupCustomDropdown(input, dropdownList, () => initialOptions, trackingOnSelect);
+ input.click();
+
+ const newOptions = [
+ { value: 'gpt4', label: 'GPT-4' },
+ { value: 'claude', label: 'Claude' },
+ ];
+ updateDropdownOptions(input, newOptions);
+
+ const items = dropdownList.querySelectorAll('.ldr-custom-dropdown-item');
+ items[1].click(); // Click "Claude"
+
+ expect(trackingOnSelect).toHaveBeenCalledWith('claude', newOptions[1]);
+ expect(onSelectStateAtChange).toBe(true);
+ expect(hiddenInput.value).toBe('claude');
+ dd.destroy();
+
+ wrapper.remove();
+ if (document.getElementById('update-test-list')) {
+ document.getElementById('update-test-list').remove();
+ }
+ });
+});
+
+describe('disabled options (issue #5204)', () => {
+ // The custom dropdown is reused by the scope-aware search engine
+ // picker. Disabled entries must render with the right visual +
+ // semantic contract so screen readers and keyboard users get the
+ // same affordance as a native <option disabled>.
+ let input, hiddenInput, dropdownList, onSelect;
+
+ beforeEach(() => {
+ input = document.createElement('input');
+ input.type = 'text';
+ input.id = 'test-disabled-input';
+ hiddenInput = document.createElement('input');
+ hiddenInput.type = 'hidden';
+ hiddenInput.id = 'test-disabled-input_hidden';
+ dropdownList = document.createElement('div');
+ dropdownList.id = 'test-disabled-list';
+ const wrapper = document.createElement('div');
+ wrapper.appendChild(input);
+ wrapper.appendChild(hiddenInput);
+ wrapper.appendChild(dropdownList);
+ document.body.appendChild(wrapper);
+ onSelect = vi.fn();
+ });
+
+ afterEach(() => {
+ const wrapper = input.closest('div');
+ if (wrapper && wrapper.parentNode) wrapper.remove();
+ const detached = document.getElementById('test-disabled-list');
+ if (detached) detached.remove();
+ });
+
+ function openList() {
+ // Drive the focus path the user takes.
+ input.dispatchEvent(new Event('focus'));
+ return Array.from(
+ dropdownList.querySelectorAll('.ldr-custom-dropdown-item')
+ );
+ }
+
+ it('renders disabled entries with aria-disabled, the disabled class, and a reason label', () => {
+ const options = [
+ { value: 'arxiv', label: 'ArXiv' },
+ {
+ value: 'library',
+ label: 'Library',
+ disabled: true,
+ disabled_reason: 'Blocked: not a local source under Private only',
+ },
+ ];
+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);
+
+ const rendered = openList();
+ const lib = rendered.find((el) => el.getAttribute('data-value') === 'library');
+ expect(lib.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);
+ expect(lib.getAttribute('aria-disabled')).toBe('true');
+ const reason = lib.querySelector('.ldr-dropdown-item-disabled-reason');
+ expect(reason).not.toBeNull();
+ expect(reason.textContent).toMatch(/not a local source under Private only/);
+ // The reason is also exposed to assistive tech via
+ // aria-describedby pointing at the reason span's id.
+ const describedById = lib.getAttribute('aria-describedby');
+ expect(describedById).toBe(reason.id);
+ dd.destroy();
+ });
+
+ it('does not call onSelect when a disabled entry is clicked', () => {
+ const options = [
+ {
+ value: 'library',
+ label: 'Library',
+ disabled: true,
+ disabled_reason: 'Blocked: local source under Public only',
+ },
+ ];
+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);
+
+ const rendered = openList();
+ const lib = rendered[0];
+ lib.click();
+
+ expect(onSelect).not.toHaveBeenCalled();
+ // Hidden input stays empty — no value was selected.
+ expect(hiddenInput.value).toBe('');
+ dd.destroy();
+ });
+
+ it('skips disabled entries in arrow-key navigation', () => {
+ const options = [
+ { value: 'a', label: 'A' },
+ { value: 'b', label: 'B', disabled: true, disabled_reason: 'blocked' },
+ { value: 'c', label: 'C' },
+ ];
+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);
+
+ // Open + focus first entry.
+ input.dispatchEvent(new Event('focus'));
+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown' }));
+ // The first ArrowDown lands on the first ENABLED entry
+ // (A), NOT on the disabled B.
+ let active = dropdownList.querySelector('.ldr-custom-dropdown-item.active');
+ expect(active).not.toBeNull();
+ expect(active.getAttribute('data-value')).toBe('a');
+
+ // Next ArrowDown skips B and lands on C.
+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown' }));
+ active = dropdownList.querySelector('.ldr-custom-dropdown-item.active');
+ expect(active.getAttribute('data-value')).toBe('c');
+
+ // Next ArrowDown wraps back to A (still skips B).
+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown' }));
+ active = dropdownList.querySelector('.ldr-custom-dropdown-item.active');
+ expect(active.getAttribute('data-value')).toBe('a');
+
+ // ArrowUp from A (index 0) wraps to C (skipping disabled B).
+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowUp' }));
+ active = dropdownList.querySelector('.ldr-custom-dropdown-item.active');
+ expect(active.getAttribute('data-value')).toBe('c');
+
+ dd.destroy();
+ });
+
+ it('Enter on a highlighted disabled entry is a no-op', () => {
+ // Direct: the only option is disabled. After the open, Enter
+ // would otherwise auto-select the first item; the disabled
+ // gate must short-circuit it.
+ const options = [
+ { value: 'b', label: 'B', disabled: true, disabled_reason: 'blocked' },
+ ];
+ const dd = setupCustomDropdown(input, dropdownList, () => options, onSelect);
+
+ input.dispatchEvent(new Event('focus'));
+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter' }));
+
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(hiddenInput.value).toBe('');
+ dd.destroy();
+ });
+
+ it('updateDropdownOptions also respects the disabled contract', () => {
+ // The research.js reapplier calls updateDropdownOptions (not
+ // setupCustomDropdown) when re-stamping the egress-aware list,
+ // so this path is just as important.
+ const dd = setupCustomDropdown(
+ input,
+ dropdownList,
+ () => [],
+ onSelect
+ );
+ // Open so the in-place re-render kicks in.
+ input.dispatchEvent(new Event('focus'));
+
+ const newOptions = [
+ {
+ value: 'arxiv',
+ label: 'ArXiv',
+ disabled: true,
+ disabled_reason: 'Blocked: not a local source under Private only',
+ },
+ { value: 'library', label: 'Library' },
+ ];
+ updateDropdownOptions(input, newOptions);
+
+ const rendered = Array.from(
+ dropdownList.querySelectorAll('.ldr-custom-dropdown-item')
+ );
+ const arxiv = rendered.find((el) => el.getAttribute('data-value') === 'arxiv');
+ expect(arxiv.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);
+ expect(arxiv.getAttribute('aria-disabled')).toBe('true');
+ const reason = arxiv.querySelector('.ldr-dropdown-item-disabled-reason');
+ expect(reason.textContent).toMatch(/not a local source under Private only/);
+ dd.destroy();
+ });
});
diff --git a/tests/js/components/research.test.js b/tests/js/components/research.test.js
index 909194d239..59c4660867 100644
--- a/tests/js/components/research.test.js
+++ b/tests/js/components/research.test.js
@@ -68,7 +68,7 @@ function buildForm() {
<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></select>
+ <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">
@@ -651,20 +651,44 @@ describe("research form — egress lock truthfulness", () => {
it("refreshes rejected scope changes from effective server metadata", async () => {
const scope = document.getElementById("policy_egress_scope");
- fetchMock
- .mockImplementationOnce(() => Promise.resolve({
- ok: false,
- status: 400,
- json: () => Promise.resolve({ error: "operator rejected" }),
- }))
- .mockImplementationOnce(() => Promise.resolve({
+ // Route mocks by URL + method rather than call order: a scope
+ // change also fires the issue-#5204 search-engine re-fetch, so
+ // call-ordered mockImplementationOnce entries would be consumed
+ // by the wrong request. Everything that isn't the scope-setting
+ // endpoint gets the same harmless stub as the beforeAll base
+ // (no engine_options key, non-success status → no navigation).
+ fetchMock.mockImplementation((url, options) => {
+ if (url === "/settings/api/policy.egress_scope") {
+ if (options?.method === "PUT") {
+ return Promise.resolve({
+ ok: false,
+ status: 400,
+ json: () => Promise.resolve({ error: "operator rejected" }),
+ });
+ }
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({
+ value: "adaptive",
+ editable: true,
+ }),
+ });
+ }
+ return Promise.resolve({
ok: true,
status: 200,
json: () => Promise.resolve({
- value: "adaptive",
- editable: true,
+ status: "error",
+ message: "stubbed — no navigation",
+ providers: {},
+ provider_options: [],
+ models: [],
+ engines: [],
}),
- }));
+ text: () => Promise.resolve(""),
+ });
+ });
scope.value = "private_only";
scope.dispatchEvent(new Event("change"));
@@ -686,11 +710,38 @@ describe("research form — egress lock truthfulness", () => {
status: 200,
json: () => Promise.resolve({}),
});
- fetchMock
- .mockImplementationOnce(() => new Promise(resolve => {
- resolveFirst = resolve;
- }))
- .mockImplementationOnce(() => Promise.resolve(successfulResponse()));
+ // Route by URL + method (see the previous test): only PUTs to
+ // the scope-setting endpoint participate in the serialization
+ // under test; the issue-#5204 engines re-fetch and any other
+ // traffic resolve immediately with the base stub.
+ let scopePutCount = 0;
+ fetchMock.mockImplementation((url, options) => {
+ if (
+ url === "/settings/api/policy.egress_scope" &&
+ options?.method === "PUT"
+ ) {
+ scopePutCount += 1;
+ if (scopePutCount === 1) {
+ return new Promise(resolve => {
+ resolveFirst = resolve;
+ });
+ }
+ return Promise.resolve(successfulResponse());
+ }
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({
+ status: "error",
+ message: "stubbed — no navigation",
+ providers: {},
+ provider_options: [],
+ models: [],
+ engines: [],
+ }),
+ text: () => Promise.resolve(""),
+ });
+ });
scope.value = "private_only";
scope.dispatchEvent(new Event("change"));
@@ -1192,3 +1243,928 @@ describe('research form — egress-scope change preserves unrelated field errors
expect(document.getElementById('research-error-alert').style.display).toBe('none');
});
});
+
+describe('research form — scope-aware search engine dropdown (issue #5204)', () => {
+ // The Search Engine dropdown must re-evaluate which options are
+ // selectable whenever the active Egress Scope or the saved
+ // primary changes. Disabled entries get aria-disabled="true" and
+ // a one-line reason label; the user's current selection is
+ // preserved (the precheck is the second backstop if it becomes
+ // disabled). The backend precheck + the PR #5126 inline-error
+ // path are unchanged — this is the UX layer.
+
+ const ENGINES_URL = '/settings/api/available-search-engines';
+ const FULL_OPTIONS = [
+ { 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: 'github', label: 'GitHub', category: 'Code', requires_api_key: false, is_favorite: false,
+ group: 'code', group_label: 'Code', group_order: 5,
+ base_group: 'code', base_group_label: 'Code', base_group_order: 5 },
+ { value: 'library', label: 'Library', 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 },
+ { 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 },
+ ];
+
+ function stubEngines(url) {
+ // The handler can match either an unfiltered request (no
+ // query params) or an egress-aware one (?egress_scope=&primary=).
+ // The URL produced by the app may be relative or fully
+ // qualified depending on the env (happy-dom returns
+ // ``http://localhost:3000/...`` because window.location.origin
+ // is set); match both.
+ const isEnginesUrl = (u) =>
+ !!u &&
+ (u === ENGINES_URL ||
+ u.startsWith(ENGINES_URL + '?') ||
+ u.includes(ENGINES_URL + '?') ||
+ u.endsWith(ENGINES_URL));
+ if (!isEnginesUrl(url)) return null;
+ // Detect the egress-scope query string so the test can drive
+ // the backend contract end-to-end.
+ const qIdx = (url || '').indexOf('?');
+ const qs = qIdx >= 0 ? (url || '').slice(qIdx + 1) : '';
+ const hasEgress = qs.includes('egress_scope=');
+ let body = { engine_options: FULL_OPTIONS, engines: {}, favorites: [] };
+ if (hasEgress) {
+ const params = new URLSearchParams(qs);
+ const scope = params.get('egress_scope') || '';
+ const primary = params.get('primary') || '';
+ body = {
+ engine_options: FULL_OPTIONS.map((opt) => decorateForScope(opt, scope, primary)),
+ engines: {},
+ favorites: [],
+ };
+ }
+ return {
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(body),
+ text: () => Promise.resolve(''),
+ };
+ }
+
+ function flush() {
+ return new Promise((r) => setTimeout(r, 0));
+ }
+
+ function getEnginesCalls() {
+ // The URL is fully qualified in happy-dom
+ // (http://localhost:3000/settings/api/...); match the path
+ // suffix so both the relative form and the absolute form
+ // produced by the URL builder count.
+ return fetchMock.mock.calls.filter(([u]) => {
+ if (!u) return false;
+ return (
+ u === ENGINES_URL ||
+ u.startsWith(ENGINES_URL + '?') ||
+ u.endsWith(ENGINES_URL) ||
+ u.includes(ENGINES_URL + '?')
+ );
+ });
+ }
+
+ function openDropdownAndReadOptions() {
+ // Drive the custom dropdown's open path: focus the input,
+ // then read the rendered option list. Mirrors how a real user
+ // would open the dropdown.
+ 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'));
+ }
+
+ function decorateForScope(opt, scope, primary) {
+ if (scope === 'private_only') {
+ if (opt.value === 'library' || opt.category === 'Local RAG') {
+ return { ...opt, egress: { allowed: true, reason: 'allowed' } };
+ }
+ return { ...opt, egress: { allowed: false, reason: 'scope_mismatch_private_only' } };
+ }
+ if (scope === 'public_only') {
+ if (opt.category === 'Local RAG') {
+ return { ...opt, egress: { allowed: false, reason: 'scope_mismatch_public_only' } };
+ }
+ return { ...opt, egress: { allowed: true, reason: 'allowed' } };
+ }
+ if (scope === 'strict') {
+ if (primary && opt.value === primary) {
+ return { ...opt, egress: { allowed: true, reason: 'primary_carve_out' } };
+ }
+ return { ...opt, egress: { allowed: false, reason: 'strict_not_primary' } };
+ }
+ // adaptive / unknown / no-scope => no egress annotation
+ return { ...opt };
+ }
+
+ beforeEach(() => {
+ // Reset the egress scope + search engine back to defaults so
+ // each test starts from a known state. The base beforeEach
+ // already clears the form, so we just touch the two fields.
+ const scope = document.getElementById('policy_egress_scope');
+ scope.value = 'adaptive';
+ const hidden = document.getElementById('search_engine_hidden');
+ hidden.value = 'arxiv';
+ const input = document.getElementById('search_engine');
+ input.value = '';
+ fetchMock.mockClear();
+ });
+
+ it('initial load includes the egress_scope query param when a scope is set', async () => {
+ document.getElementById('policy_egress_scope').value = 'private_only';
+ fetchMock.mockImplementation((url) => Promise.resolve(stubEngines(url) || {
+ ok: true, status: 200,
+ json: () => Promise.resolve({ engines: [], engine_options: [] }),
+ text: () => Promise.resolve(''),
+ }));
+
+ // Dispatch the scope change so the reapplier fires.
+ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));
+ await flush();
+ await flush();
+
+ const calls = getEnginesCalls();
+ expect(calls.length).toBeGreaterThan(0);
+ // The reapplier (or initial load, depending on test order)
+ // asked for the egress-aware shape.
+ const hasEgressCall = calls.some(([u]) => u.includes('egress_scope=private_only'));
+ expect(hasEgressCall).toBe(true);
+ });
+
+ it('marks options disabled with aria-disabled and a one-line reason', async () => {
+ // Set the primary to library (a local engine) so a PUBLIC
+ // engine (arxiv/github) is the one that gets denied under
+ // private_only — otherwise the primary carve-out keeps the
+ // public primary allowed and there'd be nothing to disable.
+ document.getElementById('search_engine_hidden').value = 'library';
+ document.getElementById('policy_egress_scope').value = 'private_only';
+ fetchMock.mockImplementation((url) => Promise.resolve(stubEngines(url) || {
+ ok: true, status: 200,
+ json: () => Promise.resolve({ engines: [], engine_options: [] }),
+ text: () => Promise.resolve(''),
+ }));
+
+ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));
+ await flush();
+ await flush();
+
+ const rendered = openDropdownAndReadOptions();
+ // Every option the backend returned is rendered.
+ expect(rendered.length).toBe(FULL_OPTIONS.length);
+ // Arxiv (public) is denied under private_only; library (the
+ // local primary) is allowed by carve-out.
+ const arxiv = rendered.find((el) => el.getAttribute('data-value') === 'arxiv');
+ const library = rendered.find((el) => el.getAttribute('data-value') === 'library');
+ expect(arxiv).toBeDefined();
+ expect(arxiv.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);
+ expect(arxiv.getAttribute('aria-disabled')).toBe('true');
+ const reason = arxiv.querySelector('.ldr-dropdown-item-disabled-reason');
+ expect(reason).not.toBeNull();
+ expect(reason.textContent).toMatch(/not a local source under Private only/i);
+ // The local primary is allowed (carve-out) and not disabled.
+ expect(library.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);
+ expect(library.getAttribute('aria-disabled')).toBeNull();
+ });
+
+ it('re-applies when the user switches to a different scope', async () => {
+ fetchMock.mockImplementation((url) => Promise.resolve(stubEngines(url) || {
+ ok: true, status: 200,
+ json: () => Promise.resolve({ engines: [], engine_options: [] }),
+ text: () => Promise.resolve(''),
+ }));
+
+ // 1. Switch to public_only.
+ const scope = document.getElementById('policy_egress_scope');
+ scope.value = 'public_only';
+ scope.dispatchEvent(new Event('change'));
+ await flush();
+ await flush();
+
+ // The local library entry is now disabled (local source under
+ // public-only is denied).
+ let rendered = openDropdownAndReadOptions();
+ let lib = rendered.find((el) => el.getAttribute('data-value') === 'library');
+ expect(lib.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);
+
+ // 2. Switch to private_only.
+ scope.value = 'private_only';
+ scope.dispatchEvent(new Event('change'));
+ await flush();
+ await flush();
+
+ // The local library entry is now allowed.
+ rendered = openDropdownAndReadOptions();
+ lib = rendered.find((el) => el.getAttribute('data-value') === 'library');
+ expect(lib.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);
+ });
+
+ it('disables primary if it violates the active egress scope', async () => {
+ // The user's saved search.tool (arxiv) is the primary.
+ document.getElementById('search_engine_hidden').value = 'arxiv';
+ document.getElementById('policy_egress_scope').value = 'private_only';
+ fetchMock.mockImplementation((url) => Promise.resolve(stubEngines(url) || {
+ ok: true, status: 200,
+ json: () => Promise.resolve({ engines: [], engine_options: [] }),
+ text: () => Promise.resolve(''),
+ }));
+
+ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));
+ await flush();
+ await flush();
+
+ const rendered = openDropdownAndReadOptions();
+ const arxiv = rendered.find((el) => el.getAttribute('data-value') === 'arxiv');
+ // arxiv is a public engine so under private_only it must be disabled
+ expect(arxiv.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);
+ });
+
+ it('does not request egress filtering under "Adaptive" scope so all primary options remain selectable', async () => {
+ document.getElementById('policy_egress_scope').value = 'adaptive';
+ fetchMock.mockImplementation((url) => Promise.resolve(stubEngines(url) || {
+ ok: true, status: 200,
+ json: () => Promise.resolve({ engines: [], engine_options: [] }),
+ text: () => Promise.resolve(''),
+ }));
+
+ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));
+ await flush();
+ await flush();
+
+ const calls = getEnginesCalls();
+ // Under Adaptive, options are unfiltered (no ?egress_scope=) so user can pick any primary
+ const hasEgressCall = calls.some(([u]) => u.includes('egress_scope='));
+ expect(hasEgressCall).toBe(false);
+ });
+
+ it('does not request egress filtering under "Primary only" (strict) scope', async () => {
+ document.getElementById('policy_egress_scope').value = 'strict';
+ fetchMock.mockImplementation((url) => Promise.resolve(stubEngines(url) || {
+ ok: true, status: 200,
+ json: () => Promise.resolve({ engines: [], engine_options: [] }),
+ text: () => Promise.resolve(''),
+ }));
+
+ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));
+ await flush();
+ await flush();
+
+ const calls = getEnginesCalls();
+ // Under strict scope, options are unfiltered so user can choose any single engine as primary
+ const hasEgressCall = calls.some(([u]) => u.includes('egress_scope='));
+ expect(hasEgressCall).toBe(false);
+ });
+
+ it('does not request egress filtering under "Unprotected" (escape hatch)', async () => {
+ document.getElementById('policy_egress_scope').value = 'unprotected';
+ fetchMock.mockImplementation((url) => Promise.resolve(stubEngines(url) || {
+ ok: true, status: 200,
+ json: () => Promise.resolve({ engines: [], engine_options: [] }),
+ text: () => Promise.resolve(''),
+ }));
+
+ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));
+ await flush();
+ await flush();
+
+ const calls = getEnginesCalls();
+ const hasEgressCall = calls.some(([u]) => u.includes('egress_scope='));
+ expect(hasEgressCall).toBe(false);
+ });
+
+ it('switches the visible selection to a pre-configured favorite when the current engine becomes hidden', async () => {
+ // The user picked github (public, allowed under public_only).
+ // They then switch to private_only. github becomes disabled.
+ // The reconcile step should switch the visible selection to
+ // the next pre-configured favorite — SearXNG first, then
+ // library ("Search All Collections") — so the form is never
+ // submitted with a hidden value by default.
+ document.getElementById('search_engine_hidden').value = 'github';
+ fetchMock.mockImplementation((url) => Promise.resolve(stubEngines(url) || {
+ ok: true, status: 200,
+ json: () => Promise.resolve({ engine_options: [], engines: [] }),
+ text: () => Promise.resolve(''),
+ }));
+
+ const scope = document.getElementById('policy_egress_scope');
+ scope.value = 'private_only';
+ scope.dispatchEvent(new Event('change'));
+ await flush();
+ await flush();
+
+ // github was hidden under private_only — the reconcile should
+ // have moved the selection to the library fallback.
+ expect(document.getElementById('search_engine_hidden').value).toBe('library');
+ const input = document.getElementById('search_engine');
+ expect(input.value).toBe('Library');
+ });
+
+ it('reconciles selection from library to a public engine when switching to public_only', async () => {
+ document.getElementById('search_engine_hidden').value = 'library';
+ document.getElementById('search_engine').value = 'Library';
+ fetchMock.mockImplementation((url) => Promise.resolve(stubEngines(url) || {
+ ok: true, status: 200,
+ json: () => Promise.resolve({ engines: [], engine_options: [] }),
+ text: () => Promise.resolve(''),
+ }));
+
+ const scope = document.getElementById('policy_egress_scope');
+ scope.value = 'public_only';
+ scope.dispatchEvent(new Event('change'));
+ await flush();
+ await flush();
+
+ // library is disabled under public_only, so selection reconciles to arxiv/searxng (allowed public engine)
+ expect(document.getElementById('search_engine_hidden').value).toBe('arxiv');
+ expect(document.getElementById('search_engine').value).toBe('ArXiv');
+ });
+
+ it('prefers SearXNG over library when picking the default', async () => {
+ // With both SearXNG and library in the option list under
+ // public_only, a hidden selection must reconcile to SearXNG
+ // (the preferred default).
+ const options = [
+ { 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: 'searxng', label: 'SearXNG', category: 'Web Search', requires_api_key: false, is_favorite: false,
+ group: 'web', group_label: 'Web Search', group_order: 2,
+ base_group: 'web', base_group_label: 'Web Search', base_group_order: 2 },
+ { value: 'library', label: 'Library', 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 },
+ ];
+ fetchMock.mockImplementation(() => Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({
+ engine_options: options.map((o) => (
+ o.value === 'searxng'
+ ? { ...o, egress: { allowed: true, reason: 'allowed' } }
+ : { ...o, egress: { allowed: false, reason: 'scope_mismatch_private_only' } }
+ )),
+ engines: {},
+ favorites: [],
+ }),
+ text: () => Promise.resolve(''),
+ }));
+
+ document.getElementById('search_engine_hidden').value = 'arxiv';
+ const scope = document.getElementById('policy_egress_scope');
+ scope.value = 'private_only';
+ scope.dispatchEvent(new Event('change'));
+ await flush();
+ await flush();
+
+ // arxiv is hidden; reconcile must prefer SearXNG over library.
+ expect(document.getElementById('search_engine_hidden').value).toBe('searxng');
+ expect(document.getElementById('search_engine').value).toBe('SearXNG');
+ });
+
+ it('keeps the user\'s current selection when it is still visible after an update', async () => {
+ // When the current selection survives the options refresh (still allowed),
+ // the reconcile must NOT touch it.
+ document.getElementById('search_engine_hidden').value = 'library';
+ document.getElementById('search_engine').value = 'Library';
+ fetchMock.mockImplementation((url) => Promise.resolve(stubEngines(url) || {
+ ok: true, status: 200,
+ json: () => Promise.resolve({ engines: [], engine_options: [] }),
+ text: () => Promise.resolve(''),
+ }));
+
+ const scope = document.getElementById('policy_egress_scope');
+ scope.value = 'adaptive';
+ scope.dispatchEvent(new Event('change'));
+ await flush();
+ await flush();
+
+ // library is allowed under adaptive scope so it must stay selected
+ expect(document.getElementById('search_engine_hidden').value).toBe('library');
+ });
+
+ it('re-applies when the user picks a different primary (saved engine changes)', async () => {
+ fetchMock.mockImplementation((url) => Promise.resolve(stubEngines(url) || {
+ ok: true, status: 200,
+ json: () => Promise.resolve({ engines: [], engine_options: [] }),
+ text: () => Promise.resolve(''),
+ }));
+
+ document.getElementById('policy_egress_scope').value = 'private_only';
+ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));
+ await flush();
+ await flush();
+
+ fetchMock.mockClear();
+
+ // Now change the saved primary: arxiv -> library. This must
+ // trigger a re-fetch with primary=library, which reshapes
+ // the carve-out and the disabled set.
+ const hidden = document.getElementById('search_engine_hidden');
+ hidden.value = 'library';
+ hidden.dispatchEvent(new Event('change'));
+ await flush();
+ await flush();
+
+ const calls = getEnginesCalls();
+ // The reapplier fired with the new primary in the URL.
+ const hasPrimary = calls.some(([u]) => u.includes('primary=library'));
+ expect(hasPrimary).toBe(true);
+ });
+
+ it('reclassifies using the just-clicked primary, not the previous one (issue #5204 follow-up)', async () => {
+ // Regression: the hidden input's change listener fires before
+ // the dropdown's onSelect callback (custom_dropdown.js), which
+ // means the re-fetch used to carry the STALE in-memory
+ // primary. The newly selected engine could then briefly be
+ // marked unavailable because the carve-out was still on the
+ // old primary.
+ //
+ // Drive the real click path — open the dropdown, click an
+ // option — and assert the fetch URL carries the NEW primary
+ // and the dropdown re-renders with the right disabled set.
+ fetchMock.mockImplementation((url) => Promise.resolve(stubEngines(url) || {
+ ok: true, status: 200,
+ json: () => Promise.resolve({ engines: [], engine_options: [] }),
+ text: () => Promise.resolve(''),
+ }));
+
+ // Saved primary = arxiv, scope = private_only.
+ document.getElementById('search_engine_hidden').value = 'arxiv';
+ document.getElementById('policy_egress_scope').value = 'private_only';
+ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));
+ await flush();
+ await flush();
+
+ // Under private_only, arxiv (public) is disabled.
+ let rendered = openDropdownAndReadOptions();
+ let arxiv = rendered.find((el) => el.getAttribute('data-value') === 'arxiv');
+ expect(arxiv.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);
+
+ // User clicks library. library is a local engine, so it is
+ // selectable under private_only.
+ fetchMock.mockClear();
+ const list = document.getElementById('search-engine-dropdown-list');
+ const libraryItem = Array.from(list.querySelectorAll('.ldr-custom-dropdown-item'))
+ .find((el) => el.getAttribute('data-value') === 'library');
+ expect(libraryItem).toBeDefined();
+ libraryItem.click();
+ await flush();
+ await flush();
+
+ // The re-fetch must carry the NEWLY-CLICKED primary (library),
+ // not the previous one (arxiv). The bug would emit primary=arxiv.
+ const calls = getEnginesCalls();
+ expect(calls.length).toBeGreaterThan(0);
+ const postClickCall = calls.find(([u]) => u.includes('primary='));
+ expect(postClickCall).toBeDefined();
+ expect(postClickCall[0]).toContain('primary=library');
+ expect(postClickCall[0]).not.toContain('primary=arxiv');
+
+ // The hidden input reflects the new selection.
+ expect(document.getElementById('search_engine_hidden').value).toBe('library');
+
+ // The dropdown has re-rendered with the new disabled set:
+ // arxiv loses its primary carve-out and is now denied under
+ // private_only (because the re-fetch used primary=library).
+ rendered = openDropdownAndReadOptions();
+ arxiv = rendered.find((el) => el.getAttribute('data-value') === 'arxiv');
+ expect(arxiv.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);
+ const library = rendered.find((el) => el.getAttribute('data-value') === 'library');
+ expect(library.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);
+ });
+
+ it('ignores a superseded (older) response when a newer fetch is in flight (issue #5204 follow-up)', async () => {
+ // Regression for the rapid scope/primary-change race: every
+ // scope/primary change fires a new fetch, and without
+ // cancellation the last response to arrive wins. If the older
+ // fetch completes last, the dropdown ends up showing
+ // classifications for a scope/primary that is no longer
+ // selected. The reapplier must abort the older request (or
+ // drop its response via a generation token).
+ const scopeSelect = document.getElementById('policy_egress_scope');
+ const hidden = document.getElementById('search_engine_hidden');
+ hidden.value = 'arxiv';
+
+ // Build a controllable fetch: each call returns a Promise we
+ // can resolve manually. The first response is for the OLD
+ // scope (private_only); the second is for the NEW scope
+ // (public_only). We resolve the second first, then the first,
+ // and assert the dropdown reflects the NEW scope, not the old.
+ // Only the engines endpoint is captured — other endpoints
+ // (settings save, etc.) are stubbed but ignored.
+ const responders = [];
+ const isEnginesUrl = (u) =>
+ typeof u === 'string' && (
+ u === ENGINES_URL ||
+ u.startsWith(ENGINES_URL + '?') ||
+ u.endsWith(ENGINES_URL) ||
+ u.includes(ENGINES_URL + '?')
+ );
+ fetchMock.mockImplementation((url, _opts) => {
+ // Pass through non-engine endpoints immediately.
+ if (!isEnginesUrl(url)) {
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({}),
+ text: () => Promise.resolve(''),
+ });
+ }
+ const qIdx = (url || '').indexOf('?');
+ const qs = qIdx >= 0 ? (url || '').slice(qIdx + 1) : '';
+ const params = new URLSearchParams(qs);
+ const scope = params.get('egress_scope') || '';
+ const body = {
+ engine_options: FULL_OPTIONS.map((opt) => decorateForScope(opt, scope, params.get('primary') || '')),
+ engines: {},
+ favorites: [],
+ };
+ let resolveFn;
+ const promise = new Promise((resolve) => {
+ resolveFn = resolve;
+ });
+ responders.push({ url, resolve: () => resolveFn({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(body),
+ text: () => Promise.resolve(''),
+ }) });
+ return promise;
+ });
+
+ // Fire the FIRST fetch (private_only).
+ scopeSelect.value = 'private_only';
+ scopeSelect.dispatchEvent(new Event('change'));
+ await flush();
+ expect(responders.length).toBe(1);
+
+ // Before the first fetch resolves, fire a SECOND fetch
+ // (public_only). This must cancel / supersede the first.
+ scopeSelect.value = 'public_only';
+ scopeSelect.dispatchEvent(new Event('change'));
+ await flush();
+ expect(responders.length).toBe(2);
+
+ // Resolve the SECOND (newer) request first.
+ responders[1].resolve();
+ await flush();
+ await flush();
+
+ // Then resolve the FIRST (older, now superseded) request.
+ responders[0].resolve();
+ await flush();
+ await flush();
+
+ // The dropdown must reflect the NEW scope (public_only), not the OLD
+// one (private_only). github is allowed under public_only but denied
+// under private_only (public source under private), so the disabled
+// state of github is the visible signal. With primary=library, the
+// library entry is the carve-out under both scopes, so we deliberately
+// check github instead.
+ const rendered = openDropdownAndReadOptions();
+ const github = rendered.find((el) => el.getAttribute('data-value') === 'github');
+ expect(github).toBeDefined();
+ expect(github.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);
+ });
+
+ it('settles outer Promise and retains wrapper loading state on aborted request until newest request settles', async () => {
+ const fetchPromises = [];
+
+ fetchMock.mockImplementation((url) => {
+ let resFn;
+ const p = new Promise((res) => {
+ resFn = res;
+ });
+ const urlStr = typeof url === 'string' ? url : (url && url.toString ? url.toString() : '');
+ if (urlStr.includes('available-search-engines')) {
+ fetchPromises.push({ resolve: resFn });
+ }
+ return p;
+ });
+
+ const searchEngineInput = document.getElementById('search_engine');
+
+ // Trigger refresh button click (starts first load)
+ const refreshBtn = document.getElementById('search_engine-refresh');
+ refreshBtn.click();
+ await flush();
+
+ expect(refreshBtn.classList.contains('ldr-loading')).toBe(true);
+ expect(searchEngineInput.parentNode.classList.contains('ldr-loading')).toBe(true);
+ expect(fetchPromises.length).toBe(1);
+
+ // Before first fetch completes, fire a scope change (starts second load, aborting/superseding the first)
+ const scopeSelect = document.getElementById('policy_egress_scope');
+ scopeSelect.value = 'private_only';
+ scopeSelect.dispatchEvent(new Event('change'));
+ await flush();
+
+ expect(fetchPromises.length).toBe(2);
+ expect(searchEngineInput.parentNode.classList.contains('ldr-loading')).toBe(true);
+
+ // Simulate AbortError on the first request
+ const abortErr = new Error('The user aborted a request.');
+ abortErr.name = 'AbortError';
+ fetchPromises[0].resolve(Promise.reject(abortErr));
+ await flush();
+ await flush();
+
+ // The refresh button loading indicator must be cleared (proving the superseded Promise settled),
+ // but the dropdown wrapper must STILL be loading because the second request is in flight.
+ expect(refreshBtn.classList.contains('ldr-loading')).toBe(false);
+ expect(searchEngineInput.parentNode.classList.contains('ldr-loading')).toBe(true);
+
+ // Now resolve second request (newest request)
+ fetchPromises[1].resolve({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ engine_options: FULL_OPTIONS, engines: {}, favorites: [] }),
+ text: () => Promise.resolve(''),
+ });
+ await flush();
+ await flush();
+
+ // Settlement of the newest request clears the wrapper loading indicator
+ expect(searchEngineInput.parentNode.classList.contains('ldr-loading')).toBe(false);
+ });
+
+ it('retains wrapper loading state on non-aborting stale response until newest request settles', async () => {
+ const fetchPromises = [];
+
+ fetchMock.mockImplementation((url) => {
+ let resFn;
+ const p = new Promise((res) => {
+ resFn = res;
+ });
+ const urlStr = typeof url === 'string' ? url : (url && url.toString ? url.toString() : '');
+ if (urlStr.includes('available-search-engines')) {
+ fetchPromises.push({ resolve: resFn });
+ }
+ return p;
+ });
+
+ const searchEngineInput = document.getElementById('search_engine');
+
+ // Trigger refresh button click (starts first load)
+ const refreshBtn = document.getElementById('search_engine-refresh');
+ refreshBtn.click();
+ await flush();
+
+ expect(searchEngineInput.parentNode.classList.contains('ldr-loading')).toBe(true);
+ expect(fetchPromises.length).toBe(1);
+
+ // Before first fetch completes, fire a scope change (starts second load)
+ const scopeSelect = document.getElementById('policy_egress_scope');
+ scopeSelect.value = 'private_only';
+ scopeSelect.dispatchEvent(new Event('change'));
+ await flush();
+
+ expect(fetchPromises.length).toBe(2);
+ expect(searchEngineInput.parentNode.classList.contains('ldr-loading')).toBe(true);
+
+ // Resolve the FIRST (stale generation, non-aborting) response
+ fetchPromises[0].resolve({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ engine_options: FULL_OPTIONS, engines: {}, favorites: [] }),
+ text: () => Promise.resolve(''),
+ });
+ await flush();
+ await flush();
+
+ // Older request settling must NOT clear the newer request's wrapper loading indicator
+ expect(searchEngineInput.parentNode.classList.contains('ldr-loading')).toBe(true);
+
+ // Resolve the SECOND (newest) request
+ fetchPromises[1].resolve({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ engine_options: FULL_OPTIONS, engines: {}, favorites: [] }),
+ text: () => Promise.resolve(''),
+ });
+ await flush();
+ await flush();
+
+ // Settlement of the newest request clears the wrapper loading indicator
+ expect(searchEngineInput.parentNode.classList.contains('ldr-loading')).toBe(false);
+ });
+});
+
+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.
+
+ const ENGINES_URL = '/settings/api/available-search-engines';
+
+ 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' } },
+ ];
+
+ 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 setStrategy(value) {
+ const sel = document.getElementById('strategy');
+ sel.value = value;
+ sel.dispatchEvent(new Event('change'));
+ }
+
+ 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'));
+ await flush();
+ await flush();
+
+ const disabled = getOption('collection_disabled');
+ 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'));
+ await flush();
+ await flush();
+
+ const disabled = getOption('collection_disabled');
+ expect(disabled.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);
+ expect(disabled.getAttribute('aria-disabled')).toBeNull();
+ });
+
+ 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'));
+ await flush();
+ await flush();
+ let coll = getOption('collection_disabled');
+ expect(coll.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);
+
+ // 2. Switch to LangGraph. No server re-fetch needed — the
+ // strategy reapplier re-maps the existing options in memory.
+ setStrategy('langgraph-agent');
+ await flush();
+
+ coll = getOption('collection_disabled');
+ 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'));
+ await flush();
+ await flush();
+ let coll = getOption('collection_disabled');
+ expect(coll.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);
+
+ // 2. Switch back to source-based.
+ setStrategy('source-based');
+ await flush();
+
+ coll = getOption('collection_disabled');
+ 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 flush();
+ await flush();
+
+ const arxiv = getOption('arxiv');
+ expect(arxiv.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);
+ });
+
+ 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');
+ await flush();
+ 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('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('egress-disabled engine remains disabled across strategy switches', async () => {
+ 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);
+ });
+});
diff --git a/tests/js/pages/news-subscription-form.test.js b/tests/js/pages/news-subscription-form.test.js
new file mode 100644
index 0000000000..93982191b2
--- /dev/null
+++ b/tests/js/pages/news-subscription-form.test.js
@@ -0,0 +1,145 @@
+/**
+ * Tests for news subscription form egress-scope search engine filtering.
+ *
+ * Exercises the loadSearchEngines URL construction and egress policy mapping logic
+ * used by news-subscription-form.html (Issue #5204).
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+describe('news-subscription-form egress search engine loading', () => {
+ let originalFetch;
+
+ beforeEach(() => {
+ originalFetch = globalThis.fetch;
+ document.body.innerHTML = `
+ <input type="hidden" id="subscription-search-engine" value="searxng" />
+ `;
+ });
+
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ document.body.innerHTML = '';
+ });
+
+ async function runLoadSearchEngines(scope, primary, engineOptionsResponse) {
+ let requestedUrl = null;
+ globalThis.fetch = vi.fn((url) => {
+ requestedUrl = url;
+ return Promise.resolve({
+ ok: true,
+ json: () => Promise.resolve({ engine_options: engineOptionsResponse }),
+ });
+ });
+
+ let searchEngineOptions = [];
+ const windowUpdateOptions = vi.fn();
+ window.updateDropdownOptions = windowUpdateOptions;
+
+ // Function logic matching news-subscription-form.html loadSearchEngines()
+ const filterScope = (scope && scope !== 'unprotected') ? scope : null;
+ let url = '/settings/api/available-search-engines';
+ if (filterScope) {
+ const parts = [`egress_scope=${encodeURIComponent(filterScope)}`];
+ if (primary) parts.push(`primary=${encodeURIComponent(primary)}`);
+ url += '?' + parts.join('&');
+ }
+
+ const response = await fetch(url, { credentials: 'same-origin' });
+ const data = await response.json();
+
+ if (data.engine_options) {
+ searchEngineOptions = data.engine_options.map((engine) => {
+ const egress = engine.egress;
+ const isDenied = !!egress && egress.allowed === false;
+ const display = engine.display_name || engine.label || engine.value || 'engine';
+ let disabledReason = null;
+ if (isDenied && egress) {
+ switch (egress.reason) {
+ case 'scope_mismatch_private_only':
+ disabledReason = 'Blocked: not a local source under Private only';
+ break;
+ case 'scope_mismatch_public_only':
+ disabledReason = 'Blocked: local source under Public only';
+ break;
+ case 'strict_not_primary':
+ disabledReason = 'Blocked: only the primary search engine is allowed under Strict';
+ break;
+ case 'unclassified':
+ case 'engine_unknown':
+ disabledReason = `Blocked: ${display} is not recognized by the egress policy`;
+ break;
+ case 'engine_denied':
+ disabledReason = `Blocked: ${display} is denied by the egress policy`;
+ break;
+ default:
+ disabledReason = `Blocked by egress policy (${egress.reason})`;
+ break;
+ }
+ }
+ return {
+ ...engine,
+ disabled: isDenied,
+ disabled_reason: disabledReason,
+ };
+ });
+
+ if (window.updateDropdownOptions) {
+ const searchEngineInput = document.getElementById('subscription-search-engine');
+ window.updateDropdownOptions(searchEngineInput, searchEngineOptions);
+ }
+ }
+
+ return { requestedUrl, searchEngineOptions, windowUpdateOptions };
+ }
+
+ it('builds egress_scope and primary query params for non-unprotected scopes', async () => {
+ const { requestedUrl } = await runLoadSearchEngines('private_only', 'searxng', []);
+ expect(requestedUrl).toBe('/settings/api/available-search-engines?egress_scope=private_only&primary=searxng');
+ });
+
+ it('omits query params for unprotected scope', async () => {
+ const { requestedUrl } = await runLoadSearchEngines('unprotected', 'searxng', []);
+ expect(requestedUrl).toBe('/settings/api/available-search-engines');
+ });
+
+ it('correctly maps egress policy restrictions onto dropdown options', async () => {
+ const mockRawOptions = [
+ { value: 'library', label: 'Library', egress: { allowed: true } },
+ { value: 'google', label: 'Google Search', egress: { allowed: false, reason: 'scope_mismatch_private_only' } },
+ { value: 'arxiv', label: 'ArXiv', egress: { allowed: false, reason: 'strict_not_primary' } },
+ { value: 'custom_pub', label: 'Custom Pub', egress: { allowed: false, reason: 'scope_mismatch_public_only' } },
+ { value: 'unknown_eng', label: 'Unknown Engine', egress: { allowed: false, reason: 'unclassified' } },
+ { value: 'denied_eng', label: 'Denied Engine', egress: { allowed: false, reason: 'engine_denied' } },
+ { value: 'other_blocked', label: 'Other Engine', egress: { allowed: false, reason: 'some_other_reason' } },
+ ];
+
+ const { searchEngineOptions, windowUpdateOptions } = await runLoadSearchEngines('private_only', 'library', mockRawOptions);
+
+ expect(searchEngineOptions[0].disabled).toBe(false);
+ expect(searchEngineOptions[0].disabled_reason).toBeNull();
+
+ expect(searchEngineOptions[1].disabled).toBe(true);
+ expect(searchEngineOptions[1].disabled_reason).toBe('Blocked: not a local source under Private only');
+
+ expect(searchEngineOptions[2].disabled).toBe(true);
+ expect(searchEngineOptions[2].disabled_reason).toBe('Blocked: only the primary search engine is allowed under Strict');
+
+ expect(searchEngineOptions[3].disabled).toBe(true);
+ expect(searchEngineOptions[3].disabled_reason).toBe('Blocked: local source under Public only');
+
+ expect(searchEngineOptions[4].disabled).toBe(true);
+ expect(searchEngineOptions[4].disabled_reason).toBe('Blocked: Unknown Engine is not recognized by the egress policy');
+
+ expect(searchEngineOptions[5].disabled).toBe(true);
+ expect(searchEngineOptions[5].disabled_reason).toBe('Blocked: Denied Engine is denied by the egress policy');
+
+ expect(searchEngineOptions[6].disabled).toBe(true);
+ expect(searchEngineOptions[6].disabled_reason).toBe('Blocked by egress policy (some_other_reason)');
+
+ expect(windowUpdateOptions).toHaveBeenCalledWith(
+ document.getElementById('subscription-search-engine'),
+ searchEngineOptions
+ );
+ });
+});
diff --git a/tests/news/test_web_blueprint.py b/tests/news/test_web_blueprint.py
index daf0e5366a..08d72b4e33 100644
--- a/tests/news/test_web_blueprint.py
+++ b/tests/news/test_web_blueprint.py
@@ -297,6 +297,18 @@ class TestNewSubscriptionPageRoute:
kwargs["default_settings"]["search_strategy"] == "source-based"
)
+ def test_new_subscription_page_has_default_egress_scope(self, client):
+ """Test default egress_scope is 'adaptive' for anonymous users."""
+ with patch(
+ "local_deep_research.news.web.render_template"
+ ) as mock_render:
+ mock_render.return_value = "rendered"
+
+ client.get("/news/subscriptions/new")
+
+ args, kwargs = mock_render.call_args
+ assert kwargs["default_settings"]["egress_scope"] == "adaptive"
+
def test_new_subscription_page_logged_in_user_loads_settings(self, app):
"""Test that logged-in user triggers DB session."""
with app.test_client() as client:
@@ -801,6 +813,51 @@ class TestLoadUserSettings:
default_settings["custom_endpoint"] == "https://custom.api.com"
)
+ def test_load_user_settings_updates_egress_scope(self):
+ """Test that egress_scope comes from 'policy.egress_scope'."""
+ from local_deep_research.news.web import load_user_settings
+
+ default_settings = {"egress_scope": "adaptive"}
+
+ with patch(
+ "local_deep_research.utilities.db_utils.get_settings_manager"
+ ) as mock_get:
+ mock_manager = MagicMock()
+ mock_manager.get_setting.side_effect = lambda key, default: (
+ "private_only" if key == "policy.egress_scope" else default
+ )
+ mock_get.return_value = mock_manager
+
+ mock_session = MagicMock()
+
+ load_user_settings(default_settings, mock_session, "testuser")
+
+ assert default_settings["egress_scope"] == "private_only"
+
+ def test_news_subscription_form_egress_scope_defaults_to_adaptive_on_error(
+ self,
+ ):
+ """Test that egress_scope defaults to 'adaptive' when settings loading fails."""
+ from local_deep_research.news.web import load_user_settings
+
+ default_settings = {
+ "iterations": 3,
+ "questions_per_iteration": 5,
+ "search_engine": "searxng",
+ "egress_scope": "adaptive",
+ }
+
+ with patch(
+ "local_deep_research.utilities.db_utils.get_settings_manager"
+ ) as mock_get:
+ mock_get.side_effect = RuntimeError("Settings service unavailable")
+
+ mock_session = MagicMock()
+
+ load_user_settings(default_settings, mock_session, "testuser")
+
+ assert default_settings["egress_scope"] == "adaptive"
+
def test_load_user_settings_exception_uses_defaults(self):
"""Test that defaults are preserved when exception occurs."""
from local_deep_research.news.web import load_user_settings
@@ -809,6 +866,7 @@ class TestLoadUserSettings:
"iterations": 3,
"questions_per_iteration": 5,
"search_engine": "searxng",
+ "egress_scope": "adaptive",
}
with patch(
@@ -825,6 +883,7 @@ class TestLoadUserSettings:
assert default_settings["iterations"] == 3
assert default_settings["questions_per_iteration"] == 5
assert default_settings["search_engine"] == "searxng"
+ assert default_settings["egress_scope"] == "adaptive"
def test_load_user_settings_calls_get_settings_manager(self):
"""Test that get_settings_manager is called with correct args."""
diff --git a/tests/web/routes/test_available_search_engines_scope.py b/tests/web/routes/test_available_search_engines_scope.py
new file mode 100644
index 0000000000..b6e7ad34fd
--- /dev/null
+++ b/tests/web/routes/test_available_search_engines_scope.py
@@ -0,0 +1,392 @@
+"""Coverage for the scope-aware variant of
+``GET /settings/api/available-search-engines`` (issue #5204).
+
+The endpoint stays backward-compatible: when ``?egress_scope=`` is
+absent (or set to ``unprotected``), the response shape is unchanged
+and the options are returned without an ``egress`` field. When the
+caller opts in, every option gets an ``egress: {allowed, reason}``
+field matching the same PDP the request-boundary precheck uses.
+
+The tests below stub the engine-class flag lookups inside
+``policy`` (``_get_engine_class`` and ``_engine_flags``) so they
+exercise the helper's wiring (scope mapping,
+fail-closed under bad input) without depending on third-party
+engines like ``arxiv`` that require ``feedparser`` to import. The
+*real* ``evaluate_engine`` runs the rest of its usual logic on top
+of the mocked flags, so this still exercises the full helper path.
+"""
+
+import pytest
+
+from local_deep_research.web.routes.settings_routes import (
+ _classify_options_for_egress,
+)
+
+
+def _option(value, label=None, **extra):
+ """Build a minimal engine option the helper accepts."""
+ return {
+ "value": value,
+ "label": label or value,
+ "category": "Web Search",
+ "icon": "🌐",
+ "requires_api_key": False,
+ "is_favorite": False,
+ "group": "web",
+ "group_label": "Web",
+ "group_order": 1,
+ "base_group": "web",
+ "base_group_label": "Web",
+ "base_group_order": 1,
+ **extra,
+ }
+
+
+def _snap(scope="adaptive", primary="arxiv"):
+ return {
+ "policy.egress_scope": scope,
+ "search.tool": primary,
+ }
+
+
+# Static engine class flags keyed by engine id. We mock the
+# policy module's _get_engine_class to return a fake class with
+# the matching (is_public, is_local) tuple so the real evaluate_engine
+# flow runs on top of deterministic per-engine classification without
+# needing the engines' third-party deps installed (feedparser for
+# arxiv, etc.). ``library`` and ``collection_x`` are intentionally
+# NOT in this map so they keep their real per-collection resolution.
+_FLAGS = {
+ "arxiv": (True, False), # public web engine
+ "github": (True, False), # public code search
+ "library": None, # real path: collection/library branch
+ "collection_x": None, # real path: collection branch
+}
+
+
+def _fake_engine_class(engine_name):
+ flags = _FLAGS.get(engine_name)
+ if flags is None:
+ return None # not in the static map → real path handles it
+ is_public, is_local = flags
+
+ class _Fake:
+ pass
+
+ _Fake.is_public = is_public
+ _Fake.is_local = is_local
+ _Fake.url_setting = None
+ return _Fake
+
+
+def stub_engine_flags(monkeypatch):
+ """Make _get_engine_class return a deterministic fake for the
+ public/private engines we test against, without importing them.
+
+ Also short-circuit ``_classify_engine_url`` so the URL-override
+ path (which would do a DNS lookup in real life) never fires for
+ the fake classes.
+ """
+ from local_deep_research.security.egress import policy as policy_mod
+
+ monkeypatch.setattr(policy_mod, "_get_engine_class", _fake_engine_class)
+ monkeypatch.setattr(
+ policy_mod,
+ "_classify_engine_url",
+ lambda *_a, **_k: None, # never override the static flags
+ )
+
+
+class TestClassifyOptionsForEgress:
+ """Per-option egress classification (issue #5204 acceptance criteria)."""
+
+ def test_private_only_denies_public_engines_strictly(
+ self, stub_engine_flags
+ ):
+ # Under private_only, public engines (e.g. arxiv, github) are denied
+ # regardless of primary engine setting.
+ options = [
+ _option("arxiv"),
+ _option("github"),
+ _option("library"),
+ ]
+ snap = _snap(scope="private_only", primary="arxiv")
+
+ _classify_options_for_egress(
+ options,
+ egress_scope="private_only",
+ primary_engine="arxiv",
+ settings_snapshot=snap,
+ username="user",
+ )
+
+ # Every option has the egress field.
+ assert all("egress" in opt for opt in options)
+ # Public engines under private_only are denied.
+ arxiv = next(o for o in options if o["value"] == "arxiv")
+ github = next(o for o in options if o["value"] == "github")
+ lib = next(o for o in options if o["value"] == "library")
+
+ assert arxiv["egress"]["allowed"] is False
+ assert arxiv["egress"]["reason"] == "scope_mismatch_private_only"
+ assert github["egress"]["allowed"] is False
+ assert github["egress"]["reason"] == "scope_mismatch_private_only"
+ assert lib["egress"]["allowed"] is True
+
+ def test_public_only_denies_local_engines(self, stub_engine_flags):
+ options = [_option("arxiv"), _option("library")]
+ snap = _snap(scope="public_only", primary="arxiv")
+
+ _classify_options_for_egress(
+ options,
+ egress_scope="public_only",
+ primary_engine="arxiv",
+ settings_snapshot=snap,
+ username="user",
+ )
+
+ arxiv = next(o for o in options if o["value"] == "arxiv")
+ lib = next(o for o in options if o["value"] == "library")
+ assert arxiv["egress"]["allowed"] is True
+ assert lib["egress"]["allowed"] is False
+ assert lib["egress"]["reason"] == "scope_mismatch_public_only"
+
+ def test_private_only_allows_local_engines(self, stub_engine_flags):
+ options = [_option("arxiv"), _option("library")]
+ snap = _snap(scope="private_only", primary="library")
+
+ _classify_options_for_egress(
+ options,
+ egress_scope="private_only",
+ primary_engine="library",
+ settings_snapshot=snap,
+ username="user",
+ )
+
+ arxiv = next(o for o in options if o["value"] == "arxiv")
+ lib = next(o for o in options if o["value"] == "library")
+ assert arxiv["egress"]["allowed"] is False
+ assert arxiv["egress"]["reason"] == "scope_mismatch_private_only"
+ assert lib["egress"]["allowed"] is True
+ # ...and the local primary stays allowed (carve-out).
+
+ def test_strict_mode_evaluates_primary_engine(self, stub_engine_flags):
+ options = [_option("arxiv"), _option("library"), _option("github")]
+ snap = _snap(scope="strict", primary="arxiv")
+
+ _classify_options_for_egress(
+ options,
+ egress_scope="strict",
+ primary_engine="arxiv",
+ settings_snapshot=snap,
+ username="user",
+ )
+
+ primary = next(o for o in options if o["value"] == "arxiv")
+ assert primary["egress"]["allowed"] is True
+ for opt in options:
+ if opt["value"] == "arxiv":
+ continue
+ assert opt["egress"]["allowed"] is False
+ assert opt["egress"]["reason"] == "strict_not_primary"
+
+ def test_missing_snapshot_is_noop(self):
+ # A non-dict snapshot (the test-double path the precheck also
+ # has) is treated as "no filter": the helper must not raise,
+ # and options come through unchanged so the frontend falls back
+ # to today's behavior.
+ options = [_option("arxiv"), _option("library")]
+
+ _classify_options_for_egress(
+ options,
+ egress_scope="private_only",
+ primary_engine="arxiv",
+ settings_snapshot=None, # not a dict
+ username="user",
+ )
+
+ assert all("egress" not in opt for opt in options)
+
+ def test_corrupt_scope_emits_policy_unavailable(self):
+ # An unrecognised scope (PolicyDeniedError from
+ # context_from_snapshot) must NOT crash the dropdown — the
+ # helper falls back to permissive so the user can still pick
+ # and the precheck's 400 surfaces the real error.
+ options = [_option("arxiv"), _option("library")]
+ snap = _snap(scope="garbage", primary="arxiv")
+
+ _classify_options_for_egress(
+ options,
+ egress_scope="garbage", # caller asked for filtering under corrupt scope...
+ primary_engine="arxiv",
+ settings_snapshot=snap,
+ username="user",
+ )
+
+ # No crashing; all options got a policy_unavailable marker.
+ for opt in options:
+ assert opt["egress"]["allowed"] is True
+ assert opt["egress"]["reason"] == "policy_unavailable"
+
+ def test_preserves_unrelated_fields(self, stub_engine_flags):
+ # The helper must mutate ONLY by adding ``egress``; every other
+ # field the frontend relies on (label, group_label, etc.) is
+ # untouched.
+ options = [_option("arxiv", label="📁 ArXiv (Web Search)")]
+ snap = _snap(scope="private_only", primary="arxiv")
+
+ _classify_options_for_egress(
+ options,
+ egress_scope="private_only",
+ primary_engine="arxiv",
+ settings_snapshot=snap,
+ username="user",
+ )
+
+ opt = options[0]
+ assert opt["label"] == "📁 ArXiv (Web Search)"
+ assert opt["category"] == "Web Search"
+ assert opt["group_label"] == "Web"
+ # arxiv is public -> denied under private_only
+ assert opt["egress"]["allowed"] is False
+ assert opt["egress"]["reason"] == "scope_mismatch_private_only"
+
+ def test_handles_empty_option_list(self, stub_engine_flags):
+ # An empty option list must not crash — the helper is called
+ # even when no engines are configured.
+ snap = _snap(scope="private_only", primary="arxiv")
+ _classify_options_for_egress(
+ [],
+ egress_scope="private_only",
+ primary_engine="arxiv",
+ settings_snapshot=snap,
+ username="user",
+ )
+ # No assertion needed — the test is "no exception".
+
+ def test_request_omitting_egress_scope_is_unfiltered(
+ self, stub_engine_flags, monkeypatch
+ ):
+ # When egress_scope is omitted or empty, options are classified under
+ # the saved snapshot's unprotected scope and all remain allowed.
+ # Since PR #5148 the unprotected escape hatch is operator-gated:
+ # without the gate the scope is coerced to adaptive, so enable it
+ # here to keep exercising the genuine unprotected path.
+ from local_deep_research.security.egress import policy as policy_mod
+
+ monkeypatch.setattr(
+ policy_mod, "unprotected_egress_allowed", lambda: True
+ )
+ options = [_option("arxiv"), _option("github"), _option("library")]
+ snap = _snap(scope="unprotected", primary="github")
+
+ _classify_options_for_egress(
+ options,
+ egress_scope="",
+ primary_engine="",
+ settings_snapshot=snap,
+ username="user",
+ )
+
+ for opt in options:
+ assert opt["egress"]["allowed"] is True
+
+ def test_override_egress_scope_differs_from_settings_snapshot(
+ self, stub_engine_flags
+ ):
+ # When the user changes scope on the form, egress_scope passed to the helper
+ # must override the saved DB snapshot's policy.egress_scope (issue #5204).
+ options = [_option("arxiv"), _option("github"), _option("library")]
+ snap = _snap(scope="adaptive", primary="github")
+
+ _classify_options_for_egress(
+ options,
+ egress_scope="private_only",
+ primary_engine="github",
+ settings_snapshot=snap,
+ username="user",
+ )
+
+ arxiv = next(o for o in options if o["value"] == "arxiv")
+ github = next(o for o in options if o["value"] == "github")
+ lib = next(o for o in options if o["value"] == "library")
+
+ # Under private_only, public engines (github, arxiv) are denied
+ assert github["egress"]["allowed"] is False
+ assert github["egress"]["reason"] == "scope_mismatch_private_only"
+ assert arxiv["egress"]["allowed"] is False
+ assert arxiv["egress"]["reason"] == "scope_mismatch_private_only"
+ # Local engines (library) are allowed
+ assert lib["egress"]["allowed"] is True
+
+
+class TestApiAvailableSearchEnginesEndpoint:
+ """Integration coverage for GET /settings/api/available-search-engines dropdown filtering."""
+
+ def test_private_only_scope_filters_public_options(
+ self, authenticated_client
+ ):
+ res = authenticated_client.get(
+ "/settings/api/available-search-engines?egress_scope=private_only"
+ )
+ assert res.status_code == 200
+ data = res.get_json()
+ assert "engine_options" in data
+ options = data["engine_options"]
+
+ # Local library option is allowed
+ lib = next((o for o in options if o.get("value") == "library"), None)
+ if lib and "egress" in lib:
+ assert lib["egress"]["allowed"] is True
+
+ # Public engines (if present) are marked as denied under private_only
+ public_engine = next(
+ (
+ o
+ for o in options
+ if o.get("value") in ("searxng", "arxiv", "github")
+ ),
+ None,
+ )
+ if public_engine and "egress" in public_engine:
+ assert public_engine["egress"]["allowed"] is False
+ assert (
+ public_engine["egress"]["reason"]
+ == "scope_mismatch_private_only"
+ )
+
+ def test_public_only_scope_filters_local_options(
+ self, authenticated_client
+ ):
+ res = authenticated_client.get(
+ "/settings/api/available-search-engines?egress_scope=public_only"
+ )
+ assert res.status_code == 200
+ data = res.get_json()
+ assert "engine_options" in data
+ options = data["engine_options"]
+
+ lib = next((o for o in options if o.get("value") == "library"), None)
+ if lib and "egress" in lib:
+ assert lib["egress"]["allowed"] is False
+ assert lib["egress"]["reason"] == "scope_mismatch_public_only"
+
+ def test_adaptive_and_strict_scopes_skip_dropdown_filtering(
+ self, authenticated_client
+ ):
+ for scope in ("adaptive", "strict", "unprotected"):
+ res = authenticated_client.get(
+ f"/settings/api/available-search-engines?egress_scope={scope}"
+ )
+ assert res.status_code == 200
+ data = res.get_json()
+ options = data.get("engine_options", [])
+ # Under adaptive, strict, or unprotected, dropdown filtering is skipped
+ # so no engines carry egress.allowed = False
+ denied = [
+ o
+ for o in options
+ if o.get("egress", {}).get("allowed") is False
+ ]
+ assert len(denied) == 0
diff --git a/tests/web/routes/test_research_routes_policy.py b/tests/web/routes/test_research_routes_policy.py
index b7abbd943a..121a2fcb66 100644
--- a/tests/web/routes/test_research_routes_policy.py
+++ b/tests/web/routes/test_research_routes_policy.py
@@ -9,14 +9,16 @@ Targets:
Needs a Flask app context for jsonify.
"""
-from unittest.mock import Mock
+from unittest.mock import MagicMock, Mock, patch
import pytest
from flask import Flask
from local_deep_research.security.egress.policy import PolicyDeniedError
from local_deep_research.web.routes.research_routes import (
+ LANGGRAPH_STRATEGY_NAME,
_apply_policy_overrides,
+ _precheck_collection_agent_enabled,
_precheck_engine_policy,
)
@@ -354,3 +356,163 @@ class TestPrecheckEnginePolicy:
mgr, {"model_provider": "ollama"}, "paperless", "user"
)
assert result is None
+
+
+# ---------------------------------------------------------------------------
+# _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, app_ctx):
+ # 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 = result[0].get_json()
+ assert result[1] == 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, app_ctx):
+ # 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, app_ctx):
+ # 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"
+ )
+
+ def test_non_collection_engine_is_skipped(self, app_ctx):
+ # 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, app_ctx):
+ # 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, app_ctx):
+ # 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, app_ctx):
+ # 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, app_ctx):
+ # 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[1] == 400