~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(web): surface egress-scope denial errors near Start Research button (#5126)
S78e3115e7df5
diff --git a/changelog.d/+egress-error-ux-tweaks.bugfix.md b/changelog.d/+egress-error-ux-tweaks.bugfix.mdnew file mode 100644index 0000000000..5666b04239--- /dev/null+++ b/changelog.d/+egress-error-ux-tweaks.bugfix.md@@ -0,0 +1,31 @@+Egress-scope denial errors on the New Research form are now more+accurate and accessible: the inline field hint only fires for reasons+that the Egress Scope dropdown can actually fix (`scope_mismatch_*`,+`strict_not_primary`), the "Adaptive (default)" remedy is only+suggested when it is reliable (i.e. the blocked engine is the run's+primary), and the anchored alert near the submit button is completely+non-live so screen readers don't announce the error twice alongside+the live top-of-form alert. The Start Research button has also been+hoisted to right after the query and research mode selection so the+primary action — and its error message — are visible without scrolling.++Submission error clearing is now consistent across both the+egress-specific UX and generic submission failures (network errors,+5xx, malformed responses): every alert the submit handler creates is+tagged with `data-submit-alert="true"`, and a single+`clearSubmitAlerts()` removes all of them at the start of the next+attempt (or when the implicated setting changes) — so a previous+error cannot survive an early query/model validation return and appear+to describe the new attempt. The response classifier is also now+type-safe, and the button re-enable / loading-overlay teardown runs in+a `finally` block, so a malformed server body can no longer leave the+user with a permanently disabled Start Research button.++Changing the Egress Scope dropdown now only clears the egress+inline field error (via `FormValidator.clearFieldError()`) plus the+submit-owned alert toasts; other field errors — for example an+unresolved query-required or model-required error — are preserved+so the user still sees what's actually wrong. A blank or+whitespace-only `message` in the server response is also now treated+as absent and falls back to the generic copy, so a `{}`-shaped+malformed body can no longer render an invisible empty alert.diff --git a/src/local_deep_research/security/egress/guidance.py b/src/local_deep_research/security/egress/guidance.pyindex 0ba583ec58..367066d282 100644--- a/src/local_deep_research/security/egress/guidance.py+++ b/src/local_deep_research/security/egress/guidance.py@@ -29,20 +29,26 @@ _SCOPE_SETTING = (# reason code -> (what happened, how to allow it). ``{target}`` is filled with# the blocked engine/provider/host; ``{scope_setting}`` with _SCOPE_SETTING.+#+# The two ``scope_mismatch_*`` reasons have a DYNAMIC ``how`` (see+# ``_scope_mismatch_how`` below): Adaptive (default) is only mentioned when+# it's actually reliable, i.e. the blocked engine IS the run's primary+# engine. Otherwise Adaptive would follow the primary, which may sit in the+# same restrictive bucket and resolve back to the same denial — so we point+# the user at the explicit compatible scope only._GUIDANCE: dict[str, tuple[str, str]] = {"scope_mismatch_private_only": ("{target} was blocked because your Egress Scope is set to ""Private only — only local sources (your collections, local engines) ""may run, and nothing leaves the machine.",- "To use it, change your Egress Scope to Both or Public only in "- "{scope_setting}.",+ # placeholder — replaced at call time by _scope_mismatch_how()+ "__SCOPE_MISMATCH_HOW__",),"scope_mismatch_public_only": ("{target} was blocked because your Egress Scope is set to ""Public only — local/private sources are excluded from this run.",- "To use it, change your Egress Scope to Both or Private only in "- "{scope_setting}; or, if this is a collection whose contents are "- "non-sensitive, mark it Public on the collection page.",+ # placeholder — replaced at call time by _scope_mismatch_how()+ "__SCOPE_MISMATCH_HOW__",),"strict_public_host": ("{target} was blocked because your Egress Scope is Strict — only your "@@ -150,16 +156,106 @@ _NON_POLICY = {}-def denial_guidance(reason: str, *, target: Optional[str] = None) -> str:+def _scope_mismatch_how(+ reason: str,+ *,+ target_id: Optional[str],+ primary_engine: Optional[str],+) -> str:+ """Build the "how to allow it" sentence for the two scope-mismatch reasons.++ Adaptive (default) is reliable ONLY when the blocked engine is also the+ run's primary engine — Adaptive follows the primary, so if the primary+ sits in the same restrictive bucket (the common case: primary=arxiv and+ a library collection blocked under Private only), switching to Adaptive+ resolves back to Private only and the blocked engine is still denied.+ In that case we name only the explicit compatible scope, which is always+ reliable.++ ``target_id`` is the RAW blocked engine id (used for the comparison);+ ``target`` (the display string the caller passes to+ :func:`denial_guidance`) is intentionally NOT used here, because the+ research_routes caller formats it as ``"Search engine '<id>'"`` for the+ user-facing message and we don't want that wrapper participating in the+ equality check.++ Returns a string that still contains the ``{scope_setting}`` placeholder+ for the outer ``str.format`` pass — mirroring the static templates in+ ``_GUIDANCE`` so the call site doesn't need to special-case the+ substitution.+ """+ if reason == "scope_mismatch_private_only":+ # Blocked target is public; current scope is Private only. Reliable+ # remedy: Public only. (Adaptive works only if the blocked target+ # IS the primary.)+ reliable = "Public only"+ suffix = ""+ elif reason == "scope_mismatch_public_only":+ # Blocked target is local; current scope is Public only. Reliable+ # remedy: Private only. The collection-specific escape hatch is+ # preserved so users with non-sensitive local collections can+ # promote the collection instead of loosening global egress.+ reliable = "Private only"+ suffix = (+ "; or, if this is a collection whose contents are non-sensitive, "+ "mark it Public on the collection page"+ )+ else:+ # Caller asked for a non-scope-mismatch reason — fall back to the+ # generic template so we never silently drop the "how" instruction.+ return (+ "To use it, change your Egress Scope to a mode compatible with "+ "{target} in {scope_setting}."+ )++ adaptive_reliable = bool(+ target_id and primary_engine and target_id == primary_engine+ )+ # ``reliable`` already contains the trailing "only" (e.g. "Public only",+ # "Private only") — it's the full scope name. Don't add a second "only"+ # in the template, or the rendered message reads "Private only only in+ # Settings ..." (the bug this comment is in place to prevent).+ if adaptive_reliable:+ return (+ f"To use it, change your Egress Scope to Adaptive (default) or "+ f"{reliable} in {{scope_setting}}{suffix}."+ )+ # Target isn't the primary (or primary isn't known) — the explicit+ # compatible scope is the only reliable fix.+ return (+ f"To use it, change your Egress Scope to {reliable} in "+ f"{{scope_setting}}{suffix}."+ )+++def denial_guidance(+ reason: str,+ *,+ target: Optional[str] = None,+ primary_engine: Optional[str] = None,+ target_id: Optional[str] = None,+) -> str:"""Return a clear, user-facing explanation + instructions for a denial.- ``reason`` is the PDP machine code; ``target`` is the blocked thing- (engine / provider / host), inserted into the message. Always returns a- non-empty string, even for unknown reasons.+ ``reason`` is the PDP machine code; ``target`` is the display string for+ the blocked thing (engine / provider / host) and is inserted into the+ message verbatim; ``target_id`` is the raw blocked engine id used ONLY+ for the Adaptive-reliability check on the scope-mismatch reasons — keep+ it separate from ``target`` so the research_routes caller can format the+ display target however it likes (``"Search engine 'library'"``) without+ breaking the equality check; ``primary_engine`` is the run's resolved+ primary search engine id, used to decide whether the Adaptive (default)+ scope is a reliable remedy (it is only when the blocked target IS the+ primary — see :func:`_scope_mismatch_how`). Always returns a non-empty+ string, even for unknown reasons."""label = target or "This action"if reason in _GUIDANCE:what, how = _GUIDANCE[reason]+ if how == "__SCOPE_MISMATCH_HOW__":+ how = _scope_mismatch_how(+ reason, target_id=target_id, primary_engine=primary_engine+ )# Two-step: the f-string only CONCATENATES the two plain templates# (no placeholder interpolation — {target}/{scope_setting} are literal# here), then .format() fills them. Don't collapse this into a singlediff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex 9631407b4d..ef74a80e10 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -314,17 +314,49 @@ def _precheck_engine_policy(settings_manager, params, search_engine, username):# guidance import with it.from ...security.egress.guidance import denial_guidance+ # Only the scope-mismatch and strict-not-primary denials have a+ # form field the user can toggle to fix the error (the Egress+ # Scope dropdown). For engine_unknown / unclassified the user has+ # to pick a different search engine — flagging the egress-scope+ # dropdown there would be misleading and cause the wrong field to+ # turn red. internal_error / no_snapshot are server-side issues+ # with no form-level fix at all, so we return ``field: null`` and+ # let the frontend render just the alert (no inline field error).+ field_for_reason = {+ "scope_mismatch_private_only": "policy_egress_scope",+ "scope_mismatch_public_only": "policy_egress_scope",+ "strict_not_primary": "policy_egress_scope",+ }.get(decision.reason)+return (jsonify({"status": "error",# Clear, actionable message (what + why + how to allow),- # plus the raw reason code for support/logs.+ # plus the raw reason code for support/logs. The+ # guidance uses ``primary_engine`` to decide whether+ # Adaptive (default) is a reliable remedy — see+ # ``_scope_mismatch_how``."message": denial_guidance(decision.reason,target=f"Search engine '{search_engine}'",+ # Raw engine id, used by the guidance to decide+ # whether Adaptive (default) is a reliable+ # remedy for a scope-mismatch denial (see+ # ``_scope_mismatch_how`` — kept separate from+ # ``target`` so the formatted display string+ # above doesn't break the equality check).+ target_id=search_engine,+ primary_engine=policy_ctx.primary_engine,),"reason": decision.reason,+ # The frontend uses this to highlight the offending+ # form field with an inline error (FormValidator's+ # .ldr-field-error + .ldr-field-invalid convention)+ # and to anchor an alert near the submit button.+ # ``null`` means "no form field fixes this — show the+ # alert without an inline field error".+ "field": field_for_reason,}),400,diff --git a/src/local_deep_research/web/static/css/news.css b/src/local_deep_research/web/static/css/news.cssindex 7f6f66aa76..a71898eba0 100644--- a/src/local_deep_research/web/static/css/news.css+++ b/src/local_deep_research/web/static/css/news.css@@ -2,7 +2,8 @@/* Note: Color variables inherited from themes.css *//* Alert Container */-.ldr-settings-alert-container {+.ldr-settings-alert-container,+.ldr-settings-error-container {display: none;position: fixed;top: 20px;diff --git a/src/local_deep_research/web/static/css/settings.css b/src/local_deep_research/web/static/css/settings.cssindex fb922ef6ed..a9bcd0da19 100644--- a/src/local_deep_research/web/static/css/settings.css+++ b/src/local_deep_research/web/static/css/settings.css@@ -1184,12 +1184,14 @@}/* Add styles for alert container and close button */-.ldr-settings-alert-container {+.ldr-settings-alert-container,+.ldr-settings-error-container {margin-bottom: 1rem;width: 100%;}-.ldr-settings-alert-container .alert {+.ldr-settings-alert-container .alert,+.ldr-settings-error-container .alert {position: relative;padding-right: 30px;}diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.jsindex 2cb335a299..f5ed074584 100644--- a/src/local_deep_research/web/static/js/components/research.js+++ b/src/local_deep_research/web/static/js/components/research.js@@ -4,6 +4,21 @@* Manages the research form and handles submissions*/(function() {+ /**+ * Treat blank / whitespace-only strings as absent. Used by the+ * submit handler when extracting ``data.message`` / ``data.field``+ * so a malformed response ({message: ""} or {message: " "}) is+ * never passed through as-is — that would render an empty alert+ * that is invisible to the user and recreates the original+ * "click submit and nothing happens" symptom.+ * @param {*} value - Value extracted from the response body.+ * @returns {boolean} - True when value is a non-empty string of+ * non-whitespace characters.+ */+ function nonBlankString(value) {+ return typeof value === 'string' && value.trim().length > 0;+ }+// Form validator instancelet researchValidator = null;@@ -663,6 +678,40 @@{ validateOnBlur: false, validateOnInput: false });}++ // Register the egress scope dropdown so a `.ldr-field-error` element+ // exists next to it. There's no client-side rule here — the+ // server is the source of truth — but pre-creating the slot means+ // showFormError() can attach an inline message without having to+ // insert DOM at error time (which is more error-prone around+ // timing and scroll-into-view).+ const egressScopeInput = document.getElementById('policy_egress_scope');+ if (egressScopeInput) {+ researchValidator.addValidation(+ egressScopeInput,+ () => null,+ { validateOnBlur: false, validateOnInput: false }+ );+ }++ // Clear any prior egress-scope error as soon as the user+ // changes the dropdown — keeps the red border / message+ // from sticking around once the user has acknowledged the+ // issue. Only this field's inline error is wiped: an+ // unrelated query-required / model-required error must+ // still be visible to the user. Submit-owned alert+ // toasts are also dismissed so a stale message stops+ // being announced on the next interaction.+ if (egressScopeInput) {+ egressScopeInput.addEventListener('change', () => {+ if (researchValidator) {+ try {+ researchValidator.clearFieldError(egressScopeInput);+ } catch (_e) { /* defensive */ }+ }+ clearSubmitOwnedAlerts();+ });+ }}// INITIALIZE ADVANCED OPTIONS FIRST - before any async operations@@ -2452,6 +2501,14 @@event.preventDefault();SafeLogger.log('Research form submitted');+ // Clear any alerts this submit handler previously produced — both+ // the egress-specific error UX and any generic submission error+ // (e.g. a network failure from the last attempt). Clearing at the+ // very start of submit means early validation returns (missing+ // query, missing model) also wipe the stale message instead of+ // letting it survive and appear to describe the new attempt.+ clearSubmitAlerts();+// Determine the research mode up front so validation can be mode-aware.const selectedModeRadio = document.querySelector('input[name="research_mode"]:checked');const mode = selectedModeRadio ? selectedModeRadio.value : 'quick';@@ -2643,30 +2700,53 @@}).then(response => response.json()).then(data => {- if (data.status === 'success' || data.status === window.RESEARCH_STATUS.QUEUED) {- SafeLogger.log('Research started:', data);+ try {+ if (data && (data.status === 'success' || data.status === window.RESEARCH_STATUS.QUEUED)) {+ SafeLogger.log('Research started:', data);- if (data.status === window.RESEARCH_STATUS.QUEUED) {- showAlert(data.message || 'Your research has been queued.', 'info');- }-- // Store research preferences in localStorage- // Settings are saved to database via the API, not localStorage+ if (data.status === window.RESEARCH_STATUS.QUEUED) {+ showAlert(data.message || 'Your research has been queued.', 'info');+ }- // Redirect to the progress page- // URLBuilder produces /progress/{uuid}- // bearer:disable javascript_lang_open_redirect- window.location.href = URLBuilder.progressPage(data.research_id);- } else {- // Show error message- showAlert(data.message || 'Failed to start research.', 'error');+ // Store research preferences in localStorage+ // Settings are saved to database via the API, not localStorage- // Re-enable the button+ // Redirect to the progress page+ // URLBuilder produces /progress/{uuid}+ // bearer:disable javascript_lang_open_redirect+ window.location.href = URLBuilder.progressPage(data.research_id);+ } else {+ // Show error message — anchor near submit + flag the+ // offending field (if the server told us which one).+ // showFormError is the belt-and-suspenders version:+ // bottom-of-form alert that won't scroll off-screen+ // + inline .ldr-field-error on the named field.+ // We ALSO call showAlert for the top-of-form alert (now+ // scrollIntoView'd), since the user's symptom was+ // "nothing happens" — redundancy is the point.+ //+ // Treat blank / whitespace-only strings as absent so a+ // malformed ``{}``-shaped body can't render an empty+ // alert (which would be invisible to the user and+ // look like the original "click submit and nothing+ // happens" symptom).+ const message = nonBlankString(data && data.message)+ ? data.message+ : 'Failed to start research.';+ showAlert(message, 'error');+ if (typeof showFormError === 'function') {+ showFormError(message, nonBlankString(data && data.field)+ ? data.field : null);+ }+ }+ } finally {+ // Always re-enable the button and tear down the loading+ // overlay, even if a malformed response (non-object data,+ // missing status, etc.) would otherwise throw partway+ // through. The user must never be left with a permanently+ // disabled submit button and a stuck overlay.startBtn.disabled = false;- // Use centralized security utilities for button resetwindow.safeUpdateButton(startBtn, 'fa-rocket', ' Start Research');-- // Remove loading overlayconst overlay = document.querySelector('.ldr-loading-overlay');if (overlay) overlay.remove();}@@ -2674,13 +2754,18 @@.catch(error => {SafeLogger.error('Error starting research:', error);- // Show error message- showAlert('An error occurred while starting research. Please try again.', 'error');+ // Network/parse failure — no field hint available, so just+ // surface the generic message in both alert slots.+ const message = 'An error occurred while starting research. Please try again.';+ showAlert(message, 'error');+ if (typeof showFormError === 'function') {+ showFormError(message, null);+ }// Re-enable the buttonstartBtn.disabled = false;// Use centralized security utilities for button reset- window.safeUpdateButton(startBtn, 'fa-rocket', ' Start Research');+ window.safeUpdateButton(startBtn, 'fa-rocket', ' Start Research');// Remove loading overlayconst overlay = document.querySelector('.ldr-loading-overlay');@@ -2694,11 +2779,29 @@* @param {string} type - The alert type (success, error, warning, info)*/function showAlert(message, type = 'info') {- // Use centralized security utility for alerts with auto-hide functionality+ // Use centralized security utility for alerts with auto-hide functionalitywindow.showSafeAlert('research-alert', message, type);-- // Add auto-hide functionality after 5 seconds (preserving dev branch behavior)+ // Mark the alert as submit-owned so clearSubmitAlerts() can+ // remove it on the next attempt or when the user changes the+ // implicated setting. Unrelated danger alerts (e.g. a settings+ // page warning) are not tagged and therefore survive.const alertContainer = document.getElementById('research-alert');+ if (alertContainer) {+ const alertEl = alertContainer.querySelector('.alert');+ if (alertEl) {+ alertEl.setAttribute('data-submit-alert', 'true');+ }+ try {+ alertContainer.scrollIntoView({ block: 'center', behavior: 'smooth' });+ } catch (_e) { /* old browsers */ }+ }++ // Errors don't auto-hide — they're actionable and the user may+ // need time to read them, scroll up to context, or change a+ // setting. info/success/warning still auto-hide (e.g. the queued+ // notification, the rerun hint).+ if (type === 'error') return;+if (alertContainer && alertContainer.firstChild) {const alert = alertContainer.firstChild;setTimeout(() => {@@ -2712,6 +2815,137 @@}}+ /**+ * Show a form-submission error that's impossible to miss:+ * 1. Anchors a copy of the message directly above the submit button+ * (the user's natural focal point — see the "click Start Research+ * and nothing happens" bug where the top-of-form alert was+ * off-screen and got auto-dismissed).+ * 2. Scrolls that copy into view, so it's visible even if the user+ * has scrolled the long form somewhere unusual.+ * 3. If a field name is supplied, mirrors the message inline next to+ * that field using the existing FormValidator/.ldr-field-error+ * convention so the offending input gets a red border too.+ * 4. Never auto-hides — errors need to stick around until the user+ * acts or re-submits.+ *+ * The anchored copy is a visual duplicate of the top-of-form+ * #research-alert (which is the live ``role="alert"`` announcement).+ * The child .alert element has its ``role``/``aria-atomic``+ * attributes stripped, and the parent #research-error-alert has no+ * ``role``/``aria-live`` either, so the duplicate is completely+ * non-live and screen readers will not announce the error twice.+ *+ * @param {string} message - The user-facing error text.+ * @param {string|null} fieldName - Optional form field id to flag+ * inline (e.g. "policy_egress_scope").+ */+ function showFormError(message, fieldName) {+ // Anchor near the submit button (always visible — it's the last+ // thing in the form, so scrolling can't push it off-screen+ // before the user clicks submit again).+ const errorContainer = document.getElementById('research-error-alert');+ if (errorContainer) {+ window.showSafeAlert('research-error-alert', message, 'error');+ const alertEl = errorContainer.querySelector('.alert');+ if (alertEl) {+ // Make the duplicate copy non-live to prevent double-announcement.+ alertEl.removeAttribute('role');+ alertEl.removeAttribute('aria-atomic');+ // Mark as submit-owned so clearSubmitAlerts() can+ // remove it on the next attempt or when the user+ // changes the implicated setting. Unrelated alerts+ // (none today, but a safe default) are not tagged.+ alertEl.setAttribute('data-submit-alert', 'true');+ }+ // Only scroll if the user wouldn't already see it. With a+ // reasonably-sized viewport, scrolling on every error is+ // disorienting, so prefer `nearest` and only nudge when the+ // container is fully out of view.+ try {+ const r = errorContainer.getBoundingClientRect();+ const fullyOff = r.bottom < 0 || r.top > window.innerHeight;+ if (fullyOff) {+ errorContainer.scrollIntoView({ block: 'center', behavior: 'smooth' });+ } else {+ // Nudge into the safe middle band even if partially visible.+ errorContainer.scrollIntoView({ block: 'nearest', behavior: 'smooth' });+ }+ } catch (_e) { /* old browsers */ }+ }++ // Inline field error (matches the FormValidator convention used by+ // the query/model guards). Falls back gracefully if the field+ // wasn't registered — showError is a no-op in that case.+ if (fieldName && researchValidator) {+ const fieldEl = document.getElementById(fieldName);+ if (fieldEl) {+ try {+ researchValidator.showError(fieldEl, message);+ } catch (_e) { /* defensive: never let error UX break the form */ }+ // If the field is in the (collapsed) Advanced Options+ // panel, reveal it so the user can see both the alert and+ // the highlighted field.+ if (advancedPanel && !advancedPanel.classList.contains('ldr-expanded')) {+ applyAdvancedOptionsState(true);+ }+ }+ }+ }++ /**+ * Remove the submit-owned alert toasts (the top-of-form+ * #research-alert and the anchored #research-error-alert that this+ * submit handler tagged with ``data-submit-alert="true"``). Untagged+ * alerts are preserved — only the submit handler's own messages are+ * removed. Used by the change listener for the egress-scope+ * dropdown, which should NOT wipe unrelated field errors via+ * FormValidator.clearErrors().+ */+ function clearSubmitOwnedAlerts() {+ for (const id of ['research-error-alert', 'research-alert']) {+ const container = document.getElementById(id);+ if (!container) continue;+ const tagged = container.querySelector('.alert[data-submit-alert="true"]');+ if (tagged) {+ tagged.remove();+ if (!container.firstChild) {+ container.style.display = 'none';+ }+ }+ }+ }++ /**+ * Clear the submission-error UX produced by this submit handler:+ * the top-of-form #research-alert, the anchored #research-error-alert+ * above the submit button, and the inline field errors set via+ * FormValidator. Called at the very start of a new submission (so a+ * stale message can't survive an early validation return).+ *+ * Both the egress-specific error UX AND generic submission errors+ * (network failures, 5xx, malformed responses) are wiped. The submit+ * handler tags every alert it creates with ``data-submit-alert="true"``;+ * this function removes only those tags, so unrelated page alerts+ * (e.g. a settings-page danger warning that happens to live in+ * #research-alert) survive untouched.+ */+ function clearSubmitAlerts() {+ clearSubmitOwnedAlerts();+ // Wipe inline field errors so the red borders / messages from a+ // prior attempt don't survive. Each registered field's rule is+ // re-evaluated by the validation guards that follow; if the+ // field is now valid the error is cleared, if it's still+ // invalid the error is re-shown (e.g. a missing model is+ // re-flagged so the user can see it after the next attempt's+ // missing-model guard runs).+ if (researchValidator) {+ try {+ researchValidator.clearErrors();+ } catch (_e) { /* defensive */ }+ }+ }+// Initialize research component when DOM is loadeddocument.addEventListener('DOMContentLoaded', initializeResearch);})();diff --git a/src/local_deep_research/web/static/js/utils/form-validation.js b/src/local_deep_research/web/static/js/utils/form-validation.jsindex 8a425c922a..95a4a7ed9e 100644--- a/src/local_deep_research/web/static/js/utils/form-validation.js+++ b/src/local_deep_research/web/static/js/utils/form-validation.js@@ -126,6 +126,27 @@});}+ /**+ * Clear the validation error for a single field without touching+ * the other registered fields. Useful for change-listener UX+ * where acknowledging one input must not wipe errors on others+ * (e.g. changing the egress scope must not hide a still-valid+ * query-required or model-required error).+ * @param {HTMLElement|string} field - Field element or selector+ */+ clearFieldError(field) {+ const element = typeof field === 'string' ? document.querySelector(field) : field;+ if (!element) return;++ const errorElement = this.errorElements.get(element);+ element.classList.remove('ldr-field-invalid');+ element.removeAttribute('aria-invalid');+ if (errorElement) {+ errorElement.textContent = '';+ errorElement.style.display = 'none';+ }+ }+/*** Show error on a specific field* @param {HTMLElement|string} field - Field element or selectordiff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.htmlindex 618bfa1976..8ce0a0a631 100644--- a/src/local_deep_research/web/templates/pages/research.html+++ b/src/local_deep_research/web/templates/pages/research.html@@ -78,6 +78,37 @@</fieldset></div>+ <!-- Error alert + Start Research button hoisted right after the+ query and mode selection so the primary action is+ immediately visible — the original layout put the+ submit button at the very bottom of a long form, which+ forced scrolling and made the "click and nothing+ happens" symptom worse when an egress denial occurred+ off-screen above the button. Now the user types,+ picks a mode, and clicks without scrolling; the+ anchored error alert appears right above the button,+ and the egress scope dropdown sits just below so the+ user can fix it with one short scroll if needed.+ Privacy & Egress and Advanced Options remain visible+ (and ordered) below the button for users who want to+ change them. -->+ <div id="research-error-alert" class="ldr-settings-error-container" style="display:none"></div>++ <!-- Start Research Button -->+ <div class="ldr-form-actions">+ <button type="submit" class="btn btn-primary" id="start-research-btn"><i aria-hidden="true" class="fas fa-rocket"></i> Start Research</button>+ </div>++ <!-- Audio Notifications -->+ <div class="ldr-form-options">+ <div class="ldr-form-option">+ <label for="notification-toggle" class="ldr-checkbox-label">+ <input type="checkbox" id="notification-toggle" checked>+ <span class="ldr-checkbox-text">Sound notifications when complete</span>+ </label>+ </div>+ </div>+<!-- Privacy & Egress — hoisted above Advanced Options because thesegovern WHAT data leaves the machine (a security boundary), notWHICH model/tuning to use. Hiding them inside the collapsible@@ -353,20 +384,12 @@</div></div>- <!-- Start Research Button -->- <div class="ldr-form-actions">- <button type="submit" class="btn btn-primary" id="start-research-btn"><i aria-hidden="true" class="fas fa-rocket"></i> Start Research</button>- </div>-- <!-- Audio Notifications -->- <div class="ldr-form-options">- <div class="ldr-form-option">- <label for="notification-toggle" class="ldr-checkbox-label">- <input type="checkbox" id="notification-toggle" checked>- <span class="ldr-checkbox-text">Sound notifications when complete</span>- </label>- </div>- </div>+ <!-- Error alert + Start Research button have been hoisted+ to the top of the form (right after the research mode+ selection) so the primary action is visible without+ scrolling. See the matching comment near the query+ input for the full rationale. The old block is gone+ from this position. --></form><!-- How Research Works Help Panel -->diff --git a/tests/js/components/research.test.js b/tests/js/components/research.test.jsindex 3372c77a8f..0a28aa4f0d 100644--- a/tests/js/components/research.test.js+++ b/tests/js/components/research.test.js@@ -34,6 +34,7 @@ function buildForm() {document.body.innerHTML = `<form id="research-form"><div id="research-alert" role="alert" style="display:none"></div>+ <div id="research-error-alert" class="ldr-settings-error-container" style="display:none"></div><textarea id="query" name="query"></textarea><label class="ldr-mode-option"><input type="radio" name="research_mode" value="quick" checked></label>@@ -59,6 +60,12 @@ function buildForm() {<select id="strategy"><option value="source-based" selected>source-based</option></select><input id="iterations" value="2"><input id="questions_per_iteration" value="3">++ <select id="policy_egress_scope" name="policy_egress_scope">+ <option value="adaptive" selected>Adaptive (default)</option>+ <option value="public_only">Public only</option>+ <option value="private_only">Private only</option>+ </select></div><button type="submit" id="start-research-btn"><span></span></button>@@ -230,6 +237,300 @@ describe('research form — model-required guard', () => {});});+describe('research form — egress-scope denial UX', () => {+ // Drive a server 400 that names the offending field, exactly like+ // _precheck_engine_policy does for scope-mismatch / strict-not-primary+ // denials (field: "policy_egress_scope"). The other reasons+ // (engine_unknown / unclassified / internal_error) intentionally+ // return ``field: null`` so the frontend must NOT highlight a form+ // field — those are tested in the next describe block.+ function stubEgressDenial(message, overrides = {}) {+ fetchMock.mockImplementationOnce(() =>+ Promise.resolve({+ ok: false,+ status: 400,+ json: () =>+ Promise.resolve({+ status: 'error',+ message,+ reason: 'scope_mismatch_public_only',+ field: 'policy_egress_scope',+ ...overrides,+ }),+ text: () => Promise.resolve(''),+ })+ );+ }++ // The submit handler's error path runs inside fetch().then(...).then(...),+ // which needs the microtask queue to drain. A macrotask flush is the+ // reliable way to get there.+ function flush() {+ return new Promise((r) => setTimeout(r, 0));+ }++ beforeEach(() => {+ // Clear any anchored alert from a prior test.+ const err = document.getElementById('research-error-alert');+ err.innerHTML = '';+ err.style.display = 'none';+ const scope = document.getElementById('policy_egress_scope');+ scope.classList.remove('ldr-field-invalid');+ scope.removeAttribute('aria-invalid');+ const fieldErr = document.getElementById('policy_egress_scope-error');+ if (fieldErr) {+ // Reset rather than remove: showError() reuses the cached error+ // element created during addValidation(), so removing it from the+ // DOM would leave a detached node that getElementById can't find.+ fieldErr.textContent = '';+ fieldErr.style.display = 'none';+ }+ // A model must be present or the model-required guard blocks submit+ // before the fetch (and thus the egress-error UX) ever runs.+ document.getElementById('model_hidden').value = 'qwen3:4b';+ });++ it('anchors the error alert next to the submit button and flags the egress scope field', async () => {+ stubEgressDenial('Search engine searxng was blocked because your Egress Scope is set to Private only.');++ submitForm();+ await flush();++ // The anchored alert near the button is populated and visible...+ const anchored = document.getElementById('research-error-alert');+ expect(anchored.style.display).toBe('block');+ expect(anchored.textContent).toContain('Egress Scope');+ // ...and the named field gets an inline error (red border + message).+ const scope = document.getElementById('policy_egress_scope');+ expect(scope.getAttribute('aria-invalid')).toBe('true');+ const fieldErr = document.getElementById('policy_egress_scope-error');+ expect(fieldErr).not.toBeNull();+ expect(fieldErr.textContent).toContain('Egress Scope');+ // The request WAS sent (and the server refused it with a 400); the+ // point of this test is that the refusal is surfaced to the user, not+ // swallowed.+ expect(callsTo(START_RESEARCH)).toHaveLength(1);+ });++ it('does NOT auto-hide the anchored error alert (errors must persist)', async () => {+ // Regression: showAlert() used to auto-hide errors after 5s like+ // info/success. The anchored alert is shown via showFormError(), which+ // never auto-hides, so it must still be visible after the timers fire.+ vi.useFakeTimers();+ try {+ stubEgressDenial('blocked');+ submitForm();+ // Drain the fetch microtask chain (fake timers don't affect these).+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ // Advance well past the 5s auto-hide window.+ vi.advanceTimersByTime(6000);+ const anchored = document.getElementById('research-error-alert');+ expect(anchored.style.display).toBe('block');+ expect(anchored.textContent).toContain('blocked');+ } finally {+ vi.useRealTimers();+ }+ });++ it('clears the anchored alert and field error when the user changes the egress scope', async () => {+ stubEgressDenial('Search engine blocked by Egress Scope.');+ submitForm();+ await flush();+ expect(document.getElementById('research-error-alert').style.display).toBe('block');+ expect(document.getElementById('policy_egress_scope').getAttribute('aria-invalid')).toBe('true');++ // Changing the dropdown should clear both the anchored alert and the+ // inline field error.+ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));+ expect(document.getElementById('research-error-alert').style.display).toBe('none');+ expect(document.getElementById('policy_egress_scope').getAttribute('aria-invalid')).toBeNull();+ });++ it('shows the anchored alert even when the server omits a field hint (network/parse failure)', async () => {+ // The catch path passes field=null; the anchored alert must still show.+ fetchMock.mockImplementationOnce(() => Promise.reject(new Error('network down')));+ submitForm();+ await flush();++ const anchored = document.getElementById('research-error-alert');+ expect(anchored.style.display).toBe('block');+ expect(anchored.textContent).toContain('An error occurred while starting research');+ // No inline field error was requested (field was null), so the+ // pre-registered error slot stays empty.+ const fieldErr = document.getElementById('policy_egress_scope-error');+ expect(fieldErr).not.toBeNull();+ expect(fieldErr.textContent).toBe('');+ });++ it('ensures the anchored alert copy is completely non-live so screen readers do not announce the error twice', async () => {+ // The top #research-alert is the live ``role="alert"`` and scrolls+ // into view; the anchored #research-error-alert is a visual+ // duplicate only — announcing it twice would be noisy for AT users.+ stubEgressDenial('Search engine blocked by Egress Scope.');+ submitForm();+ await flush();++ const anchored = document.getElementById('research-error-alert');+ expect(anchored.getAttribute('role')).toBeNull();+ expect(anchored.getAttribute('aria-live')).toBeNull();++ const childAlert = anchored.querySelector('.alert');+ expect(childAlert).not.toBeNull();+ expect(childAlert.getAttribute('role')).toBeNull();+ expect(childAlert.getAttribute('aria-atomic')).toBeNull();+ });++ it('preserves an unrelated (non-egress) danger alert when clearEgressError is called', () => {+ const topAlert = document.getElementById('research-alert');+ topAlert.innerHTML =+ '<div class="alert alert-danger">An unrelated danger alert!</div>';+ topAlert.style.display = 'block';++ // Call clearEgressError directly+ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));++ // The unrelated danger alert must survive because it does not have data-egress-alert="true"+ expect(topAlert.style.display).toBe('block');+ expect(topAlert.textContent).toContain('An unrelated danger alert!');+ });++ it('clears previous egress errors even if the subsequent submit has invalid query/model validation', async () => {+ stubEgressDenial('Search engine blocked by Egress Scope.');+ submitForm();+ await flush();+ expect(document.getElementById('research-error-alert').style.display).toBe('block');+ expect(document.getElementById('research-alert').style.display).toBe('block');++ // Make query invalid so early validation returns+ document.getElementById('query').value = '';+ submitForm();++ // Previous egress errors must be cleared+ expect(document.getElementById('research-error-alert').style.display).toBe('none');+ expect(document.getElementById('research-alert').style.display).toBe('none');+ });++ it('also clears the top-of-form error alert when the user changes the egress scope', async () => {+ // Regression: hideFormError() used to clear only the anchored copy,+ // leaving the non-expiring top #research-alert showing a stale+ // egress error that would re-announce on the next interaction.+ // The fix (clearEgressError()) clears BOTH copies plus the inline+ // field error.+ stubEgressDenial('Search engine blocked by Egress Scope.');+ submitForm();+ await flush();+ expect(document.getElementById('research-error-alert').style.display).toBe('block');+ expect(document.getElementById('research-alert').style.display).toBe('block');++ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));++ expect(document.getElementById('research-error-alert').style.display).toBe('none');+ // Top alert was an error (alert-danger) — must also clear.+ expect(document.getElementById('research-alert').style.display).toBe('none');+ });++ it('preserves a top-of-form info banner when the user changes the egress scope (only the error clears)', async () => {+ // Counter-test: clearEgressError() must NOT wipe out a non-error+ // top alert (e.g. the "research queued" rerun hint) when the user+ // changes the scope in response to a stale error. Only the error+ // itself is stale; the other banners are still relevant.+ // Pre-populate the top alert with a non-error (success) banner.+ const topAlert = document.getElementById('research-alert');+ topAlert.innerHTML =+ '<div class="alert alert-success">Research queued — you can leave this page.</div>';+ topAlert.style.display = 'block';++ stubEgressDenial('Search engine blocked by Egress Scope.');+ submitForm();+ await flush();+ // The error overwrites the top alert (it has its own showAlert).+ expect(document.getElementById('research-alert').style.display).toBe('block');++ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));++ // An error was just shown; clearEgressError removes it. The earlier+ // success message is gone (it was replaced by the error), so the+ // top alert ends up empty/hidden — which is the correct outcome+ // for an error->submit->change flow.+ expect(document.getElementById('research-error-alert').style.display).toBe('none');+ });+});++describe('research form — egress denial WITHOUT a form-field fix', () => {+ // The backend returns ``field: null`` for engine_unknown, unclassified,+ // and internal_error denials — those can't be fixed by toggling the+ // egress scope (or any other form field). The frontend must surface+ // the alert but must NOT highlight a form field as invalid.+ function stubNonFieldDenial(message, reason) {+ fetchMock.mockImplementationOnce(() =>+ Promise.resolve({+ ok: false,+ status: 400,+ json: () =>+ Promise.resolve({+ status: 'error',+ message,+ reason,+ field: null,+ }),+ text: () => Promise.resolve(''),+ })+ );+ }++ function flush() {+ return new Promise((r) => setTimeout(r, 0));+ }++ beforeEach(() => {+ const err = document.getElementById('research-error-alert');+ err.innerHTML = '';+ err.style.display = 'none';+ document.getElementById('model_hidden').value = 'qwen3:4b';+ // Reset the egress-scope error specifically (other fields don't+ // matter for these cases).+ const scope = document.getElementById('policy_egress_scope');+ scope.classList.remove('ldr-field-invalid');+ scope.removeAttribute('aria-invalid');+ const fieldErr = document.getElementById('policy_egress_scope-error');+ if (fieldErr) {+ fieldErr.textContent = '';+ fieldErr.style.display = 'none';+ }+ });++ it.each([+ ['engine_unknown', 'The search engine "bogus" isn\'t recognised.'],+ ['unclassified', '"bogus" couldn\'t be classified.'],+ ['internal_error', 'An internal error occurred.'],+ ])(+ 'shows the alert but does NOT flag the egress scope field for %s',+ async (reason, message) => {+ stubNonFieldDenial(message, reason);+ submitForm();+ await flush();++ const anchored = document.getElementById('research-error-alert');+ expect(anchored.style.display).toBe('block');+ expect(anchored.textContent).toContain(message);++ // No form field is flagged invalid — the user can't fix the+ // underlying issue from the form (it's a config / server issue).+ expect(+ document+ .getElementById('policy_egress_scope')+ .getAttribute('aria-invalid')+ ).toBeNull();+ const fieldErr = document.getElementById('policy_egress_scope-error');+ expect(fieldErr.textContent).toBe('');+ }+ );+});+describe('research form — model list loading', () => {it('fetches the model list only once per page load (no duplicate concurrent request)', () => {// Regression guard: initializeResearch() and setupEventListeners() each@@ -239,3 +540,476 @@ describe('research form — model list loading', () => {expect(initAvailableModelsCalls).toBe(1);});});++describe('research form — submit-owned alert clearing (generic + egress errors)', () => {+ // Regression: clearEgressError() used to remove only alerts tagged as+ // egress errors (`data-egress-alert="true"`). Generic submission+ // errors (network failures, 5xx, malformed bodies) were untagged and+ // therefore survived a retry or an early validation return — appearing+ // to describe the new attempt. The submit handler now tags every+ // alert it creates with `data-submit-alert="true"` and clearSubmitAlerts()+ // removes all of them, so generic AND egress errors both clear on+ // retry / setting change / early validation.++ function stubGenericError(message) {+ fetchMock.mockImplementationOnce(() =>+ Promise.resolve({+ ok: false,+ status: 500,+ json: () => Promise.resolve({ status: 'error', message }),+ text: () => Promise.resolve(''),+ })+ );+ }++ function stubNetworkError() {+ fetchMock.mockImplementationOnce(() => Promise.reject(new Error('network down')));+ }++ function flush() {+ return new Promise((r) => setTimeout(r, 0));+ }++ beforeEach(() => {+ // Reset both alert containers and all field-error state.+ const top = document.getElementById('research-alert');+ top.innerHTML = '';+ top.style.display = 'none';+ const anchored = document.getElementById('research-error-alert');+ anchored.innerHTML = '';+ anchored.style.display = 'none';+ // A model must be present so the model-required guard does not+ // block submit before the fetch (and the error UX) ever runs.+ document.getElementById('model_hidden').value = 'qwen3:4b';+ });++ it('tags generic submission errors as submit-owned so clearSubmitAlerts() can find them', async () => {+ stubGenericError('Search engine is unavailable');+ submitForm();+ await flush();++ const topAlertEl = document+ .getElementById('research-alert')+ .querySelector('.alert');+ const anchoredAlertEl = document+ .getElementById('research-error-alert')+ .querySelector('.alert');+ expect(topAlertEl).not.toBeNull();+ expect(anchoredAlertEl).not.toBeNull();+ expect(topAlertEl.getAttribute('data-submit-alert')).toBe('true');+ expect(anchoredAlertEl.getAttribute('data-submit-alert')).toBe('true');+ });++ it('clears generic errors on the next submit, before validation runs', async () => {+ stubGenericError('Search engine is unavailable');+ submitForm();+ await flush();+ expect(document.getElementById('research-alert').style.display).toBe('block');+ expect(document.getElementById('research-error-alert').style.display).toBe('block');++ // Second submit with a model present — fetch will be stubbed+ // again to a 200 success, but we don't care: the point is that+ // the prior generic error was wiped BEFORE the new attempt ran.+ submitForm();+ // Sync portion of clearSubmitAlerts() has run; the rest is in+ // the fetch microtask chain.+ expect(document.getElementById('research-alert').style.display).toBe('none');+ expect(document.getElementById('research-error-alert').style.display).toBe('none');+ });++ it('clears generic errors when the user changes the egress scope', async () => {+ stubGenericError('Search engine is unavailable');+ submitForm();+ await flush();+ expect(document.getElementById('research-alert').style.display).toBe('block');+ expect(document.getElementById('research-error-alert').style.display).toBe('block');++ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));++ expect(document.getElementById('research-alert').style.display).toBe('none');+ expect(document.getElementById('research-error-alert').style.display).toBe('none');+ });++ it('clears generic errors when the next submit fails the query-required guard', async () => {+ // First attempt: generic network error shows in both alert slots.+ stubNetworkError();+ submitForm();+ await flush();+ expect(document.getElementById('research-alert').style.display).toBe('block');+ expect(document.getElementById('research-error-alert').style.display).toBe('block');++ // Second attempt: empty query → submit handler clears alerts+ // first, then the query guard returns early with its own+ // inline error. The previous generic error must NOT survive.+ document.getElementById('query').value = '';+ submitForm();++ expect(document.getElementById('research-alert').style.display).toBe('none');+ expect(document.getElementById('research-error-alert').style.display).toBe('none');+ // The query guard ran: the query field is now flagged invalid.+ expect(document.getElementById('query').getAttribute('aria-invalid')).toBe('true');+ });++ it('clears generic errors when the next submit fails the model-required guard', async () => {+ // First attempt: generic network error shows in both alert slots.+ stubNetworkError();+ submitForm();+ await flush();+ expect(document.getElementById('research-alert').style.display).toBe('block');+ expect(document.getElementById('research-error-alert').style.display).toBe('block');++ // Second attempt: model missing → submit handler clears alerts+ // first, then the model guard returns early.+ document.getElementById('model_hidden').value = '';+ submitForm();++ expect(document.getElementById('research-alert').style.display).toBe('none');+ expect(document.getElementById('research-error-alert').style.display).toBe('none');+ // The model guard ran: the model field is now flagged invalid.+ expect(document.getElementById('model').getAttribute('aria-invalid')).toBe('true');+ });++ it('still preserves an unrelated non-submit danger alert when clearing', async () => {+ // Pre-populate an UNRELATED danger alert (no data-submit-alert+ // tag) into the top container, then trigger a generic error+ // (which overwrites it via showSafeAlert's inner clear), then+ // change the egress scope — the prior submit-owned error is+ // gone but if a non-submit alert were present it would survive.+ const top = document.getElementById('research-alert');+ top.innerHTML = '<div class="alert alert-danger">Unrelated</div>';+ top.style.display = 'block';++ // Simulate the state after a submit: the new error replaced+ // the old one and is tagged. Put a new unrelated alert AFTER+ // the tagged one to prove selective removal.+ stubGenericError('Search engine is unavailable');+ submitForm();+ await flush();+ // After submit, only the tagged generic error is present.+ expect(top.querySelectorAll('.alert').length).toBe(1);++ // Now inject an unrelated alert in addition to the tagged one+ // (simulating a third-party code path pushing a warning) and+ // change the scope. The tagged one clears, the untagged one+ // survives.+ const unrelated = document.createElement('div');+ unrelated.className = 'alert alert-warning';+ unrelated.textContent = 'Settings page warning';+ top.appendChild(unrelated);++ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));++ // Tagged generic error is gone; untagged warning is preserved.+ const remaining = top.querySelectorAll('.alert');+ expect(remaining.length).toBe(1);+ expect(remaining[0].textContent).toContain('Settings page warning');+ });+});++describe('research form — malformed response resilience', () => {+ // Regression: the submit handler used to call .includes() on+ // data.reason / data.message without checking types, and the+ // button re-enable lived AFTER that classification. A malformed+ // response (e.g. data as a number, data.reason as an object) would+ // throw inside the .then() and leave the button permanently+ // disabled with the loading overlay stuck. The classifier is now+ // type-safe (typeof checks) and the button/overlay reset is in a+ // finally block so it always runs.++ function flush() {+ return new Promise((r) => setTimeout(r, 0));+ }++ beforeEach(() => {+ document.getElementById('model_hidden').value = 'qwen3:4b';+ document.querySelectorAll('.ldr-loading-overlay').forEach((o) => o.remove());+ });++ it.each([+ ['null', () => Promise.resolve(null)],+ ['number', () => Promise.resolve(42)],+ ['array', () => Promise.resolve(['error'])],+ ['missing status', () => Promise.resolve({ message: 'no status field' })],+ ['reason as object', () => Promise.resolve({+ status: 'error', reason: { kind: 'scope_mismatch' }, message: 'x'+ })],+ ['reason as number', () => Promise.resolve({+ status: 'error', reason: 42, message: 'x'+ })],+ ['message as object', () => Promise.resolve({+ status: 'error', message: { nested: 'thing' }+ })],+ ])('does not throw and re-enables the button for malformed body: %s', async (_label, bodyFactory) => {+ fetchMock.mockImplementationOnce(() => Promise.resolve({+ ok: false,+ status: 400,+ json: bodyFactory,+ text: () => Promise.resolve(''),+ }));+ const btn = document.getElementById('start-research-btn');+ expect(btn.disabled).toBe(false);++ submitForm();+ await flush();++ // The button must be re-enabled so the user can try again.+ expect(btn.disabled).toBe(false);+ // The loading overlay must be removed.+ expect(document.querySelector('.ldr-loading-overlay')).toBeNull();+ });++ it('surfaces a top-of-form alert with a fallback message when the body has no message field', async () => {+ fetchMock.mockImplementationOnce(() => Promise.resolve({+ ok: false,+ status: 500,+ json: () => Promise.resolve({}),+ text: () => Promise.resolve(''),+ }));+ submitForm();+ await flush();++ const top = document.getElementById('research-alert');+ expect(top.style.display).toBe('block');+ expect(top.textContent).toContain('Failed to start research');+ const btn = document.getElementById('start-research-btn');+ expect(btn.disabled).toBe(false);+ });++ it.each([+ ['empty string', ''],+ ['whitespace-only string', ' \n\t '],+ ])('uses the fallback message when message is a %s', async (_label, message) => {+ // Regression: typeof data.message === 'string' used to accept any+ // string, including '' and ' ', so the alert rendered empty+ // (invisible to the user) — recreating the original "click submit+ // and nothing happens" symptom. Blank / whitespace-only messages+ // must be treated as absent and fall back to the generic copy.+ fetchMock.mockImplementationOnce(() => Promise.resolve({+ ok: false,+ status: 500,+ json: () => Promise.resolve({ message }),+ text: () => Promise.resolve(''),+ }));+ submitForm();+ await flush();++ const top = document.getElementById('research-alert');+ const anchored = document.getElementById('research-error-alert');+ // The fallback copy is present in BOTH alert slots — no empty+ // alert / accidental whitespace render. The trimmed blank input+ // must NOT have leaked through.+ expect(top.textContent.trim()).toContain('Failed to start research');+ expect(anchored.textContent.trim()).toContain('Failed to start research');+ // And the button is re-enabled so the user can retry.+ const btn = document.getElementById('start-research-btn');+ expect(btn.disabled).toBe(false);+ });++ it.each([+ ['empty string', ''],+ ['whitespace-only string', ' \n\t '],+ ])('does not flag a blank field name (%s)', async (_label, field) => {+ // Counterpart test: a blank/whitespace field name must NOT be+ // passed to FormValidator.showError(); that would flag a field+ // with id="" (a no-op for querySelector, but conceptually+ // wrong). The non-blank-string check on field must match the+ // one on message.+ fetchMock.mockImplementationOnce(() => Promise.resolve({+ ok: false,+ status: 400,+ json: () => Promise.resolve({+ message: 'A normal error.',+ reason: 'scope_mismatch_public_only',+ field,+ }),+ text: () => Promise.resolve(''),+ }));+ submitForm();+ await flush();++ // No form field is flagged invalid.+ expect(+ document.getElementById('policy_egress_scope').getAttribute('aria-invalid')+ ).toBeNull();+ expect(document.getElementById('query').getAttribute('aria-invalid')).toBeNull();+ expect(document.getElementById('model').getAttribute('aria-invalid')).toBeNull();+ });+});++describe('research form — egress-scope change preserves unrelated field errors', () => {+ // Regression: the egress-scope change listener used to call+ // clearSubmitAlerts(), which called researchValidator.clearErrors()+ // for every registered field. That meant changing only Egress Scope+ // would silently hide an unresolved query-required / model-required+ // error, which is unrelated and must still be visible. The change+ // listener now wipes only the egress-scope inline error via+ // FormValidator.clearFieldError(); submit-owned alerts are still+ // dismissed, but other field errors are untouched.++ function stubEgressDenial(message) {+ fetchMock.mockImplementationOnce(() =>+ Promise.resolve({+ ok: false,+ status: 400,+ json: () => Promise.resolve({+ status: 'error',+ message,+ reason: 'scope_mismatch_public_only',+ field: 'policy_egress_scope',+ }),+ text: () => Promise.resolve(''),+ })+ );+ }++ function flush() {+ return new Promise((r) => setTimeout(r, 0));+ }++ function flagEgressScopeDirectly() {+ // Simulate the field being flagged outside of a submit (e.g.+ // the user-acknowledged retry flow where the server didn't get+ // to flag it themselves, or a stale state carried over from a+ // prior page load). Mirrors the showError() path used by+ // showFormError().+ const scope = document.getElementById('policy_egress_scope');+ scope.classList.add('ldr-field-invalid');+ scope.setAttribute('aria-invalid', 'true');+ const fieldErr = document.getElementById('policy_egress_scope-error');+ if (fieldErr) {+ fieldErr.textContent = 'Egress scope blocked';+ fieldErr.style.display = 'block';+ }+ }++ function flagQueryMissing() {+ // Mirror the query validator's behaviour when the field is empty.+ const q = document.getElementById('query');+ q.classList.add('ldr-field-invalid');+ q.setAttribute('aria-invalid', 'true');+ const fieldErr = document.getElementById('query-error');+ if (fieldErr) {+ fieldErr.textContent = 'Please enter a research query.';+ fieldErr.style.display = 'block';+ }+ }++ function flagModelMissing() {+ const m = document.getElementById('model');+ m.classList.add('ldr-field-invalid');+ m.setAttribute('aria-invalid', 'true');+ const fieldErr = document.getElementById('model-error');+ if (fieldErr) {+ fieldErr.textContent = 'Please select or enter a model.';+ fieldErr.style.display = 'block';+ }+ }++ beforeEach(() => {+ const top = document.getElementById('research-alert');+ top.innerHTML = '';+ top.style.display = 'none';+ const anchored = document.getElementById('research-error-alert');+ anchored.innerHTML = '';+ anchored.style.display = 'none';+ document.getElementById('model_hidden').value = 'qwen3:4b';+ // Reset every error field so each test starts from a clean slate.+ for (const id of ['query', 'model', 'policy_egress_scope']) {+ const el = document.getElementById(id);+ el.classList.remove('ldr-field-invalid');+ el.removeAttribute('aria-invalid');+ const fieldErr = document.getElementById(`${id}-error`);+ if (fieldErr) {+ fieldErr.textContent = '';+ fieldErr.style.display = 'none';+ }+ }+ });++ it('clears ONLY the egress-scope inline error when the egress scope changes', async () => {+ // Set up an egress-scope error via the real submit path.+ stubEgressDenial('Search engine blocked by Egress Scope.');+ submitForm();+ await flush();+ flagEgressScopeDirectly();+ expect(+ document.getElementById('policy_egress_scope').getAttribute('aria-invalid')+ ).toBe('true');++ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));++ // The egress-scope inline error is wiped...+ expect(+ document.getElementById('policy_egress_scope').getAttribute('aria-invalid')+ ).toBeNull();+ const egressFieldErr = document.getElementById('policy_egress_scope-error');+ expect(egressFieldErr.textContent).toBe('');+ // ...and the submit-owned alert toasts are gone.+ expect(document.getElementById('research-alert').style.display).toBe('none');+ expect(document.getElementById('research-error-alert').style.display).toBe('none');+ });++ it('preserves an unrelated query-required error when the egress scope changes', async () => {+ flagEgressScopeDirectly();+ flagQueryMissing();+ // Sanity: both errors are showing before the change.+ expect(document.getElementById('query').getAttribute('aria-invalid')).toBe('true');+ expect(+ document.getElementById('policy_egress_scope').getAttribute('aria-invalid')+ ).toBe('true');++ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));++ // The egress error is cleared...+ expect(+ document.getElementById('policy_egress_scope').getAttribute('aria-invalid')+ ).toBeNull();+ const egressFieldErr = document.getElementById('policy_egress_scope-error');+ expect(egressFieldErr.textContent).toBe('');+ // ...but the query error is STILL visible — changing the scope+ // is not a user-acknowledged retry for query-required.+ expect(document.getElementById('query').getAttribute('aria-invalid')).toBe('true');+ expect(document.getElementById('query-error').textContent).toContain(+ 'Please enter a research query.'+ );+ });++ it('preserves an unrelated model-required error when the egress scope changes', async () => {+ flagEgressScopeDirectly();+ flagModelMissing();+ expect(document.getElementById('model').getAttribute('aria-invalid')).toBe('true');+ expect(+ document.getElementById('policy_egress_scope').getAttribute('aria-invalid')+ ).toBe('true');++ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));++ // Egress error is cleared...+ expect(+ document.getElementById('policy_egress_scope').getAttribute('aria-invalid')+ ).toBeNull();+ // ...model error is preserved.+ expect(document.getElementById('model').getAttribute('aria-invalid')).toBe('true');+ expect(document.getElementById('model-error').textContent).toContain(+ 'Please select or enter a model.'+ );+ });++ it('still wipes submit-owned alert toasts when the egress scope changes', async () => {+ // The change listener should still dismiss the submit-owned toast+ // alerts so a stale message stops being re-announced on the next+ // interaction. This is the part of the prior behaviour that did NOT+ // regress; we keep it explicit so a future refactor can't silently+ // re-introduce the regression from the other direction.+ stubEgressDenial('Search engine blocked by Egress Scope.');+ submitForm();+ await flush();+ expect(document.getElementById('research-alert').style.display).toBe('block');+ expect(document.getElementById('research-error-alert').style.display).toBe('block');++ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));++ expect(document.getElementById('research-alert').style.display).toBe('none');+ expect(document.getElementById('research-error-alert').style.display).toBe('none');+ });+});diff --git a/tests/security/test_egress_guidance.py b/tests/security/test_egress_guidance.pyindex c8ab317903..de202cb8e2 100644--- a/tests/security/test_egress_guidance.py+++ b/tests/security/test_egress_guidance.py@@ -12,15 +12,20 @@ from local_deep_research.security.egress.guidance import denial_guidance"reason,target,must_contain",[# Scope blocks name the scope AND the setting to change.+ # The retired `both` scope was replaced by `adaptive` (migration 0019),+ # so the guidance must NOT tell users to switch to "Both".+ # When ``primary_engine`` is supplied and equals ``target``, Adaptive+ # is reliable and gets mentioned. When the primary differs (or is+ # absent), only the explicit compatible scope is named.("scope_mismatch_private_only","arxiv",- ["Private only", "Egress Scope"],+ ["Private only", "Egress Scope", "Adaptive"],),("scope_mismatch_public_only","library",- ["Public only", "Egress Scope"],+ ["Public only", "Egress Scope", "Adaptive"],),("strict_not_primary", "wikipedia", ["Strict", "primary"]),# Inference blocks name the require-local toggle.@@ -34,12 +39,114 @@ from local_deep_research.security.egress.guidance import denial_guidance],)def test_guidance_is_clear_and_actionable(reason, target, must_contain):- msg = denial_guidance(reason, target=target)+ # Pass primary_engine=target_id so the scope-mismatch messages mention+ # Adaptive (the legacy happy-path test).+ msg = denial_guidance(+ reason, target=target, target_id=target, primary_engine=target+ )assert msg and len(msg) > 20for needle in must_contain:assert needle in msg, f"{reason}: expected '{needle}' in: {msg}"+def test_scope_mismatch_never_recommends_retired_both_scope():+ # Regression: guidance.py used to say "change your Egress Scope to Both or+ # Public only". `both` was deprecated (migration 0019), so the copy must+ # point at Adaptive (default) instead — at least when the primary engine+ # is the blocked target. (When the primary is something else we omit+ # Adaptive entirely; see the test below.)+ for reason in ("scope_mismatch_private_only", "scope_mismatch_public_only"):+ msg = denial_guidance(+ reason,+ target="arxiv",+ target_id="arxiv",+ primary_engine="arxiv",+ )+ assert "Both" not in msg, f"{reason}: guidance still references 'Both'"+ assert "Adaptive" in msg, (+ f"{reason}: guidance should recommend 'Adaptive' when target is primary"+ )+++def test_scope_mismatch_omits_adaptive_when_target_is_not_primary():+ # Adaptive (default) follows the saved primary engine, so if the+ # blocked target is NOT the primary, switching to Adaptive may resolve+ # back to the same restrictive scope and the block would persist. In+ # that case the explicit compatible scope is the only reliable fix —+ # the message must NOT mislead the user into trying Adaptive first.+ msg_private = denial_guidance(+ "scope_mismatch_private_only",+ target="arxiv",+ target_id="arxiv",+ primary_engine="library",+ )+ assert "Adaptive" not in msg_private, (+ "Adaptive must NOT be mentioned when the blocked target isn't the primary"+ )+ assert "Public only" in msg_private+ assert (+ "Private only" in msg_private+ ) # the current scope, in the "what" part++ msg_public = denial_guidance(+ "scope_mismatch_public_only",+ target="library",+ target_id="library",+ primary_engine="arxiv",+ )+ assert "Adaptive" not in msg_public+ assert "Private only" in msg_public+ # Collection-specific escape hatch is preserved on this reason.+ assert "mark it Public on the collection page" in msg_public++ # And the symmetric happy-path: target == primary => Adaptive IS named.+ msg_match = denial_guidance(+ "scope_mismatch_public_only",+ target="library",+ target_id="library",+ primary_engine="library",+ )+ assert "Adaptive" in msg_match+ assert "Private only" in msg_match+++def test_scope_mismatch_omits_adaptive_when_primary_engine_unknown():+ # No primary_engine supplied (e.g. we couldn't resolve it for this run).+ # We must NOT mention Adaptive as a remedy because we don't know if it+ # would help — fall back to the explicit compatible scope only.+ msg = denial_guidance("scope_mismatch_private_only", target="arxiv")+ assert "Adaptive" not in msg+ assert "Public only" in msg+++def test_adaptive_check_uses_raw_target_id_not_display_target():+ # research_routes formats the display ``target`` as+ # ``"Search engine 'library'"`` but passes the raw ``"library"`` via+ # ``target_id`` for the Adaptive comparison. The display string must+ # NOT participate in the comparison (it would always fail) — only+ # ``target_id`` does.+ msg_match = denial_guidance(+ "scope_mismatch_public_only",+ target="Search engine 'library'",+ target_id="library",+ primary_engine="library",+ )+ assert "Adaptive" in msg_match, (+ "When the raw target_id matches primary_engine, Adaptive must be "+ "named — display-string wrapping must not break the check."+ )++ # And the inverse: the raw ids differ, even though the display strings+ # would look the same.+ msg_diff = denial_guidance(+ "scope_mismatch_public_only",+ target="Search engine 'library'",+ target_id="library",+ primary_engine="arxiv",+ )+ assert "Adaptive" not in msg_diff++def test_guidance_inserts_target():msg = denial_guidance("scope_mismatch_private_only", target="arxiv")assert "arxiv" in msgdiff --git a/tests/web/routes/test_research_routes_policy.py b/tests/web/routes/test_research_routes_policy.pyindex 57ee65ee3d..7c786c47eb 100644--- a/tests/web/routes/test_research_routes_policy.py+++ b/tests/web/routes/test_research_routes_policy.py@@ -89,13 +89,114 @@ class TestPrecheckEnginePolicy:result = _precheck_engine_policy(mgr, {}, "arxiv", "user")assert result is None- def test_forbidden_engine_returns_400(self, app_ctx):- # PUBLIC_ONLY + a local engine (library) => refused => 400.+ def test_forbidden_engine_response_flags_egress_scope_field(self, app_ctx):+ # The 400 must tell the frontend WHICH field to highlight so the error+ # can be shown inline on the Egress Scope dropdown (not just as a+ # top-of-form alert the user may have scrolled past).mgr = _mgr({"policy.egress_scope": "public_only"})result = _precheck_engine_policy(mgr, {}, "library", "user")assert result is not None- _resp, status = result- assert status == 400+ body = result[0].get_json()+ assert result[1] == 400+ assert body["field"] == "policy_egress_scope"+ # And the human-readable message is still present.+ assert body["message"] and "Egress Scope" in body["message"]+ assert body["reason"] == "scope_mismatch_public_only"++ def test_strict_non_primary_response_flags_egress_scope_field(+ self, app_ctx+ ):+ # STRICT + a non-primary engine => strict_not_primary. Same fix as+ # the scope_mismatch cases: change Egress Scope away from Strict.+ mgr = _mgr(+ {"policy.egress_scope": "strict"},+ primary="arxiv",+ )+ result = _precheck_engine_policy(mgr, {}, "library", "user")+ assert result is not None+ body = result[0].get_json()+ assert result[1] == 400+ assert body["field"] == "policy_egress_scope"+ assert body["reason"] == "strict_not_primary"++ def test_internal_error_response_omits_field_attribution(+ self, app_ctx, monkeypatch+ ):+ # internal_error is a server-side issue — no form field fixes it, so+ # ``field`` must be ``null`` (NOT the egress-scope dropdown, which+ # would mislead the user into thinking the scope is the problem).+ # ``evaluate_engine`` is imported lazily from the policy module inside+ # ``_precheck_engine_policy`` (see the local-import note in the+ # implementation), so patching the source module is enough — every+ # call into it resolves through the same module attribute.+ from local_deep_research.security.egress import policy as policy_mod++ def _boom(*_args, **_kwargs):+ return policy_mod.Decision(False, "internal_error")++ monkeypatch.setattr(policy_mod, "evaluate_engine", _boom)+ mgr = _mgr({"policy.egress_scope": "public_only"})+ result = _precheck_engine_policy(mgr, {}, "arxiv", "user")+ assert result is not None+ body = result[0].get_json()+ assert result[1] == 400+ assert body["field"] is None+ assert body["reason"] == "internal_error"++ def test_engine_unknown_response_omits_field_attribution(+ self, app_ctx, monkeypatch+ ):+ # engine_unknown: the engine isn't in the registry and isn't a+ # collection. Changing the egress scope won't help, so the field+ # hint must NOT point at the egress dropdown — the user has to pick+ # a different engine, which is shown via the alert text.+ from local_deep_research.security.egress import policy as policy_mod++ monkeypatch.setattr(+ policy_mod,+ "evaluate_engine",+ lambda *_a, **_k: policy_mod.Decision(False, "engine_unknown"),+ )+ mgr = _mgr({"policy.egress_scope": "public_only"})+ result = _precheck_engine_policy(mgr, {}, "arxiv", "user")+ assert result is not None+ body = result[0].get_json()+ assert result[1] == 400+ assert body["field"] is None+ assert body["reason"] == "engine_unknown"++ def test_scope_mismatch_message_omits_adaptive_when_target_isnt_primary(+ self, app_ctx+ ):+ # Adaptive (default) follows the saved primary engine. If the+ # blocked engine is NOT the primary (library blocked under+ # public_only while primary=arxiv), Adaptive would resolve back to+ # public_only and library would still be denied. So the message+ # must point only at the explicit compatible scope (Private only)+ # — not suggest Adaptive.+ mgr = _mgr({"policy.egress_scope": "public_only"}, primary="arxiv")+ result = _precheck_engine_policy(mgr, {}, "library", "user")+ assert result is not None+ body = result[0].get_json()+ assert body["message"].startswith(+ "Search engine 'library' was blocked because your Egress Scope "+ "is set to Public only"+ )+ # Explicit remedy named, Adaptive NOT mentioned.+ assert "Private only" in body["message"]+ assert "Adaptive" not in body["message"]++ def test_scope_mismatch_message_mentions_adaptive_when_target_is_primary(+ self, app_ctx+ ):+ # When the blocked engine IS the primary, Adaptive would follow the+ # primary into the compatible bucket, so mentioning it is reliable.+ mgr = _mgr({"policy.egress_scope": "public_only"}, primary="library")+ result = _precheck_engine_policy(mgr, {}, "library", "user")+ assert result is not None+ body = result[0].get_json()+ assert "Adaptive" in body["message"]+ assert "Private only" in body["message"]def test_corrupt_scope_returns_400(self, app_ctx):mgr = _mgr({"policy.egress_scope": "garbage"})