~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
feat(ux): surface engine-URL guard state across the web UI (#5648)
LearningCircuit273712e935e6
diff --git a/changelog.d/5648.feature.md b/changelog.d/5648.feature.mdnew file mode 100644index 0000000000..6c97782709--- /dev/null+++ b/changelog.d/5648.feature.md@@ -0,0 +1 @@+Clearer feedback when the private engine-URL guard blocks something: the settings page now shows the actual rejection reason inline at the field (previously a bare "Validation errors" toast — the detailed remedy text was computed but never displayed); a guard-blocked SearXNG is grayed out in the research form's and the news subscription form's engine pickers with an explanatory note naming the operator-side remedy, instead of being silently selectable, under every egress scope including the default (the guard itself is scope-independent, so the picker's advisory is too — note it is advisory: it does no DNS lookup, so a private-DNS hostname still only fails at run time); on a default install (SearXNG at `http://localhost:8080`) the research form therefore substitutes another engine for the run and records the substitution in the browser console, leaving the saved `search.tool` untouched, while the settings page's own engine list stays unmapped so the blocked engine remains selectable on the page where its URL is fixed; environment-variable remedies in warning banners render as code for easy copying; error notifications stay on screen longer; and the collapsed log panel's counter badge turns red, with a "!" glyph and a screen-reader label, when the log contains errors — CRITICAL and FATAL included, and it stays flagged once an error has scrolled out of the panel's window. The research form's "custom model name entered" hint now actually appears: it looked for an unprefixed `.form-group` ancestor, which the research page's `ldr-`-prefixed markup does not have, so the element was built and then dropped on the floor.diff --git a/src/local_deep_research/web/routers/settings.py b/src/local_deep_research/web/routers/settings.pyindex 8b7fd2e060..0e7cc78fe5 100644--- a/src/local_deep_research/web/routers/settings.py+++ b/src/local_deep_research/web/routers/settings.py@@ -3236,6 +3236,15 @@ def _classify_options_for_egress(handles updating any invalid primary selection when scope changes. The factory PEPstill enforces at instantiation time; this is a UX filter, not a security boundary.+ After the PDP pass it applies ``_apply_guarded_url_overlay``, which+ can deny an engine the PDP allowed (an unapproved private instance+ URL). That overlay is scope-independent and therefore also runs when+ the caller did NOT opt into scope filtering — see the route — and on+ every degraded early return below (an unimportable policy module, an+ unknown ``?egress_scope=``): it needs only the settings snapshot, not+ the PDP context, and the runtime blocks the URL regardless, so+ skipping it there would make a guard-denied engine read as selectable.+Operates in place; safe to call on a freshly built option list.Failures are swallowed per option (logged) — a single bad enginemust not blank the whole dropdown.@@ -3250,6 +3259,9 @@ def _classify_options_for_egress(logger.exception("egress policy unavailable; emitting unfiltered options")+ # The URL guard does not ride on the PDP — it only needs the+ # snapshot — so it still runs when the PDP is unavailable.+ _apply_guarded_url_overlay(engine_options, settings_snapshot)returnif not isinstance(settings_snapshot, dict):@@ -3261,6 +3273,13 @@ def _classify_options_for_egress("settings_snapshot (type={}); emitting unfiltered options",type(settings_snapshot).__name__,)+ # Match every other degraded early return: the overlay is a+ # no-op here (it guards on isinstance(settings_snapshot, dict)+ # itself) since there's no dict to read a URL from, but calling+ # it keeps this branch consistent with the docstring above and+ # fail-safe if a future caller ever reaches this branch with+ # something the overlay CAN read.+ _apply_guarded_url_overlay(engine_options, settings_snapshot)return# Build an evaluation snapshot that reflects the requested scope and@@ -3312,11 +3331,17 @@ def _classify_options_for_egress("allowed": True,"reason": "policy_unavailable",}+ # Permissive on SCOPE only. The URL guard is independent of+ # the PDP context that just failed to build, and the runtime+ # still blocks the URL, so a guard-denied engine must not read+ # as selectable on this degraded path either.+ _apply_guarded_url_overlay(engine_options, eval_snapshot)returnexcept Exception: # pragma: no cover - defensivelogger.exception("egress context build failed; emitting unfiltered options")+ _apply_guarded_url_overlay(engine_options, eval_snapshot)returnfor opt in engine_options:@@ -3337,6 +3362,119 @@ def _classify_options_for_egress(logger.exception(f"egress decision failed for engine {engine_id}")opt["egress"] = {"allowed": True, "reason": "decision_error"}+ # Guarded engine-URL overlay: a public engine whose configured private+ # URL lacks operator approval self-disables at runtime, so the dropdown+ # should gray it out too. Applied here (rather than in the caller) so+ # every code path that stamps egress decisions also carries the guard.+ # Deliberately scope-INDEPENDENT — see _apply_guarded_url_overlay.+ _apply_guarded_url_overlay(engine_options, eval_snapshot)+++def _apply_guarded_url_overlay(+ engine_options: list, settings_snapshot: dict+) -> None:+ """Gray out engines whose configured instance URL the runtime will refuse.++ A PUBLIC-nature engine (SearXNG and friends) pointed at a private /+ loopback instance URL without operator approval self-disables at init+ and silently contributes zero results to the run. This overlay stamps+ ``egress={"allowed": False, "reason": "private_url_unapproved"}`` on+ those options so the picker grays them out with an explanatory note.++ SCOPE-INDEPENDENT BY CONSTRUCTION. The approval resolver this rides on+ (``resolve_engine_allow_private_ips``) deliberately ignores+ ``policy.egress_scope`` — it is a user-editable dropdown, so honouring+ it would be a self-service SSRF bypass — which means the runtime blocks+ the URL under EVERY scope. The overlay must therefore run under every+ scope too, including the shipped ``adaptive`` default and the+ ``unprotected`` escape hatch, and NOT only when the caller opted into+ scope filtering via ``?egress_scope=``. Before PR #5648's follow-up+ this lived inside the ``apply_egress_filter`` branch and could only+ ever fire under ``public_only`` (under ``private_only`` a public engine+ is already denied for scope reasons), i.e. never on a default install.++ ADVISORY, NOT AUTHORITATIVE — it is a strict subset of what the runtime+ enforces. ``check_private_engine_url_blocked`` is deliberately+ DNS-free (it must not turn a settings-page render into a resolver+ round-trip, nor let a hostile URL make the render path probe an+ internal name), so a private-DNS hostname (``searx.internal`` -> 10.x)+ and a short-form literal (``127.1``) are NOT caught here even though+ the runtime's ``validate_url`` resolves and blocks them. The overlay+ therefore fails OPEN: an engine it leaves selectable may still be+ refused at run time. For that residual gap the ONLY backstop is the+ runtime's log-panel ERROR — NOT the research form's warning banner,+ which ``warning_checks`` emits from this very same DNS-free check and+ which therefore stays silent on exactly the URLs the overlay misses+ (and is additionally suppressed once the user dismisses it, which the+ overlay ignores).++ It effectively never fails CLOSED — nothing the runtime would fetch is+ grayed out here. The one theoretical exception is a host name ending+ in ``.local``, which ``is_private_ip`` classifies by suffix: if a+ non-conforming resolver or a ``hosts`` entry maps it to a PUBLIC+ address the runtime would allow it while this overlay grays it out.+ ``.local`` is reserved for mDNS (RFC 6762), so that is a+ misconfiguration rather than a supported setup.++ Options already carrying a denial (``allowed: False``) are left alone+ so a scope denial keeps its more specific reason. Operates in place;+ every failure is swallowed per engine so one bad descriptor cannot+ blank the dropdown.+ """+ if not engine_options or not isinstance(settings_snapshot, dict):+ return+ try:+ from ...security.egress.validators import (+ guarded_engine_url_descriptors,+ )+ from ...security.egress.warnings import (+ check_private_engine_url_blocked,+ )+ from ...utilities.type_utils import unwrap_setting++ guarded_urls = {+ d.engine_name: d+ for d in guarded_engine_url_descriptors()+ if d.is_public+ }+ except Exception: # pragma: no cover - defensive+ logger.exception("guarded engine-URL overlay unavailable")+ return++ for opt in engine_options:+ # Everything that touches the option — including the id lookup and+ # the existing-decision read — runs inside the try, so a malformed+ # entry is swallowed per engine as the docstring promises rather+ # than aborting the overlay for the rest of the list.+ desc = None+ try:+ desc = guarded_urls.get(opt.get("value"))+ if desc is None:+ continue+ existing = opt.get("egress")+ if isinstance(existing, dict) and not existing.get("allowed", True):+ continue+ url_value = unwrap_setting(+ settings_snapshot.get(desc.url_setting, "")+ )+ if check_private_engine_url_blocked(+ desc.engine_name,+ desc.engine_name,+ desc.url_setting,+ url_value,+ True,+ False,+ ):+ opt["egress"] = {+ "allowed": False,+ "reason": "private_url_unapproved",+ }+ except Exception:+ engine_name = desc.engine_name if desc is not None else "unknown"+ logger.exception(+ f"guarded-URL overlay failed for engine {engine_name}"+ )+@router.get("/api/available-search-engines")def api_get_available_search_engines(@@ -3353,9 +3491,17 @@ def api_get_available_search_engines(``primary`` — the user's saved primary search tool, used by thePDP 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.).+ When ``egress_scope`` is absent the SCOPE filtering is skipped, but+ the guarded engine-URL overlay still runs: it stamps+ ``egress: {allowed: false, reason: "private_url_unapproved"}`` on any+ public engine whose configured instance URL the runtime will refuse+ for lack of operator approval. That guard ignores+ ``policy.egress_scope`` by design, so gating the overlay on the+ opt-in would have hidden it on every default (``adaptive``) install.+ Options that are not guard-blocked keep the historical shape (no+ ``egress`` key), so existing callers — the settings page, the news+ form — are unaffected except for the engines they could not have+ used anyway."""try:# Issue #5204: optional egress-scope filter. The scope/primary@@ -3511,24 +3657,32 @@ 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).+ # submit time. UNPROTECTED and missing-scope callers skip the+ # SCOPE filtering (the historical shape) but still get the+ # guarded engine-URL overlay: that guard is scope-independent by+ # design (see ``_apply_guarded_url_overlay``), so an engine the+ # runtime will refuse must read as disabled under the shipped+ # ``adaptive`` default too, not only under ``public_only``.+ try:+ policy_snapshot = settings_manager.get_settings_snapshot()+ except Exception: # pragma: no cover - defensive+ logger.exception(+ "settings snapshot unavailable for egress filter"+ )+ policy_snapshot = {}+ policy_snapshot = policy_snapshot or {}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 = {}+ # Runs the guarded-URL overlay itself, after the PDP pass._classify_options_for_egress(engine_options,egress_scope=requested_scope,primary_engine=requested_primary,- settings_snapshot=policy_snapshot or {},+ settings_snapshot=policy_snapshot,username=username,search_engines=search_engines,)+ else:+ _apply_guarded_url_overlay(engine_options, policy_snapshot)return {"engines": engines_dict,diff --git a/src/local_deep_research/web/static/css/styles.css b/src/local_deep_research/web/static/css/styles.cssindex 25f8b48f9e..dfb7c54fe0 100644--- a/src/local_deep_research/web/static/css/styles.css+++ b/src/local_deep_research/web/static/css/styles.css@@ -2067,6 +2067,31 @@ textarea:focus, input[type="text"]:focus {text-align: center;}+/* Collapsed-panel severity signal: the count badge turns error-colored+ when the log contains ERROR entries (same variable as the per-entry+ error badge), so failures are visible without expanding the panel.++ Colour is NOT the only channel. --error-color and --accent-primary are+ similar-luminance mid-tones both carrying white text, so the swap alone+ is invisible to a red/purple-confusing viewer (and to anyone who never+ saw the un-alerted badge to compare against). The state therefore also+ changes TEXT and WEIGHT: a trailing "!" glyph in bold. (No coloured+ ring — a ring in --error-color would be invisible against the badge it+ sits on.) The glyph is a ::after pseudo-element, so it never enters+ textContent — updateFilterCounters parses the indicator's textContent+ for the "All" badge and must keep reading a bare number. The matching+ role="img" + aria-label is set in logpanel.js (paintLogIndicators) so+ the state is not hover-only for assistive tech. */+.ldr-log-indicator--has-error {+ background-color: var(--error-color, #e74c3c);+ font-weight: 700;+}++.ldr-log-indicator--has-error::after {+ content: " !";+ font-weight: 700;+}+.ldr-log-panel-content {display: flex;flex-direction: column;diff --git a/src/local_deep_research/web/static/js/components/logpanel.js b/src/local_deep_research/web/static/js/components/logpanel.jsindex 29ebca47e4..4b8c79aeb9 100644--- a/src/local_deep_research/web/static/js/components/logpanel.js+++ b/src/local_deep_research/web/static/js/components/logpanel.js@@ -64,6 +64,14 @@// and bumps to HISTORY_LOGS_HARD_CAP after the user clicks "Load older",// so the panel can show up to the hard cap without a full re-init.renderedLimit: null,+ // High-water mark of ERROR-category entries seen for the connected+ // research. The header badge's severity signal reads this rather+ // than a live DOM count: the DOM holds only the rendered window+ // (older rows are paged out and the ordered prune can evict rows),+ // so a raw count can silently drop back to 0 and un-red a badge+ // for an error that really happened. Monotonic within a research;+ // reset by resetForResearchSwitch. Null/0 means "no error known".+ errorHighWater: 0,};/**@@ -104,6 +112,9 @@// still loading. The next loadLogsForResearch call will// recompute from B's DOM. See issue #5151 (Gap 2).window._logPanelState.counts = emptyCounts();+ // The error high-water mark is per-research too — B must not+ // inherit A's red badge.+ window._logPanelState.errorHighWater = 0;const renderedIds = new Set();document.querySelectorAll(@@ -421,10 +432,13 @@// Initialize the log countconst logIndicators = document.querySelectorAll('.ldr-log-indicator');if (logIndicators.length > 0) {- // Set count on all indicators- logIndicators.forEach(indicator => {- indicator.textContent = '0';- });+ // Set count on all indicators. Route through paintLogIndicators+ // rather than writing textContent directly so the severity+ // class/tooltip/ARIA are re-derived here too — otherwise a+ // re-init would repaint a fresh count under a stale red badge.+ const logContainerEl =+ document.getElementById('console-log-container');+ paintLogIndicators('0', logContainerEl, false);// Skip the API call when there is no researchId (e.g. on a// freshly-loaded /chat/ page before a research has started).@@ -436,9 +450,18 @@if (researchId) {fetchAndCacheLogCount(researchId).then((total) => {if (typeof total === 'number') {- logIndicators.forEach(indicator => {- indicator.textContent = formatNumber(total);- });+ // The server total counts rows the DOM does not+ // hold, so the error signal is a lower bound.+ const domCount = logContainerEl+ ? logContainerEl.querySelectorAll(+ '.ldr-console-log-entry'+ ).length+ : 0;+ paintLogIndicators(+ formatNumber(total),+ logContainerEl,+ domCount < total+ );}});}@@ -1481,6 +1504,107 @@}}+ /**+ * Count ERROR-severity entries currently rendered in `containerEl`.+ *+ * Reads `data-log-type` (the RAW level, which is what the row carries)+ * and folds it through `getDisplayLogCategory` — the same normalizer+ * `recomputeCountersFromDom` and the filter buttons use. A selector on+ * `[data-log-type="error"]` alone would miss CRITICAL and FATAL, the+ * two severities the badge most needs to surface, while the "Error"+ * filter badge counted them (they map to the `error` category).+ *+ * @param {Element|null} containerEl - The log container.+ * @returns {number} Rendered ERROR-category entry count.+ */+ function countRenderedErrors(containerEl) {+ if (!containerEl) return 0;+ let count = 0;+ containerEl+ .querySelectorAll('.ldr-console-log-entry')+ .forEach((entry) => {+ const raw = (entry.dataset.logType || 'info');+ if (getDisplayLogCategory(raw) === 'error') count++;+ });+ return count;+ }++ /**+ * Paint the header count badge(s): the numeric label plus the severity+ * signal, in ONE place.+ *+ * Every writer of `.ldr-log-indicator`'s textContent inside this module+ * must go through here. Earlier revisions of this branch had+ * `initializeLogPanel` and `recomputeCountersFromDom` write the number+ * directly while only `updateLogCountIndicator` toggled the error+ * class/title, so a re-init or a recompute left a stale red badge (and+ * stale tooltip) attached to a fresh count. The one writer outside this+ * module is `services/socket.js`'s no-log-panel fallback (it increments+ * `#log-indicator` directly around socket.js:1079-1083); it is reached+ * only when `window.logPanel` is absent, i.e. when this function does+ * not exist either.+ *+ * The error signal is a HIGH-WATER mark, not a live DOM count. The DOM+ * holds only the rendered window: the server returns the most recent+ * `limit` rows (errors are fetched first — `priority=diagnostic` sorts+ * ERROR/CRITICAL/FATAL to the front — but a run with more errors than+ * the limit still loses the oldest), and the ordered prune can evict+ * error rows once every routine row is gone. Flooring at the high-water+ * mark keeps a badge that has legitimately gone red from silently+ * going purple again. It also means the number is a LOWER BOUND+ * whenever the panel is showing a truncated slice, which the tooltip+ * says out loud rather than implying a total it cannot know.+ *+ * Accessibility: colour alone must not carry the state. The badge also+ * gets an `!` glyph (CSS `::after`, so `textContent` — which+ * `updateFilterCounters` parses — is untouched) and a heavier+ * weight, plus `role="img"` + `aria-label` so the severity is+ * exposed to assistive tech instead of living only in a hover `title`.+ *+ * @param {string} labelText - The already-formatted count label.+ * @param {Element|null} containerEl - Log container to count errors in.+ * @param {boolean} [truncated] - True when the panel is showing fewer+ * rows than exist server-side, making the error count a lower bound.+ * @returns {number} The error count applied (the high-water mark).+ */+ function paintLogIndicators(labelText, containerEl, truncated) {+ const indicators = document.querySelectorAll('.ldr-log-indicator');+ if (indicators.length === 0) return 0;++ const seen = countRenderedErrors(containerEl);+ const previous = window._logPanelState.errorHighWater || 0;+ const errorCount = Math.max(previous, seen);+ window._logPanelState.errorHighWater = errorCount;++ const plural = errorCount === 1 ? '' : 's';+ const qualifier = truncated ? 'at least ' : '';+ const description = errorCount > 0+ ? `${qualifier}${errorCount} error${plural} in the log — ` ++ 'expand the panel for details'+ : '';++ indicators.forEach((indicator) => {+ indicator.textContent = labelText;+ indicator.classList.toggle(+ 'ldr-log-indicator--has-error',+ errorCount > 0+ );+ if (errorCount > 0) {+ indicator.title = description;+ indicator.setAttribute('role', 'img');+ indicator.setAttribute(+ 'aria-label',+ `${labelText} log entries, ${description}`+ );+ } else {+ indicator.title = '';+ indicator.removeAttribute('role');+ indicator.removeAttribute('aria-label');+ }+ });+ return errorCount;+ }+/*** Render the log-panel-header indicator (`.ldr-log-indicator`) with the* current DOM count, and append a "Load older" button when the persisted@@ -1543,9 +1667,18 @@? Math.max(rendered, fetched): rendered;const indicatorLabel = formatNumber(indicatorValue);- logIndicators.forEach(indicator => {- indicator.textContent = indicatorLabel;- });+ // Surface severity on the always-visible header badge: the panel+ // starts collapsed, so without this an ERROR (e.g. an engine+ // self-disabling) is invisible until the user happens to expand+ // and filter the log. The count is a lower bound whenever the+ // panel is showing a truncated slice (server truncation, or the+ // post-dedup DOM holding fewer rows than were fetched), so tell+ // paintLogIndicators to word the tooltip as "at least N".+ paintLogIndicators(+ indicatorLabel,+ containerEl,+ truncated || rendered < indicatorValue+ );// updateFilterCounters reads the indicator textContent to set the// "All" badge — refresh it here so a higher fetched count (which// floors the indicator after message-content dedup) propagates to@@ -1755,9 +1888,14 @@window._logPanelState.counts = counts;// String() coercion matches updateFilterCounters' ""→"0" guard// for happy-dom (real browsers coerce to "0" automatically).- document.querySelectorAll('.ldr-log-indicator').forEach((indicator) => {- indicator.textContent = String(reportedTotal);- });+ // paintLogIndicators (not a bare textContent write) so the+ // severity class/tooltip/ARIA are recomputed with the count+ // instead of being left behind from the previous paint.+ paintLogIndicators(+ String(reportedTotal),+ logContent,+ total < reportedTotal+ );updateFilterCounters(reportedTotal);}@@ -1895,7 +2033,13 @@loadLogs: loadLogsForResearch,// Exposed for unit tests so the per-category prune ordering can be// exercised in isolation from the rest of the panel pipeline.- _pruneToCap: pruneToCap+ _pruneToCap: pruneToCap,+ // Exposed for unit tests: the header badge's count + severity+ // paint is otherwise only reachable through a full load/insert+ // cycle, which makes the CRITICAL/FATAL and paged-out cases+ // awkward to drive directly.+ _updateLogCountIndicator: updateLogCountIndicator,+ _recomputeCountersFromDom: recomputeCountersFromDom};// Self-invoke to initialize when DOM content is loadeddiff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.jsindex fd3605c8ee..68690dbad8 100644--- a/src/local_deep_research/web/static/js/components/research.js+++ b/src/local_deep_research/web/static/js/components/research.js@@ -1230,7 +1230,13 @@warningEl.id = 'custom-model-warning';warningEl.className = 'ldr-model-warning';warningEl.textContent = 'Custom model name entered. Make sure it exists in your provider.';- const parent = modelDropdown.closest('.form-group');+ // The research page wraps the dropdown in `.ldr-form-group`; the+ // unprefixed class only exists on older/settings markup. Fall back+ // to the immediate parent so the warning is never silently dropped.+ const parent =+ modelDropdown &&+ (modelDropdown.closest('.ldr-form-group, .form-group') ||+ modelDropdown.parentNode);if (parent) {parent.appendChild(warningEl);}@@ -2591,6 +2597,12 @@return `Blocked: ${display} is not recognized by the egress policy`;case 'engine_denied':return `Blocked: ${display} is denied by the egress policy`;+ case 'private_url_unapproved':+ // Deliberately not "see the warning banner": that banner is+ // suppressed once dismissed, and it is emitted from the same+ // DNS-free check as this overlay, so it stays silent on exactly+ // the URLs the overlay misses. Name the operator-side remedy.+ return `Disabled: ${display}'s private instance URL needs server-operator approval (env-only: allow private IPs, add the origin to search.private_engine_url_allowlist, or env-lock the engine's URL setting)`;default:return `Blocked by egress policy (${reason})`;}@@ -2781,11 +2793,18 @@// 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.- // When the endpoint was called with egress_scope=- // (issue #5204) each option also carries an+ // An option may also carry an// ``egress: {allowed, reason}`` field; we surface// that as the disabled / disabled_reason contract- // the custom dropdown already understands.+ // the custom dropdown already understands. Full+ // per-scope classification requires the+ // egress_scope= opt-in (issue #5204), but the+ // guarded engine-URL overlay is stamped on EVERY+ // response — that guard ignores the egress scope,+ // so an engine whose private instance URL the+ // runtime will refuse must read as disabled here+ // under the default ``adaptive`` scope too, where+ // getCurrentEgressScopeForDropdown sends no scope.formattedEngines = data.engine_options.map(mapEngineOption);}// Also try adding engines from engines object if it existsdiff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.jsindex a9cdd29e6f..4d8a0ae66b 100644--- a/src/local_deep_research/web/static/js/components/settings.js+++ b/src/local_deep_research/web/static/js/components/settings.js@@ -3197,6 +3197,66 @@}}+ /**+ * Render a settings-save failure: mark every rejected setting the user+ * can see, then hang the per-setting details off the generic headline.+ * The backend puts the actionable text — e.g. the private-URL remedies+ * — in `errors[]`, which the flattened message on its own discards.+ *+ * Shared by the 2xx-with-error-status branch of the success handler and+ * by the fetch-rejection handler, since save_all_settings reports+ * validation failures as a non-2xx (400/403) response and+ * fetchWithErrorHandling turns those into a rejection carrying the+ * parsed body on `error.details`.+ *+ * @param {Object|null} body - shape {message|error, errors: [{key, name, error}]}+ * @param {string} baseMessage - The generic headline the details hang off+ * @param {string[]} supersededKeys - Keys this request no longer owns+ * because a newer save took them over. Their verdict is already+ * stale, so it must reach neither the banner nor the field a newer+ * request is writing.+ */+ function renderSettingsSaveError(body, baseMessage, supersededKeys) {+ const errorDetails = formatServerSettingErrors(+ body ? body.errors : undefined+ ).filter(detail => !supersededKeys.includes(detail.key));+ const markedKeys = markInvalidSettingsFromServer(errorDetails);+ // Cap what reaches the banner: a raw-config save can reject+ // dozens of keys at once. An entry with no inline mark (the+ // key isn't rendered — hidden, rejected by the namespace+ // guard before it reaches the form, or outside the active+ // tab/search) has no other surface, so those are sorted to+ // the front and only fall off the banner past the cap.+ const orderedDetails = [...errorDetails].sort((a, b) => {+ const aMarked = markedKeys.has(a.key) ? 1 : 0;+ const bMarked = markedKeys.has(b.key) ? 1 : 0;+ return aMarked - bMarked;+ });+ const shownDetails = orderedDetails.slice(0, MAX_BANNER_SETTING_ERRORS);+ const hiddenCount = orderedDetails.length - shownDetails.length;+ let detailMessage = shownDetails+ .map(detail => detail.message)+ .join(' • ');+ if (detailMessage && hiddenCount > 0) {+ detailMessage += ` • +${hiddenCount} more`;+ }+ const fullMessage = detailMessage+ ? `${baseMessage} — ${detailMessage}`+ : baseMessage;++ // Show error message; give detailed failures a longer read window.+ // window.ui.showMessage sets textContent (not innerHTML) and+ // showAlert HTML-escapes before inserting, so fullMessage is safe+ // from XSS even though it originates from server-controlled text.+ const errorDuration = detailMessage ? 10000 : 5000;+ if (window.ui && window.ui.showMessage) {+ window.ui.showMessage(fullMessage, 'error', errorDuration);+ showAlert(fullMessage, 'error', true);+ } else {+ showAlert(fullMessage, 'error', false);+ }+ }+/*** Submit settings data to the API* @param {Object} formData - The settings to save@@ -3283,6 +3343,11 @@const getCurrentSavingKeys = () => savingKeys.filter(key => latestSettingsSaveGenerationByKey.get(key) === requestGeneration);+ // The complement: keys a newer save has taken over. Their verdict+ // from this response is already stale.+ const getSupersededKeys = () => savingKeys.filter(+ key => latestSettingsSaveGenerationByKey.get(key) !== requestGeneration+ );const clearOwnedLoadingState = () => {if (isLatestSourceRequest() && loadingContainer) {loadingContainer.classList.remove('ldr-saving');@@ -3443,6 +3508,15 @@successMessage = 'Settings saved';}+ // Clear any stale inline validation errors for keys that+ // just saved successfully and are still owned by this request.+ currentSavingKeys.forEach(key => {+ const control = findSettingControl(key);+ if (control) {+ markInvalidInput(control, null);+ }+ });+// Show banner notification if ui.showMessage is availableif (window.ui && window.ui.showMessage) {window.ui.showMessage(successMessage, 'success', 6000);@@ -3453,15 +3527,15 @@showAlert(successMessage, 'success', false);}} else {- // Show error message- if (window.ui && window.ui.showMessage) {- window.ui.showMessage(data.message || 'Error saving settings', 'error', 5000);- showAlert(data.message || 'Error saving settings', 'error', true);- } else {- showAlert(data.message || 'Error saving settings', 'error', false);- }-- // Remove loading state+ // A 2xx body that still reports failure carries the same+ // per-setting `errors` shape as the 400 the catch below+ // handles, so give it the same inline marks and banner+ // detail instead of only the flattened top-level message.+ renderSettingsSaveError(+ data,+ data.message || data.error || 'Error saving settings',+ getSupersededKeys()+ );clearOwnedLoadingState();}})@@ -3477,45 +3551,18 @@// Surface the structured per-setting details a 400// "Validation errors" response carries (error.details is- // attached by fetchWithErrorHandling). The banner spells out- // which setting failed and why; the same text also lands- // inline on the offending control so it outlives the banner.- const errorDetails = formatServerSettingErrors(- error && error.details ? error.details.errors : undefined+ // attached by fetchWithErrorHandling). save_all_settings+ // reports every failure this way — 403 locked, 400+ // egress-validation, 400 field-validation — so this is the+ // branch the remedy text actually arrives on. The banner+ // spells out which setting failed and why; the same text also+ // lands inline on the offending control so it outlives the+ // banner.+ renderSettingsSaveError(+ error && error.details ? error.details : null,+ 'Error saving settings: ' + error.message,+ getSupersededKeys());- const markedKeys = markInvalidSettingsFromServer(errorDetails);- // Cap what reaches the banner: a raw-config save can reject- // dozens of keys at once. An entry with no inline mark (the- // key isn't rendered — hidden, rejected by the namespace- // guard before it reaches the form, or outside the active- // tab/search) has no other surface, so those are sorted to- // the front and only fall off the banner past the cap.- const orderedDetails = [...errorDetails].sort((a, b) => {- const aMarked = markedKeys.has(a.key) ? 1 : 0;- const bMarked = markedKeys.has(b.key) ? 1 : 0;- return aMarked - bMarked;- });- const shownDetails = orderedDetails.slice(0, MAX_BANNER_SETTING_ERRORS);- const hiddenCount = orderedDetails.length - shownDetails.length;- let detailMessage = shownDetails- .map(detail => detail.message)- .join(' • ');- if (detailMessage && hiddenCount > 0) {- detailMessage += ` • +${hiddenCount} more`;- }- const baseMessage = 'Error saving settings: ' + error.message;- const fullMessage = detailMessage- ? `${baseMessage} — ${detailMessage}`- : baseMessage;-- // Show error message; give detailed failures a longer read window- const errorDuration = detailMessage ? 10000 : 5000;- if (window.ui && window.ui.showMessage) {- window.ui.showMessage(fullMessage, 'error', errorDuration);- showAlert(fullMessage, 'error', true);- } else {- showAlert(fullMessage, 'error', false);- }// Remove loading stateclearOwnedLoadingState();diff --git a/src/local_deep_research/web/static/js/research_form.js b/src/local_deep_research/web/static/js/research_form.jsindex b4c8f96ed9..2bbf9eec18 100644--- a/src/local_deep_research/web/static/js/research_form.js+++ b/src/local_deep_research/web/static/js/research_form.js@@ -281,6 +281,15 @@ function displayWarnings(warnings) {// Security: escapeHtml applied to API-controlled warning fields before innerHTML insertion// bearer:disable javascript_lang_manual_html_sanitizationconst esc = window.escapeHtml || (s => String(s || '').replace(/[&<>"']/g, m => ({'&':'&','<':'<','>':'>','"':'"',"'":"'"})[m]));+ // Wrap LDR_… env-var tokens (optionally with their =value) in <code> so+ // the copy-paste remedy stands out from the prose. Runs on the+ // ALREADY-ESCAPED string and only ever inserts <code> tags around+ // matched text, so it cannot introduce markup injection. A trailing+ // sentence period is excluded from the =value capture.+ const withCodeTokens = (escaped) => escaped.replace(+ /\bLDR_[A-Z0-9_]+(?:=[^\s,)]*[^\s,.)])?/g,+ m => `<code style="font-size: 13px; padding: 1px 4px; border-radius: 3px; background: rgba(127,127,127,0.15); word-break: break-all;">${m}</code>`+ );const warningsHtml = warnings.map(warning => {// Use success styling for recommendations/tips, warning for othersconst isInfo = warning.type === 'searxng_recommendation' || warning.type === 'legacy_server_config' || warning.type === 'backup_info';@@ -329,7 +338,7 @@ function displayWarnings(warnings) {${esc(warning.title)}</div><div style="font-size: 14px; line-height: 1.4;">- ${esc(warning.message)}+ ${withCodeTokens(esc(warning.message))}</div>${actionHtml}</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.htmlindex 40ccc02656..db6f0b0503 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@@ -334,9 +334,11 @@ async function loadSearchEngines() {if (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.+ // the research.js loader uses). An option without an egress+ // field is left enabled. Note that a denial can arrive even+ // on an unprotected / no-scope response: the guarded+ // engine-URL overlay is scope-independent, so it stamps+ // `private_url_unapproved` on every variant of the payload.searchEngineOptions = data.engine_options.map((engine) => {const egress = engine.egress;const isDenied = !!egress && egress.allowed === false;@@ -360,6 +362,16 @@ async function loadSearchEngines() {case 'engine_denied':disabledReason = `Blocked: ${display} is denied by the egress policy`;break;+ case 'private_url_unapproved':+ // Same wording as research.js. Deliberately not+ // "see the warning banner": that banner is+ // suppressed once dismissed, and it comes from+ // the same DNS-free check as this overlay, so it+ // stays silent on exactly the URLs the overlay+ // misses. Name the operator-side remedy rather+ // than the egress policy, which did not deny it.+ disabledReason = `Disabled: ${display}'s private instance URL needs server-operator approval (env-only: allow private IPs, add the origin to search.private_engine_url_allowlist, or env-lock the engine's URL setting)`;+ break;default:disabledReason = `Blocked by egress policy (${egress.reason})`;break;diff --git a/tests/js/components/logpanel-error-indicator.test.js b/tests/js/components/logpanel-error-indicator.test.jsnew file mode 100644index 0000000000..4db6d92acc--- /dev/null+++ b/tests/js/components/logpanel-error-indicator.test.js@@ -0,0 +1,317 @@+/**+ * Tests for the log-panel header badge's ERROR severity signal+ * (`.ldr-log-indicator--has-error`), added by PR #5648 and corrected in+ * its follow-up.+ *+ * All three defects below were introduced and corrected inside this branch;+ * none of them reached main. There was no JS test for the log panel's badge,+ * which is why they survived several revisions of the branch. Each `it` below+ * names the defect it pins:+ *+ * 1. The badge selected on the RAW level (`[data-log-type="error"]`),+ * but the repo's normalizer folds CRITICAL/FATAL into the `error`+ * display category (utils/log-helpers.js). A CRITICAL row therefore+ * left the badge purple and titleless while the "Error" FILTER badge+ * counted it — the panel disagreeing with itself, on precisely the+ * two severities the signal exists for.+ * 2. The badge counted only entries currently in the DOM. The header+ * number is deliberately floored to the server-known `fetched` count+ * because the DOM holds fewer rows, so the badge could report a full+ * count with no severity for a run whose errors had been paged out+ * or pruned. The count is now a per-research high-water mark, and+ * the tooltip says "at least N" while the view is truncated.+ * 3. Two other writers of the indicator's textContent (`initializeLogPanel`+ * and `recomputeCountersFromDom`) never cleared the error class or+ * the title, so a re-init or a recompute could repaint a fresh count+ * under a stale red badge. All writers now go through+ * `paintLogIndicators`.+ *+ * Plus the accessibility contract: colour alone must not carry the state,+ * and the explanation must not be hover-only (role + aria-label).+ */++let logPanel;+let emptyCounts;++beforeAll(async () => {+ await import('@js/utils/log-helpers.js');+ emptyCounts = window.LdrLogHelpers.emptyCounts;++ window.escapeHtml = (s) => String(s ?? '').replace(/[&<>"']/g, '');+ window.URLBuilder = {+ researchLogs: (id, limit) =>+ `/api/research/${id}/logs${limit ? `?limit=${limit}` : ''}`,+ historyLogCount: (id) => `/api/research/${id}/log_count`,+ researchLogsExport: (id) => `/api/research/${id}/logs/export`,+ };++ Object.defineProperty(window, 'location', {+ configurable: true,+ value: { ...window.location, pathname: '/', search: '', hash: '' },+ });++ await import('@js/components/logpanel.js');+ logPanel = window.logPanel;+});++beforeEach(() => {+ // The #research-progress wrapper makes initializeLogPanel treat this+ // as a research page — without it the init path bails before it+ // paints the indicator, and the two re-init tests below would pass+ // vacuously.+ document.body.innerHTML = `+ <div id="research-progress">+ <div class="ldr-collapsible-log-panel">+ <div class="ldr-log-panel-header" id="log-panel-toggle">+ <i class="ldr-toggle-icon"></i>+ <span class="ldr-log-indicator" id="log-indicator">0</span>+ </div>+ <div class="ldr-log-panel-content collapsed" id="log-panel-content">+ <div class="ldr-console-log" id="console-log-container"></div>+ </div>+ </div>+ </div>+ `;+ window._logPanelState.counts = emptyCounts();+ window._logPanelState.renderedIds = new Set();+ window._logPanelState.currentFilter = 'all';+ window._logPanelState.totalLogs = null;+ window._logPanelState.fetchedLogs = null;+ window._logPanelState.renderedLimit = null;+ window._logPanelState.errorHighWater = 0;+ window._logPanelState.initialized = false;+ window._logPanelState.connectedResearchId = null;++ // initializeLogPanel pre-fetches logs (and the row count) for a+ // non-null research id; stub both so the tests never touch the+ // network and never leave an unhandled rejection behind.+ globalThis.fetch = vi.fn(() =>+ Promise.resolve({ ok: true, json: () => Promise.resolve([]) })+ );+});++/** Append one rendered row of the given RAW severity to the container. */+function seed(rawLevel, message = `msg-${rawLevel}`) {+ const container = document.getElementById('console-log-container');+ const entry = document.createElement('div');+ entry.className = `ldr-console-log-entry ldr-log-${rawLevel}`;+ entry.dataset.logType = rawLevel;+ entry.dataset.logId = `${rawLevel}-${message}`;+ const span = document.createElement('span');+ span.className = 'ldr-log-message';+ span.textContent = message;+ entry.appendChild(span);+ container.appendChild(entry);+ return entry;+}++function badge() {+ return document.querySelector('.ldr-log-indicator');+}++describe('header badge severity — display-category normalization', () => {+ // Defect 1. Before the fix the selector was+ // '[data-log-type="error"], .ldr-log-error'+ // which matches neither of these rows, so both assertions failed.+ it.each(['critical', 'fatal'])(+ 'turns red for a %s entry (folded into the error category)',+ (level) => {+ seed(level);+ logPanel._updateLogCountIndicator();++ expect(+ badge().classList.contains('ldr-log-indicator--has-error')+ ).toBe(true);+ expect(badge().title).toContain('1 error');+ }+ );++ it('turns red for a plain error entry', () => {+ seed('error');+ logPanel._updateLogCountIndicator();+ expect(+ badge().classList.contains('ldr-log-indicator--has-error')+ ).toBe(true);+ });++ it('stays neutral — no class, no title, no ARIA — with no errors', () => {+ seed('info');+ seed('warning');+ seed('milestone');+ logPanel._updateLogCountIndicator();++ expect(+ badge().classList.contains('ldr-log-indicator--has-error')+ ).toBe(false);+ expect(badge().title).toBe('');+ expect(badge().hasAttribute('role')).toBe(false);+ expect(badge().hasAttribute('aria-label')).toBe(false);+ });++ it('counts critical and error together, matching the Error filter badge', () => {+ seed('error', 'a');+ seed('critical', 'b');+ seed('fatal', 'c');+ seed('info', 'd');+ logPanel._updateLogCountIndicator();+ expect(badge().title).toContain('3 errors');+ });+});++describe('header badge severity — entries outside the rendered window', () => {+ // Defect 2. The engine-self-disable ERROR this feature exists to+ // surface is emitted at init, so it is the row most likely to be+ // dropped from the fetched window or evicted by the ordered prune.+ it('keeps the signal after the error row leaves the DOM', () => {+ const errorRow = seed('error');+ seed('info');+ logPanel._updateLogCountIndicator();+ expect(+ badge().classList.contains('ldr-log-indicator--has-error')+ ).toBe(true);++ // The row is paged out / pruned; only routine rows remain.+ errorRow.remove();+ logPanel._updateLogCountIndicator();++ expect(+ badge().classList.contains('ldr-log-indicator--has-error')+ ).toBe(true);+ expect(window._logPanelState.errorHighWater).toBe(1);+ });++ it('words the tooltip as a lower bound while the view is truncated', () => {+ seed('error');+ // The server holds far more rows than the DOM renders.+ window._logPanelState.totalLogs = 9002;+ window._logPanelState.fetchedLogs = 500;+ logPanel._updateLogCountIndicator();++ expect(badge().title).toContain('at least 1 error');+ // The number itself is still the floored server count, unchanged+ // by the severity work.+ expect(badge().textContent).toBe('500');+ });++ it('does not claim a lower bound when the DOM holds everything', () => {+ seed('error');+ window._logPanelState.totalLogs = 1;+ window._logPanelState.fetchedLogs = 1;+ logPanel._updateLogCountIndicator();++ expect(badge().title).toContain('1 error');+ expect(badge().title).not.toContain('at least');+ });++ it('does not carry the previous research’s errors across a switch', () => {+ seed('error');+ logPanel._updateLogCountIndicator();+ expect(window._logPanelState.errorHighWater).toBe(1);++ // Research switch: initializeLogPanel resets the per-research state.+ document.getElementById('console-log-container').innerHTML = '';+ logPanel.initialize('research-b');++ expect(window._logPanelState.errorHighWater).toBe(0);+ expect(+ badge().classList.contains('ldr-log-indicator--has-error')+ ).toBe(false);+ });+});++describe('header badge severity — every writer clears the state', () => {+ // Defect 3. initializeLogPanel and recomputeCountersFromDom wrote+ // textContent directly and left the class/title untouched, so a badge+ // that had legitimately gone red for research A kept its colour and+ // tooltip under B's count.+ it('recomputeCountersFromDom clears a stale red badge', () => {+ badge().classList.add('ldr-log-indicator--has-error');+ badge().title = 'stale tooltip from a previous paint';+ badge().setAttribute('role', 'img');+ badge().setAttribute('aria-label', 'stale');++ seed('info');+ logPanel._recomputeCountersFromDom();++ expect(+ badge().classList.contains('ldr-log-indicator--has-error')+ ).toBe(false);+ expect(badge().title).toBe('');+ expect(badge().hasAttribute('aria-label')).toBe(false);+ });++ it('initializeLogPanel clears a stale red badge', () => {+ badge().classList.add('ldr-log-indicator--has-error');+ badge().title = 'stale tooltip from a previous paint';++ // No researchId → no count fetch, just the synchronous "0" paint.+ logPanel.initialize(null);++ expect(+ badge().classList.contains('ldr-log-indicator--has-error')+ ).toBe(false);+ expect(badge().title).toBe('');+ });+});++describe('header badge severity — accessibility', () => {+ // The blocked state was conveyed by colour alone (--error-color vs+ // --accent-primary: two similar-luminance mid-tones, both with white+ // text) and the explanation lived only in a hover `title` on a bare+ // span. The glyph lives in CSS (::after) so textContent stays a bare+ // number for updateFilterCounters; the text alternative lives here.+ it('exposes the severity to assistive tech, not just on hover', () => {+ seed('critical');+ logPanel._updateLogCountIndicator();++ expect(badge().getAttribute('role')).toBe('img');+ const label = badge().getAttribute('aria-label');+ expect(label).toContain('log entries');+ expect(label).toContain('1 error');+ });++ it('keeps textContent a bare number so the All badge can parse it', () => {+ seed('error');+ seed('info');+ logPanel._updateLogCountIndicator();+ expect(badge().textContent).toBe('2');+ expect(badge().textContent).not.toContain('!');+ });+});++describe('header badge severity — a header without a console container', () => {+ // The success paths all repaint through recomputeCountersFromDom on the+ // emptied container, so only a DOM that has the indicator but not the+ // container isolates initializeLogPanel's own paint. Reverting that+ // call leaves the previous research's red badge, tooltip and ARIA label+ // sitting under a stale count.+ it('repaints the badge on init when the container is absent', () => {+ document.body.innerHTML = `+ <div id="research-progress">+ <div class="ldr-collapsible-log-panel">+ <div class="ldr-log-panel-header" id="log-panel-toggle">+ <i class="ldr-toggle-icon"></i>+ <span class="ldr-log-indicator" id="log-indicator">7</span>+ </div>+ <div class="ldr-log-panel-content collapsed" id="log-panel-content"></div>+ </div>+ </div>+ `;+ expect(document.getElementById('console-log-container')).toBeNull();++ badge().classList.add('ldr-log-indicator--has-error');+ badge().title = 'at least 7 errors in this research';+ badge().setAttribute('role', 'img');+ badge().setAttribute('aria-label', '7 log entries, at least 7 errors');++ // No researchId → no count fetch, just the synchronous "0" paint.+ logPanel.initialize(null);++ expect(badge().textContent).toBe('0');+ expect(+ badge().classList.contains('ldr-log-indicator--has-error')+ ).toBe(false);+ expect(badge().title).toBe('');+ expect(badge().hasAttribute('aria-label')).toBe(false);+ });+});diff --git a/tests/js/components/research-api-runtime.test.js b/tests/js/components/research-api-runtime.test.jsindex aefa5442aa..a5dc718b0a 100644--- a/tests/js/components/research-api-runtime.test.js+++ b/tests/js/components/research-api-runtime.test.js@@ -686,3 +686,27 @@ it('surfaces a rejected chat-session detail and leaves the form retryable', asynbody: JSON.stringify({ initial_query: 'A current research query' }),}));});++it('anchors the custom-model hint under ldr-prefixed research markup', async () => {+ // The research page wraps the model dropdown in `.ldr-form-group` only.+ // Reverting the prefixed selector makes `closest('.form-group')` return+ // null, and the warning element is built and then dropped on the floor.+ document.getElementById('custom-model-warning')?.remove();+ const wrapper = document.getElementById('model-dropdown').parentElement;+ wrapper.className = 'ldr-form-group';+ try {+ expect(wrapper.closest('.form-group')).toBeNull();++ dropdowns.get('model').onSelect('a-model-not-in-the-list', null);++ await vi.waitFor(() => {+ expect(document.getElementById('custom-model-warning')).not.toBeNull();+ });+ const warning = document.getElementById('custom-model-warning');+ expect(warning.parentElement).toBe(wrapper);+ expect(warning.textContent).toContain('Custom model name entered');+ expect(warning.style.display).toBe('block');+ } finally {+ wrapper.className = 'form-group';+ }+});diff --git a/tests/js/components/settings-submit-runtime.test.js b/tests/js/components/settings-submit-runtime.test.jsindex a9b74fb763..7586f7f58d 100644--- a/tests/js/components/settings-submit-runtime.test.js+++ b/tests/js/components/settings-submit-runtime.test.js@@ -588,3 +588,202 @@ it('keeps a newer success state when an older same-key request rejects', async (app: expect.objectContaining({ theme: 'newer-saved' }),}));});+++function wrapThemeSetting() {+ const input = document.getElementById('app-theme');+ const item = document.createElement('div');+ item.className = 'ldr-settings-item';+ item.dataset.key = 'app.theme';+ input.before(item);+ item.appendChild(input);+ return {+ input,+ item,+ restore: () => {+ item.before(input);+ input.classList.remove('ldr-settings-error');+ item.remove();+ },+ };+}++it('shows validation details inline and clears them after a successful save', async () => {+ // Reverting structured error forwarding loses the inline remedy and toast.+ const field = wrapThemeSetting();+ try {+ const fetchMock = vi.fn()+ .mockResolvedValueOnce(jsonResponse({+ message: 'Validation errors',+ errors: [{ key: 'app.theme', error: 'Choose a supported theme <literal>' }],+ }, 400))+ .mockResolvedValueOnce(jsonResponse({ status: 'success' }));+ vi.stubGlobal('fetch', fetchMock);+ submitSettingsForm();+ await flushPromises();+ expect(field.item.querySelector('.ldr-settings-error-message').textContent)+ .toBe('Choose a supported theme <literal>');+ expect(field.item.querySelector('literal')).toBeNull();+ expect(window.ui.showMessage).toHaveBeenLastCalledWith(+ 'Error saving settings: Validation errors — app.theme: Choose a supported theme <literal>',+ 'error',+ 10000,+ );+ submitSettingsForm();+ await flushPromises();+ expect(field.item.querySelector('.ldr-settings-error-message')).toBeNull();+ expect(field.input.classList).not.toContain('ldr-settings-error');+ } finally {+ field.restore();+ }+});++it('limits partial bulk-save errors to owned keys and preserves the newer spinner', async () => {+ // Reverting per-key filtering paints the stale theme error; clearing the+ // container directly removes the spinner belonging to the queued save.+ const field = wrapThemeSetting();+ const older = deferred();+ const newer = deferred();+ const fetchMock = vi.fn()+ .mockImplementationOnce(() => older.promise)+ .mockImplementationOnce(() => newer.promise);+ vi.stubGlobal('fetch', fetchMock);+ try {+ const rawEditor = document.getElementById('raw_config_editor');+ rawEditor.value = JSON.stringify({ app: { theme: 'older', extra: 'invalid' } });+ submitSettingsForm();+ rawEditor.value = JSON.stringify({ app: { theme: 'newer' } });+ submitSettingsForm();+ expect(fetchMock).toHaveBeenCalledOnce();+ older.resolve(jsonResponse({+ message: 'Validation errors',+ errors: [+ { key: 'app.theme', error: 'Stale theme rejection' },+ { key: 'app.extra', error: 'Current extra rejection' },+ ],+ }, 400));+ await flushPromises();+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(field.item.querySelector('.ldr-settings-error-message')).toBeNull();+ expect(window.ui.showMessage).toHaveBeenLastCalledWith(+ 'Error saving settings: Validation errors — app.extra: Current extra rejection',+ 'error',+ 10000,+ );+ expect(document.getElementById('settings-form').classList).toContain('ldr-saving');+ newer.resolve(jsonResponse({ status: 'success' }));+ await flushPromises();+ expect(document.getElementById('settings-form').classList).not.toContain('ldr-saving');+ } finally {+ older.resolve(jsonResponse({ status: 'success' }));+ newer.resolve(jsonResponse({ status: 'success' }));+ await flushPromises();+ field.restore();+ }+});++function wrapEnabledSetting() {+ const checkbox = document.getElementById('app-enabled');+ const item = document.createElement('div');+ item.className = 'ldr-settings-item';+ item.dataset.key = 'app.enabled';+ checkbox.before(item);+ // Mirrors components/settings_form.html: the unchecked-state fallback+ // is a hidden input rendered ahead of the visible checkbox.+ const fallback = document.createElement('input');+ fallback.type = 'hidden';+ fallback.name = 'app.enabled';+ fallback.value = 'false';+ fallback.className = 'ldr-checkbox-hidden-fallback';+ item.appendChild(fallback);+ item.appendChild(checkbox);+ return {+ checkbox,+ fallback,+ item,+ restore: () => {+ item.before(checkbox);+ checkbox.classList.remove('ldr-settings-error');+ item.remove();+ },+ };+}++it('clears a field error on a save path that never pre-cleared', async () => {+ // The submit handler wipes every inline error before it fetches, so a+ // submit-driven assertion passes with the success-path clear removed.+ // Hiding the raw editor saves through submitSettingsData directly and+ // pre-clears nothing, so this is the path where reverting the+ // success-path clear leaves a stale remedy under a field that just saved.+ const field = wrapThemeSetting();+ try {+ const fetchMock = vi.fn()+ .mockResolvedValueOnce(jsonResponse({+ message: 'Validation errors',+ errors: [{ key: 'app.theme', error: 'Choose a supported theme' }],+ }, 400))+ .mockResolvedValueOnce(jsonResponse({ status: 'success' }));+ vi.stubGlobal('fetch', fetchMock);++ submitSettingsForm();+ await flushPromises();+ expect(field.item.querySelector('.ldr-settings-error-message').textContent)+ .toBe('Choose a supported theme');+ expect(field.input.classList).toContain('ldr-settings-error');++ document.getElementById('raw_config_editor').value = JSON.stringify({+ app: { theme: 'dark' },+ });+ document.getElementById('toggle-raw-config').click();+ await flushPromises();++ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(JSON.parse(fetchMock.mock.calls[1][1].body))+ .toEqual({ 'app.theme': 'dark' });+ expect(field.item.querySelector('.ldr-settings-error-message')).toBeNull();+ expect(field.input.classList).not.toContain('ldr-settings-error');+ } finally {+ field.restore();+ }+});++it('borders the visible checkbox rather than its hidden fallback', async () => {+ // Reverting the visible-control selector marks the hidden input, whose+ // only error style is a border-color nothing can render, so a rejected+ // checkbox setting shows the message with no field highlighted.+ const field = wrapEnabledSetting();+ try {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({+ message: 'Validation errors',+ errors: [{ key: 'app.enabled', error: 'Enabling needs a licence' }],+ }, 400)));++ submitSettingsForm();+ await flushPromises();++ expect(field.checkbox.classList).toContain('ldr-settings-error');+ expect(field.fallback.classList).not.toContain('ldr-settings-error');+ expect(field.item.querySelector('.ldr-settings-error-message').textContent)+ .toBe('Enabling needs a licence');+ } finally {+ field.restore();+ }+});++it('falls back to a top-level error field when the body carries no message', async () => {+ // api.js already reads `error` alongside `message`; without the same+ // fallback here a body shaped {error: ...} rendered "Error saving+ // settings" and dropped the server's wording.+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({+ error: 'Engine URL rejected by the private-URL guard',+ }, 400)));++ submitSettingsForm();+ await flushPromises();++ expect(window.ui.showMessage).toHaveBeenLastCalledWith(+ 'Error saving settings: Engine URL rejected by the private-URL guard',+ 'error',+ 5000,+ );+});diff --git a/tests/js/pages/news-subscription-engine-egress-runtime.test.js b/tests/js/pages/news-subscription-engine-egress-runtime.test.jsnew file mode 100644index 0000000000..18ae75e457--- /dev/null+++ b/tests/js/pages/news-subscription-engine-egress-runtime.test.js@@ -0,0 +1,172 @@+/**+ * Runtime contract for the news subscription form's engine picker.+ *+ * The checked-in inline `loadSearchEngines` is extracted from the template+ * and executed, so the reason text the browser renders is asserted against+ * the shipped source rather than a copy of it.+ */++import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++const TEMPLATE_PATH = resolve(+ __dirname,+ '../../../src/local_deep_research/web/templates/pages/news-subscription-form.html',+);+const RESEARCH_JS_PATH = resolve(+ __dirname,+ '../../../src/local_deep_research/web/static/js/components/research.js',+);++// The one operator-remedy sentence both pickers must render for a+// guard-blocked private instance URL. This is the shipped template+// literal as it appears in the source, matched verbatim.+const PRIVATE_URL_REMEDY_LITERAL =+ // eslint-disable-next-line no-template-curly-in-string -- source text, not a format string.+ '`Disabled: ${display}\'s private instance URL needs server-operator '+ + 'approval (env-only: allow private IPs, add the origin to '+ + 'search.private_engine_url_allowlist, or env-lock the engine\'s URL '+ + 'setting)`';++function extractFunction(source, name) {+ const signature = new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\(`);+ const match = signature.exec(source);+ if (!match) throw new Error(`Function ${name} not found in template`);++ const openBrace = source.indexOf('{', match.index + match[0].length);+ let depth = 0;+ for (let index = openBrace; index < source.length; index += 1) {+ if (source[index] === '{') depth += 1;+ if (source[index] === '}') {+ depth -= 1;+ if (depth === 0) return source.slice(match.index, index + 1);+ }+ }++ throw new Error(`Function ${name} has an unterminated body`);+}++function renderLoaderJinja(source, scope, primary) {+ const rendered = source+ .replace(+ /\{\{\s*\(default_settings\.egress_scope or "adaptive"\)\s*\|\s*tojson\s*\}\}/g,+ JSON.stringify(scope),+ )+ .replace(+ /\{\{\s*\(subscription\.search_engine if subscription else default_settings\.search_engine\)\s*\|\s*tojson\s*\}\}/g,+ JSON.stringify(primary),+ );++ if (/\{[{%]/.test(rendered)) {+ throw new Error('Unhandled Jinja remains in loadSearchEngines');+ }+ return rendered;+}++function compileLoader(scope, primary) {+ const template = readFileSync(TEMPLATE_PATH, 'utf8');+ const body = renderLoaderJinja(+ extractFunction(template, 'loadSearchEngines'),+ scope,+ primary,+ );+ // The extracted source is repository-owned production code from the+ // template above, not user-controlled input.+ const factory = new Function( // eslint-disable-line no-new-func+ 'console',+ `let searchEngineOptions = [];\n${body}\n`+ + 'return { loadSearchEngines, mapped: () => searchEngineOptions };',+ );+ return factory({ error: () => {}, log: () => {}, warn: () => {} });+}++async function mapEngineOptions(engineOptions, scope = 'adaptive') {+ const fetchMock = vi.fn(() => Promise.resolve({+ ok: true,+ json: () => Promise.resolve({ engine_options: engineOptions }),+ }));+ vi.stubGlobal('fetch', fetchMock);+ const loader = compileLoader(scope, 'searxng');+ await loader.loadSearchEngines();+ return { mapped: loader.mapped(), requestedUrl: fetchMock.mock.calls[0][0] };+}++beforeEach(() => {+ document.body.innerHTML =+ '<input type="hidden" id="subscription-search-engine" value="searxng">';+ window.updateDropdownOptions = vi.fn();+});++afterEach(() => {+ vi.unstubAllGlobals();+ delete window.updateDropdownOptions;+ document.body.replaceChildren();+});++it('names the operator remedy for a guard-blocked private instance URL', async () => {+ // Reverting the `private_url_unapproved` case drops this option into+ // `default:`, which renders the raw internal token and blames the+ // egress policy for a refusal the egress policy did not make.+ const { mapped } = await mapEngineOptions([+ {+ value: 'searxng',+ label: 'SearXNG',+ egress: { allowed: false, reason: 'private_url_unapproved' },+ },+ ]);++ expect(mapped[0].disabled).toBe(true);+ expect(mapped[0].disabled_reason).toBe(+ "Disabled: SearXNG's private instance URL needs server-operator "+ + 'approval (env-only: allow private IPs, add the origin to '+ + "search.private_engine_url_allowlist, or env-lock the engine's URL "+ + 'setting)',+ );+ expect(mapped[0].disabled_reason).not.toContain('egress policy');+ expect(mapped[0].disabled_reason).not.toContain('private_url_unapproved');+});++it('renders the same remedy sentence as the research picker', () => {+ // The two pickers hold separate copies of the switch; this pins them+ // to one wording so a future edit cannot fix only one surface.+ expect(readFileSync(TEMPLATE_PATH, 'utf8'))+ .toContain(PRIVATE_URL_REMEDY_LITERAL);+ expect(readFileSync(RESEARCH_JS_PATH, 'utf8'))+ .toContain(PRIVATE_URL_REMEDY_LITERAL);+});++it('grays the engine out even when the request carries no scope filter', async () => {+ // The guarded engine-URL overlay is scope-independent, so the+ // unprotected (unfiltered) payload can carry a denial too.+ const { mapped, requestedUrl } = await mapEngineOptions(+ [+ {+ value: 'searxng',+ label: 'SearXNG',+ egress: { allowed: false, reason: 'private_url_unapproved' },+ },+ ],+ 'unprotected',+ );++ expect(requestedUrl).toBe('/settings/api/available-search-engines');+ expect(mapped[0].disabled).toBe(true);+ expect(mapped[0].disabled_reason).toContain('server-operator approval');+});++it('keeps the generic fallback for a reason it does not recognize', async () => {+ const { mapped } = await mapEngineOptions([+ {+ value: 'brave',+ label: 'Brave',+ egress: { allowed: false, reason: 'some_future_reason' },+ },+ { value: 'library', label: 'Library' },+ ]);++ expect(mapped[0].disabled).toBe(true);+ expect(mapped[0].disabled_reason)+ .toBe('Blocked by egress policy (some_future_reason)');+ expect(mapped[1].disabled).toBe(false);+ expect(mapped[1].disabled_reason).toBeNull();+});diff --git a/tests/web/routes/test_available_search_engines_scope.py b/tests/web/routes/test_available_search_engines_scope.pyindex e417defbf8..6c938d12dd 100644--- a/tests/web/routes/test_available_search_engines_scope.py+++ b/tests/web/routes/test_available_search_engines_scope.py@@ -1,11 +1,11 @@"""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.+Without ``?egress_scope=`` (or under ``unprotected``), only options+blocked by the DNS-free private-URL advisory receive an ``egress`` field.+When the caller opts into scope filtering, every option gets an+``egress: {allowed, reason}`` field from the request-boundary policy,+then the same URL advisory can add a denial.The tests below stub the engine-class flag lookups inside``policy`` (``_get_engine_class`` and ``_engine_flags``) so they@@ -19,6 +19,7 @@ of the mocked flags, so this still exercises the full helper path.import pytestfrom local_deep_research.web.routers.settings import (+ _apply_guarded_url_overlay,_classify_options_for_egress,)@@ -59,6 +60,7 @@ def _snap(scope="adaptive", primary="arxiv"):_FLAGS = {"arxiv": (True, False), # public web engine"github": (True, False), # public code search+ "searxng": (True, False), # public metasearch (guarded URL)"library": None, # real path: collection/library branch"collection_x": None, # real path: collection branch}@@ -79,6 +81,21 @@ def _fake_engine_class(engine_name):return _Fake[email protected](autouse=True)+def _fresh_guarded_descriptor_cache():+ """The guarded-URL overlay sweeps the engine registry through the+ (monkeypatched) ``_get_engine_class`` and caches the result — clear it+ on both sides so a sweep taken under the stub can never leak real-+ registry expectations into other test files (or vice versa)."""+ from local_deep_research.security.egress import validators++ validators.guarded_engine_url_descriptors.cache_clear()+ validators._public_engine_url_settings.cache_clear()+ yield+ validators.guarded_engine_url_descriptors.cache_clear()+ validators._public_engine_url_settings.cache_clear()++@pytest.fixturedef stub_engine_flags(monkeypatch):"""Make _get_engine_class return a deterministic fake for the@@ -335,12 +352,22 @@ class TestApiAvailableSearchEnginesEndpoint:assert "engine_options" in dataoptions = data["engine_options"]+ # Guard against a vacuous pass. ``any`` is not enough: the guarded+ # engine-URL overlay stamps ``egress`` on SearXNG on EVERY response,+ # scope opt-in or not, so ``any`` holds even when the PDP pass never+ # ran. The PDP pass stamps every option unconditionally, so ``all``+ # is what actually proves it ran.+ assert all("egress" in o for o in options), (+ "not every option carried an egress decision — the scope opt-in "+ "did not run, so the per-engine assertions below are vacuous"+ )+# Local library option is allowedlib = next((o for o in options if o.get("value") == "library"), None)- if lib and "egress" in lib:- assert lib["egress"]["allowed"] is True+ assert lib is not None, "library option missing from the dropdown"+ assert lib["egress"]["allowed"] is True- # Public engines (if present) are marked as denied under private_only+ # Public engines are marked as denied under private_onlypublic_engine = next((o@@ -349,12 +376,14 @@ class TestApiAvailableSearchEnginesEndpoint:),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"- )+ assert public_engine is not None, (+ "no public engine in the dropdown — the denial assertion below "+ "would not be exercised"+ )+ 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@@ -367,14 +396,38 @@ class TestApiAvailableSearchEnginesEndpoint:assert "engine_options" in dataoptions = data["engine_options"]+ # ``all``, not ``any``: the guarded engine-URL overlay stamps+ # ``egress`` on SearXNG unconditionally, so ``any`` would hold even+ # if the scope opt-in never ran (see the private_only test above).+ assert all("egress" in o for o in options), (+ "not every option carried an egress decision — the scope opt-in "+ "did not run, so the per-engine assertion below is vacuous"+ )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"+ assert lib is not None, "library option missing from the dropdown"+ 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+ def test_adaptive_and_strict_scopes_skip_scope_filtering_but_keep_guard(+ self, authenticated_client, monkeypatch):+ """Scope filtering is still skipped outside private_only /+ public_only — but the guarded engine-URL overlay is NOT, because+ the guard it mirrors ignores ``policy.egress_scope`` entirely.++ This previously asserted ``len(denied) == 0``, which pinned the+ very hole that made the feature dead on a default install: the+ shipped default scope is ``adaptive``, so the overlay never ran+ where it mattered. The corrected contract is "no SCOPE denials,+ guard denials allowed".+ """+ for var in (+ "LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS",+ "LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST",+ "LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL",+ ):+ monkeypatch.delenv(var, raising=False)+for scope in ("adaptive", "strict", "unprotected"):res = authenticated_client.get(f"/settings/api/available-search-engines?egress_scope={scope}"@@ -382,11 +435,299 @@ class TestApiAvailableSearchEnginesEndpoint:assert res.status_code == 200data = res.get_json()options = data.get("engine_options", [])- # Under adaptive, strict, or unprotected, dropdown filtering is skipped- # so no engines carry egress.allowed = Falsedenied = [ofor o in optionsif o.get("egress", {}).get("allowed") is False]- assert len(denied) == 0+ # No engine is denied for SCOPE reasons: the PDP pass is+ # skipped for these scopes, so the only denial the response+ # may carry is the scope-independent URL guard.+ assert all(+ o["egress"]["reason"] == "private_url_unapproved"+ for o in denied+ ), [o["egress"] for o in denied]++ # ...and the guard IS applied: the shipped SearXNG default is+ # http://localhost:8080, which no approval env covers here, so+ # it must read as disabled rather than silently self-disabling+ # at run time. Skipped only if this build has no SearXNG.+ searxng = next(+ (o for o in options if o.get("value") == "searxng"), None+ )+ if searxng is not None:+ assert "egress" in searxng, (+ "the guarded-URL overlay did not run under "+ f"egress_scope={scope}"+ )+ assert searxng["egress"] == {+ "allowed": False,+ "reason": "private_url_unapproved",+ }++ def test_unfiltered_response_still_carries_the_url_guard(+ self, authenticated_client, monkeypatch+ ):+ """No ``?egress_scope=`` at all — the request a default install+ actually makes, since ``getCurrentEgressScopeForDropdown`` returns+ null for every scope but private_only / public_only. Would FAIL+ before the fix: the overlay was inside the opt-in branch."""+ for var in (+ "LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS",+ "LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST",+ "LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL",+ ):+ monkeypatch.delenv(var, raising=False)++ res = authenticated_client.get("/settings/api/available-search-engines")+ assert res.status_code == 200+ options = res.get_json().get("engine_options", [])+ searxng = next(+ (o for o in options if o.get("value") == "searxng"), None+ )+ if searxng is None:+ pytest.skip("SearXNG not present in this build's engine config")+ assert searxng["egress"] == {+ "allowed": False,+ "reason": "private_url_unapproved",+ }+ # Engines the guard does not cover keep the historical shape.+ others = [+ o for o in options if o.get("value") != "searxng" and "egress" in o+ ]+ assert others == []+++class TestGuardedUrlOverlay:+ """The private-URL guard grays out a blocked engine in the dropdown.++ The overlay reuses the warning-banner check verbatim, so the dropdown+ and the banner can never disagree: an unapproved private instance URL+ means the engine would silently self-disable at runtime, and the+ option must say so instead of being selectable.++ It is ADVISORY, not authoritative. The banner check is DNS-free by+ design, so it is a strict SUBSET of what the runtime's ``validate_url``+ blocks — the overlay can fail open (an engine stays selectable and is+ refused later) but never fails closed. The two "advisory gap" tests+ below pin that, and the scope-independence tests pin that it fires+ under every egress scope rather than only ``public_only``.+ """++ APPROVAL_ENVS = (+ "LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS",+ "LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST",+ "LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL",+ )+ URL_KEY = "search.engine.web.searxng.default_params.instance_url"++ def _clear(self, monkeypatch):+ for var in self.APPROVAL_ENVS:+ monkeypatch.delenv(var, raising=False)++ def _classify(self, snap, scope="public_only", primary="searxng"):+ options = [_option("searxng")]+ _classify_options_for_egress(+ options,+ egress_scope=scope,+ primary_engine=primary,+ settings_snapshot=snap,+ username="user",+ )+ return options[0]++ def test_unapproved_private_url_disables_option(+ self, stub_engine_flags, monkeypatch+ ):+ self._clear(monkeypatch)+ snap = _snap(scope="public_only", primary="searxng")+ snap[self.URL_KEY] = "http://localhost:8080"+ opt = self._classify(snap)+ assert opt["egress"]["allowed"] is False+ assert opt["egress"]["reason"] == "private_url_unapproved"++ def test_allowlisted_private_url_stays_enabled(+ self, stub_engine_flags, monkeypatch+ ):+ self._clear(monkeypatch)+ monkeypatch.setenv(+ "LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST",+ "http://localhost:8080",+ )+ snap = _snap(scope="public_only", primary="searxng")+ snap[self.URL_KEY] = "http://localhost:8080"+ opt = self._classify(snap)+ assert opt["egress"]["allowed"] is True++ def test_public_url_is_untouched(self, stub_engine_flags, monkeypatch):+ self._clear(monkeypatch)+ snap = _snap(scope="public_only", primary="searxng")+ snap[self.URL_KEY] = "https://searx.example.com"+ opt = self._classify(snap)+ assert opt["egress"]["allowed"] is True++ # ------------------------------------------------------------------+ # Scope independence (PR #5648 follow-up, P0).+ #+ # ``resolve_engine_allow_private_ips`` deliberately ignores+ # ``policy.egress_scope`` (a user-editable dropdown would otherwise be+ # a self-service SSRF bypass), so the runtime refuses the URL under+ # EVERY scope. The overlay must therefore fire under every scope too.+ # Before the fix it lived inside the ``apply_egress_filter`` branch:+ # under ``private_only`` a public engine is already denied for scope+ # reasons and the overlay skipped it, and every other scope skipped+ # the branch entirely — so it could only ever fire under+ # ``public_only``, i.e. never on the shipped ``adaptive`` default.+ # ------------------------------------------------------------------++ @pytest.mark.parametrize("scope", ["adaptive", "strict", "unprotected"])+ def test_overlay_fires_under_every_scope(+ self, stub_engine_flags, monkeypatch, scope+ ):+ """Would FAIL before the fix for adaptive/strict/unprotected: the+ overlay only ran when the caller opted into scope filtering."""+ self._clear(monkeypatch)+ snap = _snap(scope=scope, primary="searxng")+ snap[self.URL_KEY] = "http://localhost:8080"+ opt = self._classify(snap, scope=scope)+ assert opt["egress"]["allowed"] is False+ assert opt["egress"]["reason"] == "private_url_unapproved"++ def test_overlay_runs_without_any_scope_classification(+ self, stub_engine_flags, monkeypatch+ ):+ """The unfiltered response path (no ``?egress_scope=``) still gets+ the overlay — this is the code path a default install takes, since+ ``getCurrentEgressScopeForDropdown`` sends no scope for adaptive.+ Would FAIL before the fix: nothing stamped ``egress`` at all."""+ self._clear(monkeypatch)+ options = [_option("searxng"), _option("arxiv")]+ _apply_guarded_url_overlay(+ options, {self.URL_KEY: "http://localhost:8080"}+ )+ searxng = next(o for o in options if o["value"] == "searxng")+ arxiv = next(o for o in options if o["value"] == "arxiv")+ assert searxng["egress"] == {+ "allowed": False,+ "reason": "private_url_unapproved",+ }+ # Non-guarded engines keep the historical shape (no egress key).+ assert "egress" not in arxiv++ def test_overlay_still_runs_when_the_policy_context_fails_to_build(+ self, stub_engine_flags, monkeypatch+ ):+ """The degraded path stamps ``policy_unavailable`` and returns early.++ ``context_from_snapshot`` raises on a malformed snapshot (and on an+ unknown ``policy.egress_scope``). The route then fails OPEN on scope+ deliberately, so the frontend defers to the request-boundary+ precheck instead of showing a half-blanked dropdown. The URL guard+ is not part of that context, though, and the runtime refuses the URL+ regardless — so a guard-denied engine must not read as selectable+ here either. Would FAIL before this change: the early ``return``+ came before the overlay.+ """+ self._clear(monkeypatch)+ import local_deep_research.security.egress.policy as policy_mod++ def _boom(*args, **kwargs):+ raise ValueError("malformed snapshot")++ monkeypatch.setattr(policy_mod, "context_from_snapshot", _boom)++ snap = _snap(scope="public_only", primary="searxng")+ snap[self.URL_KEY] = "http://localhost:8080"+ options = [_option("searxng"), _option("arxiv")]+ _classify_options_for_egress(+ options,+ egress_scope="public_only",+ primary_engine="searxng",+ settings_snapshot=snap,+ username="user",+ )+ searxng = next(o for o in options if o["value"] == "searxng")+ arxiv = next(o for o in options if o["value"] == "arxiv")+ # Scope decision degraded permissively...+ assert arxiv["egress"] == {+ "allowed": True,+ "reason": "policy_unavailable",+ }+ # ...but the scope-independent URL guard still denied SearXNG.+ assert searxng["egress"] == {+ "allowed": False,+ "reason": "private_url_unapproved",+ }++ def test_scope_denial_keeps_its_more_specific_reason(+ self, stub_engine_flags, monkeypatch+ ):+ """Under private_only a public engine is denied for scope reasons;+ the overlay must not overwrite that with the vaguer URL reason."""+ self._clear(monkeypatch)+ snap = _snap(scope="private_only", primary="library")+ snap[self.URL_KEY] = "http://localhost:8080"+ opt = self._classify(snap, scope="private_only", primary="library")+ assert opt["egress"]["allowed"] is False+ assert opt["egress"]["reason"] == "scope_mismatch_private_only"++ # ------------------------------------------------------------------+ # Advisory, not authoritative (PR #5648 follow-up, P1-1).+ #+ # ``check_private_engine_url_blocked`` is DNS-free on purpose — a+ # settings-page render must not become a resolver round-trip, and must+ # not let a hostile instance URL make the render path probe an+ # internal name. It is therefore a strict SUBSET of what the runtime+ # blocks: a short-form literal and a private-DNS hostname sail past+ # the overlay and are refused later by ``validate_url``. The overlay+ # fails OPEN (never closed), and these tests pin that contract so a+ # future change that silently adds a DNS lookup has to justify itself.+ # ------------------------------------------------------------------++ def test_short_form_literal_is_not_caught_advisory_gap(+ self, stub_engine_flags, monkeypatch+ ):+ self._clear(monkeypatch)+ snap = _snap(scope="adaptive", primary="searxng")+ snap[self.URL_KEY] = "http://127.1:8080"+ opt = self._classify(snap, scope="adaptive")+ # Documented gap: the runtime WILL block this. The overlay does+ # not, because 127.1 is not a parseable IP literal and the no-DNS+ # hostname check does not recognise it.+ assert opt["egress"]["allowed"] is True++ def test_private_dns_hostname_is_not_caught_advisory_gap(+ self, stub_engine_flags, monkeypatch+ ):+ self._clear(monkeypatch)+ snap = _snap(scope="adaptive", primary="searxng")+ snap[self.URL_KEY] = "http://searx.internal:8080"+ opt = self._classify(snap, scope="adaptive")+ # Documented gap: resolving searx.internal (-> 10.x) would block+ # at runtime; the overlay does no DNS so it stays selectable.+ assert opt["egress"]["allowed"] is True++ def test_lan_literal_is_caught(self, stub_engine_flags, monkeypatch):+ """The dominant misconfiguration (a LAN literal) IS covered, so+ the advisory gap above is a subset, not a no-op."""+ self._clear(monkeypatch)+ snap = _snap(scope="adaptive", primary="searxng")+ snap[self.URL_KEY] = "http://192.168.1.50:8080"+ opt = self._classify(snap, scope="adaptive")+ assert opt["egress"]["allowed"] is False+ assert opt["egress"]["reason"] == "private_url_unapproved"++ def test_env_locked_url_stays_enabled_under_adaptive(+ self, stub_engine_flags, monkeypatch+ ):+ """Operator-provisioned (env-locked) URLs are approved, and that+ approval is scope-independent too."""+ self._clear(monkeypatch)+ monkeypatch.setenv(+ "LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL",+ "http://localhost:8080",+ )+ snap = _snap(scope="adaptive", primary="searxng")+ snap[self.URL_KEY] = "http://localhost:8080"+ opt = self._classify(snap, scope="adaptive")+ assert opt["egress"]["allowed"] is Truediff --git a/tests/web/test_js_fetch_parity.py b/tests/web/test_js_fetch_parity.pyindex ae490ccb26..86108178fa 100644--- a/tests/web/test_js_fetch_parity.py+++ b/tests/web/test_js_fetch_parity.py@@ -955,7 +955,7 @@ LIVE_CASES = (bad={"val": 0.5},),LiveCase(- js_ref="components/research.js:2989",+ js_ref="components/research.js:3008",method="POST",url="/settings/api/search-favorites/toggle",good={"engine_id": "zzz_no_such_engine"},