~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 per-setting validation errors on settings save (#6323)
LearningCircuitcaf957026c5f
diff --git a/changelog.d/6322.bugfix.md b/changelog.d/6322.bugfix.mdnew file mode 100644index 0000000000..565a778f2d--- /dev/null+++ b/changelog.d/6322.bugfix.md@@ -0,0 +1,3 @@+Settings save failures now show *which* setting failed and *why* instead of a bare "Validation errors". `fetchWithErrorHandling` attaches the parsed error body to the thrown error (`error.details`), and the settings page renders the per-setting details from the server's `errors` array — both inline on the offending control (same `.ldr-settings-error-message` block client-side validation uses, cleared on the next edit) and in the banner message.++Most visible for self-hosted SearXNG: saving a LAN/localhost instance URL used to fail with only "Validation errors"; the UI now shows the actual SSRF-guard rejection including the operator opt-ins (`LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST`, env-pinned URL, `LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true`) that the server already sent but the client discarded.diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.jsindex 24b48e19c0..df2c686f21 100644--- a/src/local_deep_research/web/static/js/components/settings.js+++ b/src/local_deep_research/web/static/js/components/settings.js@@ -649,6 +649,164 @@}}+ /**+ * How many per-setting failures the banner spells out before the rest+ * are summarised as "+N more". The banner is a fixed, dismiss-less+ * overlay with no max-height, so an unbounded join can cover the page+ * for its read window — but the inline marks only reach the keys the+ * settings page actually rendered (a hidden setting, a brand-new key+ * the namespace guard rejects before it reaches the form, or a key+ * outside the active tab/search never gets a control), so for those+ * the banner is the only surface. The slice below is biased so an+ * entry with no inline mark is shown first, and only bumped off the+ * banner once there are more than this many of them.+ */+ const MAX_BANNER_SETTING_ERRORS = 5;++ const SETTING_CONTROL_SELECTOR = 'input, select, textarea';++ /**+ * Resolve a `[data-key]` element down to the form control it names:+ * itself when it already is one, otherwise the first descendant+ * control (see renderSettingItem's `.ldr-settings-item` markup and the+ * `[data-key]` copy initAutoSaveHandlers stamps from `[name]` at+ * ~329-331).+ * @param {string} escaped - A `CSS.escape()`-d setting key+ * @returns {HTMLElement|null}+ */+ function findKeyedControl(escaped) {+ const keyed = document.querySelector(`[data-key="${escaped}"]`);+ if (!keyed) return null;+ if (keyed.matches(SETTING_CONTROL_SELECTOR)) return keyed;+ return keyed.querySelector(SETTING_CONTROL_SELECTOR);+ }++ /**+ * Resolve the form control for a setting key. `[name]` is carried by+ * the control itself, while `[data-key]` sits on the+ * `.ldr-settings-item` wrapper (renderSettingItem) as well as on some+ * controls directly — so a combined `[data-key], [name]` selector+ * returns the wrapper in document order and the control never picks up+ * the error styling. Query `[name]` first, preferring a control the+ * user can see over a hidden companion (a checkbox's hidden fallback,+ * or a custom dropdown's value mirror — for `llm.provider`,+ * `llm.model` and `search.tool` the mirror is the *only* `[name]`+ * match, so when every named match is hidden we fall through to the+ * `[data-key]` control — the visible `.ldr-custom-dropdown-input` —+ * before settling for the mirror). Resolve a `[data-key]` wrapper down+ * to the control it contains.+ * @param {string} key - The setting key+ * @returns {HTMLElement|null} The control, or null when not rendered+ */+ function findSettingControl(key) {+ if (!key) return null;+ const escaped = CSS.escape(key);+ const named = Array.from(+ document.querySelectorAll(`[name="${escaped}"]`)+ );+ // Prefer a control the user can see over a hidden companion input+ // (checkbox fallbacks, custom-dropdown value mirrors).+ const visible = named.find(el => el.type !== 'hidden');+ if (visible) return visible;+ if (named.length > 0) {+ const keyed = findKeyedControl(escaped);+ if (keyed && keyed.type !== 'hidden') return keyed;+ return named[0];+ }+ return findKeyedControl(escaped);+ }++ /**+ * The `.ldr-settings-item` wrapper for a setting key, resolved through+ * the control when there is one and through `[data-key]` otherwise.+ * @param {string} key - The setting key+ * @returns {HTMLElement|null}+ */+ function findSettingItem(key) {+ if (!key) return null;+ const control = findSettingControl(key);+ const item = control && control.closest('.ldr-settings-item');+ if (item) return item;+ const keyed = document.querySelector(`[data-key="${CSS.escape(key)}"]`);+ return keyed ? keyed.closest('.ldr-settings-item') : null;+ }++ /**+ * Human label for a setting key, read off the rendered form. The+ * egress guards return `{key, error}` with no display name, so without+ * this the banner falls back to the raw dotted key.+ * @param {string} key - The setting key+ * @returns {string} The label text, or '' when the key is not rendered+ */+ function findSettingLabel(key) {+ const item = findSettingItem(key);+ const label = item && item.querySelector('label');+ if (!label) return '';+ return label.textContent.replace(/\s+/g, ' ').trim();+ }++ /**+ * Normalize the structured per-setting validation details the settings+ * save routes return with a 400 "Validation errors" response (see+ * web/routers/settings.py). Covers both producer shapes: per-key+ * validation entries ({key, name, error}) and egress-guard rejections+ * ({key, error}), whose message already opens with the key itself.+ * @param {Array|undefined} errors - The raw `errors` array from the response body+ * @returns {Array<{key: string, label: string, error: string, message: string}>}+ */+ function formatServerSettingErrors(errors) {+ if (!Array.isArray(errors)) return [];+ return errors+ .map(err => {+ if (!err || typeof err !== 'object') return null;+ if (err.error === undefined || err.error === null) return null;+ const key = typeof err.key === 'string' ? err.key : '';+ // A present-but-falsy error ('' / 0) still names a setting+ // the server refused; dropping it would restore the bare+ // "Validation errors" banner this code exists to replace.+ const error = (err.error ? String(err.error) : '').trim()+ || 'Validation error';+ // Prefer the label the user actually sees over the dotted+ // key; `name` is only present on the per-key shape.+ const name = typeof err.name === 'string' ? err.name : '';+ const label = findSettingLabel(key) || name || key || 'Setting';+ // The egress guards open their message with the key, so+ // prefixing would print the setting's name twice in a row.+ const alreadyNamed = [label, key].some(+ prefix => prefix+ && error.toLowerCase().startsWith(prefix.toLowerCase())+ );+ return {+ key,+ label,+ error,+ message: alreadyNamed ? error : `${label}: ${error}`,+ };+ })+ .filter(Boolean);+ }++ /**+ * Render server-side save validation failures on the offending+ * controls. The banner message alone cannot say WHICH setting failed;+ * the inline .ldr-settings-error-message block — the same one+ * client-side validation uses — can, and it persists until the user+ * edits the field (handleInputChange clears it on the next change).+ * @param {Array<{key: string, error: string}>} errorDetails+ * @returns {Set<string>} The keys that had a rendered control to mark+ */+ function markInvalidSettingsFromServer(errorDetails) {+ const markedKeys = new Set();+ errorDetails.forEach(({ key, error }) => {+ const control = findSettingControl(key);+ if (control) {+ markInvalidInput(control, error);+ markedKeys.add(key);+ }+ });+ return markedKeys;+ }+/*** Toggle the inline "no model selected" warning shown under the* Language Model dropdown. The element itself lives in the settings@@ -3088,12 +3246,46 @@SafeLogger.error('[submitSettingsData] AJAX Error:', error);SafeLogger.error('[submitSettingsData] Error details:', error.message);- // Show error message+ // 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+ );+ 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('Error saving settings: ' + error.message, 'error', 5000);- showAlert('Error saving settings: ' + error.message, 'error', true);+ window.ui.showMessage(fullMessage, 'error', errorDuration);+ showAlert(fullMessage, 'error', true);} else {- showAlert('Error saving settings: ' + error.message, 'error', false);+ showAlert(fullMessage, 'error', false);}// Remove loading statediff --git a/src/local_deep_research/web/static/js/services/api.js b/src/local_deep_research/web/static/js/services/api.jsindex ac6204bd43..6b8b680834 100644--- a/src/local_deep_research/web/static/js/services/api.js+++ b/src/local_deep_research/web/static/js/services/api.js@@ -133,12 +133,26 @@ async function fetchWithErrorHandling(url, options = {}) {// the UI lost session-expired / CSRF-missing messages.if (!response.ok) {const errorData = await response.json().catch(() => ({}));- throw new Error(+ const error = new Error(errorData?.message ||errorData?.error ||errorData?.detail ||`API Error: ${response.status} ${response.statusText}`);+ // Preserve the parsed error body so callers can surface+ // structured details the single-message throw discards — e.g.+ // the per-setting `errors` array the settings save routes+ // return alongside the generic "Validation errors" message.+ // Only a non-empty object body has anything worth forwarding:+ // null bodies and unparseable payloads resolve to nothing.+ if (+ errorData &&+ typeof errorData === 'object' &&+ Object.keys(errorData).length > 0+ ) {+ error.details = errorData;+ }+ throw error;}// Parse the responsediff --git a/tests/js/components/settings-save-validation-errors.test.js b/tests/js/components/settings-save-validation-errors.test.jsnew file mode 100644index 0000000000..97c0dde74d--- /dev/null+++ b/tests/js/components/settings-save-validation-errors.test.js@@ -0,0 +1,354 @@+/**+ * Runtime contract for the settings save failure path: the per-setting+ * `errors` array a 400 "Validation errors" response carries has to reach+ * both the offending control (inline, via .ldr-settings-error-message) and+ * the banner, without printing the setting's name twice and without the+ * banner growing without bound.+ *+ * This drives the real submitSettingsData catch block against real+ * .ldr-settings-item markup, so deleting formatServerSettingErrors or+ * markInvalidSettingsFromServer fails it.+ */++import '@js/config/urls.js';+import '@js/services/api.js';+import '@js/utils/alert-helpers.js';+import '@js/utils/provider-options.js';+import '@js/utils/value-helpers.js';++// Verbatim from security/egress/validators.py::_engine_url_error — the+// message opens with the key, and the entry carries no display `name`.+const SEARXNG_URL_KEY = 'search.engine.web.searxng.default_params.instance_url';+const SEARXNG_PRIVATE_URL_ERROR =+ `${SEARXNG_URL_KEY} points at a private, loopback, or link-local address. `+ + 'A public search engine proxies the internet, so an internal URL is '+ + 'refused to prevent it being used to reach your private network. '+ + 'Self-hosted instances on localhost/LAN are still supported, but the '+ + 'server operator must approve them in the server environment: add this '+ + 'exact URL origin to LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST '+ + '(comma-separated scheme://host:port entries), or pin the URL via its '+ + 'LDR_ environment variable (as the bundled docker-compose.yml does), or '+ + 'set LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true to allow all private '+ + 'addresses. Only one of these is needed; restart after changing. See '+ + 'docs/SearXNG-Setup.md.';++const flushPromises = async (turns = 8) => {+ for (let turn = 0; turn < turns; turn += 1) {+ await Promise.resolve();+ }+};++function validationErrorResponse(errors) {+ return new Response(+ JSON.stringify({+ status: 'error',+ message: 'Validation errors',+ errors,+ }),+ { status: 400, headers: { 'Content-Type': 'application/json' } },+ );+}++function submitSettingsForm() {+ document.getElementById('settings-form').dispatchEvent(new Event(+ 'submit',+ { bubbles: true, cancelable: true },+ ));+}++async function saveAndFail(errors) {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(+ validationErrorResponse(errors),+ ));+ submitSettingsForm();+ await flushPromises();+ expect(window.ui.showMessage).toHaveBeenCalled();+ const [message, level] = window.ui.showMessage.mock.calls.at(-1);+ expect(level).toBe('error');+ return message;+}++function inlineErrorFor(key) {+ const item = document.querySelector(`[data-key="${CSS.escape(key)}"]`);+ const message = item.querySelector('.ldr-settings-error-message');+ return message ? message.textContent : null;+}++beforeAll(async () => {+ document.head.insertAdjacentHTML(+ 'beforeend',+ '<meta name="csrf-token" content="csrf-settings-validation">',+ );+ // The real .ldr-settings-item shape: [data-key] on the wrapper, the+ // label in the header, and [name] on the control itself.+ document.body.innerHTML = `+ <form id="settings-form">+ <div+ class="ldr-settings-item form-group"+ data-key="search.engine.web.searxng.default_params.instance_url"+ >+ <div class="ldr-settings-item-header">+ <label for="searxng-instance-url">+ Instance Url+ </label>+ </div>+ <input+ id="searxng-instance-url"+ class="ldr-settings-input"+ type="text"+ name="search.engine.web.searxng.default_params.instance_url"+ value="http://localhost:8080"+ >+ </div>+ <div class="ldr-settings-item form-group" data-key="app.theme">+ <div class="ldr-settings-item-header">+ <label for="app-theme">+ Theme+ </label>+ </div>+ <input+ id="app-theme"+ class="ldr-settings-input"+ type="text"+ name="app.theme"+ value="light"+ >+ </div>+ <div class="ldr-settings-item form-group" data-key="app.enable_thing">+ <div class="ldr-settings-checkbox-container">+ <label class="ldr-checkbox-label" for="app-enable-thing">+ <!-- Hidden fallback ensures unchecked state is submitted;+ modelled on renderSettingItem's 'checkbox' case. -->+ <input type="hidden"+ name="app.enable_thing"+ id="app-enable-thing_hidden_fallback"+ value="false"+ class="ldr-checkbox-hidden-fallback">+ <input type="checkbox" id="app-enable-thing" name="app.enable_thing"+ class="ldr-settings-checkbox"+ data-hidden-fallback="app-enable-thing_hidden_fallback">+ <!-- Internal whitespace run (line break + indent) so the+ label-collapse test has something to collapse. -->+ <span class="ldr-checkbox-text">Enable+ Thing</span>+ </label>+ </div>+ </div>+ <div class="ldr-settings-item form-group" data-key="llm.provider">+ <div class="ldr-settings-item-header">+ <label for="llm.provider" id="setting-llm-provider-label">+ LLM Provider+ </label>+ </div>+ <!-- Modelled on renderCustomDropdownHTML: the visible input+ carries [data-key], the hidden mirror carries [name]. -->+ <div class="ldr-custom-dropdown" id="setting-llm-provider-dropdown">+ <input type="text"+ id="llm.provider"+ data-key="llm.provider"+ class="ldr-custom-dropdown-input"+ placeholder="Select a provider"+ autocomplete="off"+ role="combobox"+ aria-labelledby="setting-llm-provider-label">+ <input type="hidden" name="llm.provider" id="llm.provider_hidden" value="openai">+ <div class="ldr-custom-dropdown-list" id="setting-llm-provider-dropdown-list" role="listbox"></div>+ </div>+ </div>+ <section id="raw-config" style="display: none">+ <textarea id="raw_config_editor">{}</textarea>+ </section>+ <div id="settings-alert"></div>+ </form>+ `;+ expect(+ document.querySelector(`[data-key="${SEARXNG_URL_KEY}"]`).tagName,+ ).toBe('DIV');+ window.ui = { showMessage: vi.fn() };++ const needsDomReady = document.readyState === 'loading';+ await import('@js/components/settings.js');+ if (needsDomReady) {+ document.dispatchEvent(new Event('DOMContentLoaded'));+ }+});++beforeEach(() => {+ document.querySelectorAll('.ldr-settings-error-message')+ .forEach(node => node.remove());+ document.querySelectorAll('.ldr-settings-error')+ .forEach(node => node.classList.remove('ldr-settings-error'));+ document.getElementById('settings-form').className = '';+ window.ui = { showMessage: vi.fn() };+});++afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++afterAll(() => {+ document.querySelector('meta[name="csrf-token"]')?.remove();+ document.body.replaceChildren();+ delete window.ui;+});++it('marks the control and names the setting once for an egress rejection', async () => {+ const message = await saveAndFail([+ { key: SEARXNG_URL_KEY, error: SEARXNG_PRIVATE_URL_ERROR },+ ]);++ // Inline, on the offending control's settings item — outlives the banner.+ expect(inlineErrorFor(SEARXNG_URL_KEY)).toBe(SEARXNG_PRIVATE_URL_ERROR);++ // The CONTROL carries the error class, not just its wrapper: the CSS+ // border rule is meant for the input, and the wrapper's own border is+ // the row separator.+ const control = document.getElementById('searxng-instance-url');+ expect(control.classList.contains('ldr-settings-error')).toBe(true);+ expect(control.closest('.ldr-settings-item').classList+ .contains('ldr-settings-error')).toBe(true);++ // The guard's message already opens with the key, so the banner must+ // not prefix a label onto it: the key appears exactly once.+ expect(message).toBe(+ `Error saving settings: Validation errors — ${SEARXNG_PRIVATE_URL_ERROR}`,+ );+ expect(message.split(SEARXNG_URL_KEY)).toHaveLength(2);+ expect(message).not.toContain(`${SEARXNG_URL_KEY}: ${SEARXNG_URL_KEY}`);+ expect(message).not.toContain('Instance Url:');+});++it('labels a per-key rejection from the rendered form, not the dotted key', async () => {+ const message = await saveAndFail([+ {+ key: 'app.theme',+ name: 'app_theme',+ error: 'Value must be one of: light, dark',+ },+ ]);++ expect(inlineErrorFor('app.theme')).toBe('Value must be one of: light, dark');+ expect(document.getElementById('app-theme').classList+ .contains('ldr-settings-error')).toBe(true);+ // The form's own label wins over the server's `name` and over the key.+ expect(message).toBe(+ 'Error saving settings: Validation errors'+ + ' — Theme: Value must be one of: light, dark',+ );+});++it('falls back to the server name for a setting not on this page', async () => {+ const message = await saveAndFail([+ { key: 'llm.temperature', name: 'Temperature', error: 'Value must be a number' },+ ]);++ expect(message).toContain('Temperature: Value must be a number');+});++it('falls back to the key when neither the form nor the server names it', async () => {+ const message = await saveAndFail([+ { key: 'llm.max_tokens', error: 'Value must be at least 1' },+ ]);++ expect(message).toContain('llm.max_tokens: Value must be at least 1');+});++it('keeps a present-but-empty error instead of dropping the entry', async () => {+ const message = await saveAndFail([{ key: 'app.theme', error: '' }]);++ expect(inlineErrorFor('app.theme')).toBe('Validation error');+ expect(message).toBe(+ 'Error saving settings: Validation errors — Theme: Validation error',+ );+});++it('caps the banner at five entries with a "+N more" tail', async () => {+ // None of these keys are rendered, so the no-inline-mark ordering bias+ // (tested separately below) has nothing to reorder here — this test is+ // only about the cap itself.+ const errors = Array.from({ length: 7 }, (unused, index) => ({+ key: `app.unknown_${index}`,+ name: `Unknown ${index}`,+ error: `rejected ${index}`,+ }));++ const message = await saveAndFail(errors);++ expect(message).toContain('Unknown 0: rejected 0');+ expect(message).toContain('Unknown 4: rejected 4');+ expect(message).not.toContain('Unknown 5');+ expect(message).not.toContain('Unknown 6');+ // Five spelled-out entries plus the "+N more" tail.+ expect(message).toContain('+2 more');+ // Separator-safe: counting `Unknown N:` occurrences (rather than+ // splitting on ' • ') can't be skewed by an error message that itself+ // contains ' • '.+ expect((message.match(/Unknown \d+:/g) || []).length).toBe(5);+});++it('marks the checkbox and the visible dropdown input, not their hidden companions, and collapses the label', async () => {+ const message = await saveAndFail([+ { key: 'app.enable_thing', error: 'must be a boolean' },+ { key: 'llm.provider', error: 'must be a known provider' },+ ]);++ const checkbox = document.getElementById('app-enable-thing');+ const checkboxHiddenFallback = document.getElementById('app-enable-thing_hidden_fallback');+ expect(checkbox.classList.contains('ldr-settings-error')).toBe(true);+ expect(checkboxHiddenFallback.classList.contains('ldr-settings-error')).toBe(false);++ const dropdownInput = document.getElementById('llm.provider');+ const dropdownHiddenMirror = document.getElementById('llm.provider_hidden');+ expect(dropdownInput.classList.contains('ldr-custom-dropdown-input')).toBe(true);+ expect(dropdownInput.classList.contains('ldr-settings-error')).toBe(true);+ expect(dropdownHiddenMirror.classList.contains('ldr-settings-error')).toBe(false);++ // The checkbox label collapses its internal whitespace run (a line+ // break plus indentation between "Enable" and "Thing" in the fixture).+ expect(message).toContain('Enable Thing: must be a boolean');+ expect(message).toContain('LLM Provider: must be a known provider');+});++it('sorts entries with no rendered control to the front of a capped banner', async () => {+ // Five entries that DO resolve to a rendered control (one key used+ // twice), placed first; two that don't, placed LAST. A plain+ // slice(0, 5) would drop the last two — the fix biases them to the+ // front instead, so they still make the cut.+ const renderedRejections = [+ SEARXNG_URL_KEY, 'app.theme', 'app.enable_thing', 'llm.provider', 'app.theme',+ ].map((key, index) => ({ key, error: `rendered rejection ${index}` }));+ const errors = [+ ...renderedRejections,+ { key: 'app.unknown_x', name: 'Unknown X', error: 'unrendered rejection x' },+ { key: 'app.unknown_y', name: 'Unknown Y', error: 'unrendered rejection y' },+ ];+ expect(errors).toHaveLength(7);++ const message = await saveAndFail(errors);++ // The two unrendered entries made it into the capped banner.+ expect(message).toContain('Unknown X: unrendered rejection x');+ expect(message).toContain('Unknown Y: unrendered rejection y');+ // Only 3 of the 5 rendered-control rejections fit in what's left.+ expect(message).toContain('rendered rejection 0');+ expect(message).toContain('rendered rejection 1');+ expect(message).toContain('rendered rejection 2');+ expect(message).not.toContain('rendered rejection 3');+ expect(message).not.toContain('rendered rejection 4');+ expect(message).toContain('+2 more');+});++it('leaves the banner alone when the failure carries no details', async () => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(+ JSON.stringify({ message: 'Validation errors' }),+ { status: 400, headers: { 'Content-Type': 'application/json' } },+ )));+ submitSettingsForm();+ await flushPromises();++ expect(window.ui.showMessage).toHaveBeenLastCalledWith(+ 'Error saving settings: Validation errors', 'error', 5000,+ );+ expect(inlineErrorFor(SEARXNG_URL_KEY)).toBeNull();+});diff --git a/tests/js/services/api.test.js b/tests/js/services/api.test.jsindex 3ee7491c89..36f794e6bb 100644--- a/tests/js/services/api.test.js+++ b/tests/js/services/api.test.js@@ -15,6 +15,23 @@ import '@js/services/api.js';const { fetchWithErrorHandling, shouldRedirectToLoginOn401 } = window.api;+// Verbatim from the egress guard that motivated error.details:+// security/egress/validators.py::_engine_url_error. The message opens with+// the key and the entry carries no display `name`.+const SEARXNG_URL_KEY = 'search.engine.web.searxng.default_params.instance_url';+const SEARXNG_PRIVATE_URL_ERROR =+ `${SEARXNG_URL_KEY} points at a private, loopback, or link-local address. `+ + 'A public search engine proxies the internet, so an internal URL is '+ + 'refused to prevent it being used to reach your private network. '+ + 'Self-hosted instances on localhost/LAN are still supported, but the '+ + 'server operator must approve them in the server environment: add this '+ + 'exact URL origin to LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST '+ + '(comma-separated scheme://host:port entries), or pin the URL via its '+ + 'LDR_ environment variable (as the bundled docker-compose.yml does), or '+ + 'set LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true to allow all private '+ + 'addresses. Only one of these is needed; restart after changing. See '+ + 'docs/SearXNG-Setup.md.';+describe('shouldRedirectToLoginOn401', () => {const originalLocation = window.location;@@ -179,6 +196,75 @@ describe('fetchWithErrorHandling — 401 handling', () => {);});+ it('attaches the parsed error body as error.details so callers can surface structured details', async () => {+ globalThis.fetch = vi.fn(() =>+ Promise.resolve(new Response(+ JSON.stringify({+ status: 'error',+ message: 'Validation errors',+ errors: [+ {+ key: SEARXNG_URL_KEY,+ error: SEARXNG_PRIVATE_URL_ERROR,+ },+ ],+ }),+ { status: 400, statusText: 'Bad Request' },+ ))+ );++ const thrown = await fetchWithErrorHandling('/settings/api/save')+ .then(() => { throw new Error('expected a rejection'); })+ .catch(e => e);++ expect(thrown).toBeInstanceOf(Error);+ expect(thrown.message).toBe('Validation errors');+ expect(thrown.details.status).toBe('error');+ expect(thrown.details.errors).toHaveLength(1);+ expect(thrown.details.errors[0].key).toBe(SEARXNG_URL_KEY);+ // The guard sends no display `name`, and its message opens with the+ // key itself — the shape consumers have to render around.+ expect(thrown.details.errors[0].name).toBeUndefined();+ expect(thrown.details.errors[0].error).toBe(SEARXNG_PRIVATE_URL_ERROR);+ expect(thrown.details.errors[0].error.startsWith(SEARXNG_URL_KEY))+ .toBe(true);+ });++ it('does not attach details when the error body is JSON null', async () => {+ globalThis.fetch = vi.fn(() =>+ Promise.resolve(new Response(+ 'null',+ { status: 500, statusText: 'Internal Server Error' },+ ))+ );++ const thrown = await fetchWithErrorHandling('/api/history')+ .then(() => { throw new Error('expected a rejection'); })+ .catch(e => e);++ expect(thrown.message).toBe('API Error: 500 Internal Server Error');+ expect(thrown.details).toBeUndefined();+ });++ it('does not attach details for an empty object body', async () => {+ // What the `.catch(() => ({}))` fallback produces for an+ // unparseable body, and the only case the non-empty gate decides.+ globalThis.fetch = vi.fn(() =>+ Promise.resolve(new Response(+ '{}',+ { status: 500, statusText: 'Internal Server Error' },+ ))+ );++ const thrown = await fetchWithErrorHandling('/api/history')+ .then(() => { throw new Error('expected a rejection'); })+ .catch(e => e);++ expect(thrown.message).toBe('API Error: 500 Internal Server Error');+ expect(thrown.details).toBeUndefined();+ expect('details' in thrown).toBe(false);+ });+it('uses the HTTP status fallback for a non-2xx JSON null body', async () => {globalThis.fetch = vi.fn(() =>Promise.resolve(new Response(