~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(settings): use shared API error handling (#5075)
LearningCircuit58c2a93c848e
diff --git a/changelog.d/+settings-fetch-error-handling.bugfix.md b/changelog.d/+settings-fetch-error-handling.bugfix.mdnew file mode 100644index 0000000000..bbfed1bf81--- /dev/null+++ b/changelog.d/+settings-fetch-error-handling.bugfix.md@@ -0,0 +1 @@+Settings requests now report server errors instead of treating failed responses as valid settings data.diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.jsindex e94e1679c0..3126f42db3 100644--- a/src/local_deep_research/web/static/js/components/settings.js+++ b/src/local_deep_research/web/static/js/components/settings.js@@ -1011,8 +1011,7 @@// Only run this for the main settings dashboardif (!settingsContent) return;- fetch(URLS.SETTINGS_API.BASE)- .then(response => response.json())+ window.api.fetchWithErrorHandling(URLS.SETTINGS_API.BASE).then(data => {if (data.status === 'success') {// Process settings to handle object values and check for corruption@@ -1388,8 +1387,7 @@const contentElement = document.getElementById('data-location-content');if (!contentElement) return;- fetch('/settings/api/data-location')- .then(response => response.json())+ window.api.fetchWithErrorHandling('/settings/api/data-location').then(data => {let html = '<div class="ldr-data-location-details">';@@ -1772,8 +1770,7 @@const contentElement = document.getElementById('ldr-backup-status-content');if (!contentElement) return;- fetch(URLS.SETTINGS_API.BACKUP_STATUS)- .then(response => response.json())+ window.api.fetchWithErrorHandling(URLS.SETTINGS_API.BACKUP_STATUS).then(data => {const esc = window.escapeHtml || (s => String(s || ''));@@ -2756,17 +2753,10 @@const requestTimestamp = Date.now();lastSettingsUpdateTimestamp = requestTimestamp;- fetch(URLS.SETTINGS_API.SAVE_ALL_SETTINGS, {+ window.api.fetchWithErrorHandling(URLS.SETTINGS_API.SAVE_ALL_SETTINGS, {method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'X-CSRFToken': getCsrfToken()- },body: JSON.stringify(formData),})- .then(response => {- return response.json();- }).then(data => {if (data.status === 'success') {// Show success indicator on the source element@@ -3110,14 +3100,9 @@// Show confirmation dialogif (confirm('Are you sure you want to reset ALL settings to their default values? This cannot be undone.')) {// Call the reset to defaults API- fetch(URLS.SETTINGS_API.RESET_TO_DEFAULTS, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'X-CSRFToken': getCsrfToken()- }+ window.api.fetchWithErrorHandling(URLS.SETTINGS_API.RESET_TO_DEFAULTS, {+ method: 'POST'})- .then(response => response.json()).then(data => {if (data.status === 'success') {showAlert('Settings have been reset to defaults. Reloading page...', 'success');@@ -3321,14 +3306,9 @@*/function handleFixCorruptedSettings() {// Call the fix corrupted settings API- fetch(URLS.SETTINGS_API.FIX_CORRUPTED_SETTINGS, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'X-CSRFToken': getCsrfToken()- }+ window.api.fetchWithErrorHandling(URLS.SETTINGS_API.FIX_CORRUPTED_SETTINGS, {+ method: 'POST'})- .then(response => response.json()).then(data => {if (data.status === 'success') {if (data.fixed_settings && data.fixed_settings.length > 0) {@@ -4662,17 +4642,12 @@testBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Testing...';// Make API call to test notification- fetch('/settings/api/notifications/test-url', {+ window.api.fetchWithErrorHandling('/settings/api/notifications/test-url', {method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'X-CSRFToken': getCsrfToken()- },body: JSON.stringify({service_url: serviceUrl})})- .then(response => response.json()).then(data => {if (data.success) {showTestResult('Test notification sent successfully!', 'success');@@ -4682,7 +4657,7 @@}).catch(error => {SafeLogger.error('Error testing notification:', error);- showTestResult('Network error while testing notification', 'error');+ showTestResult(`Test failed: ${error?.message || 'Unable to test notification'}`, 'error');}).finally(() => {// Re-enable button and restore original textdiff --git a/src/local_deep_research/web/static/js/services/api.js b/src/local_deep_research/web/static/js/services/api.jsindex 35a6da5ff6..66bf2ef633 100644--- a/src/local_deep_research/web/static/js/services/api.js+++ b/src/local_deep_research/web/static/js/services/api.js@@ -108,7 +108,7 @@ async function fetchWithErrorHandling(url, options = {}) {// Handle non-200 responsesif (!response.ok) {const errorData = await response.json().catch(() => ({}));- throw new Error(errorData.message || errorData.error || `API Error: ${response.status} ${response.statusText}`);+ throw new Error(errorData?.message || errorData?.error || errorData?.detail || `API Error: ${response.status} ${response.statusText}`);}// Parse the responsediff --git a/tests/js/components/settings-fetch-error-handling.test.js b/tests/js/components/settings-fetch-error-handling.test.jsnew file mode 100644index 0000000000..34a4d3e092--- /dev/null+++ b/tests/js/components/settings-fetch-error-handling.test.js@@ -0,0 +1,194 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++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';++const SETTINGS_PATH = resolve(+ __dirname,+ '../../../src/local_deep_research/web/static/js/components/settings.js',+);+const SETTINGS_SOURCE = readFileSync(SETTINGS_PATH, 'utf8');+const ORIGINAL_HEAD_NODES = [...document.head.childNodes].map(node => node.cloneNode(true));+const ORIGINAL_BODY_NODES = [...document.body.childNodes].map(node => node.cloneNode(true));+const WINDOW_KEYS = [+ 'escapeHtml',+ 'ui',+ 'modelProvidersRequestInProgress',+ 'searchEnginesRequestInProgress',+ 'modelDropdownsInitialized',+ 'searchEngineDropdownInitialized',+ '__LDR_MOBILE_BREAKPOINT_PX',+ 'setupSettingsDropdowns',+];+const ORIGINAL_WINDOW_STATE = new Map(WINDOW_KEYS.map(key => [key, {+ owned: Object.hasOwn(window, key),+ value: window[key],+}]));++afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ vi.useRealTimers();+ document.head.replaceChildren(...ORIGINAL_HEAD_NODES.map(node => node.cloneNode(true)));+ document.body.replaceChildren(...ORIGINAL_BODY_NODES.map(node => node.cloneNode(true)));+ ORIGINAL_WINDOW_STATE.forEach((state, key) => {+ if (state.owned) {+ window[key] = state.value;+ } else {+ delete window[key];+ }+ });+});++describe('settings request error handling', () => {+ it('routes exactly the seven target requests through the shared helper', () => {+ const handledPatterns = [+ 'window.api.fetchWithErrorHandling(URLS.SETTINGS_API.BASE)',+ "window.api.fetchWithErrorHandling('/settings/api/data-location')",+ 'window.api.fetchWithErrorHandling(URLS.SETTINGS_API.BACKUP_STATUS)',+ 'window.api.fetchWithErrorHandling(URLS.SETTINGS_API.SAVE_ALL_SETTINGS, {',+ 'window.api.fetchWithErrorHandling(URLS.SETTINGS_API.RESET_TO_DEFAULTS, {',+ 'window.api.fetchWithErrorHandling(URLS.SETTINGS_API.FIX_CORRUPTED_SETTINGS, {',+ "window.api.fetchWithErrorHandling('/settings/api/notifications/test-url', {",+ ];+ const excludedPatterns = [+ 'const response = await fetch(URLS.SETTINGS_API.OLLAMA_STATUS, {',+ 'window.modelProvidersRequestInProgress = fetch(url)',+ 'window.searchEnginesRequestInProgress = fetch(URLS.SETTINGS_API.AVAILABLE_SEARCH_ENGINES)',+ ];+ const handledCalls = SETTINGS_SOURCE.match(+ /window\.api\.fetchWithErrorHandling\(/g,+ ) || [];+ const rawCalls = SETTINGS_SOURCE.match(/\bfetch\(/g) || [];++ handledPatterns.forEach(pattern => {+ expect(SETTINGS_SOURCE).toContain(pattern);+ });+ excludedPatterns.forEach(pattern => {+ expect(SETTINGS_SOURCE).toContain(pattern);+ });+ expect(handledCalls).toHaveLength(7);+ expect(rawCalls).toHaveLength(3);+ });++ it('preserves the settings domain success and failure checks', () => {+ expect(+ SETTINGS_SOURCE.match(/if \(data\.status === 'success'\)/g) || []+ ).toHaveLength(4);+ expect(SETTINGS_SOURCE.match(/if \(data\.success\)/g) || []).toHaveLength(1);+ });++ it('preserves backup states and renders notification HTTP errors as safe text', async () => {+ vi.useFakeTimers();+ let backupResponse = () => new Response('null', {+ status: 500,+ statusText: 'Internal Server Error',+ });+ const notificationError = '<img src=x onerror=alert(1)> URL rejected';++ document.head.innerHTML = '<meta name="csrf-token" content="test-csrf">';+ document.body.innerHTML = `+ <form id="settings-form">+ <button type="button" class="ldr-settings-tab" data-tab="app">App</button>+ <div id="settings-alert"></div>+ <div id="settings-content"></div>+ </form>+ `;+ window.escapeHtml = value => String(value);+ window.ui = null;+ window.modelProvidersRequestInProgress = null;+ window.searchEnginesRequestInProgress = null;++ vi.stubGlobal('fetch', vi.fn(url => {+ if (url === URLS.SETTINGS_API.BASE) {+ return Promise.resolve(new Response(+ '{"status":"success","settings":{}}',+ { status: 200 },+ ));+ }+ if (url === '/settings/api/data-location') {+ return Promise.resolve(new Response(JSON.stringify({+ data_directory: '/tmp/ldr',+ security_notice: { encrypted: false },+ }), { status: 200 }));+ }+ if (url === URLS.SETTINGS_API.BACKUP_STATUS) {+ return Promise.resolve(backupResponse());+ }+ if (url === URLS.SETTINGS_API.AVAILABLE_MODELS) {+ return Promise.resolve(new Response(+ '{"providers":{},"provider_options":[]}',+ { status: 200 },+ ));+ }+ if (url === URLS.SETTINGS_API.AVAILABLE_SEARCH_ENGINES) {+ return Promise.resolve(new Response(+ '{"engine_options":[]}',+ { status: 200 },+ ));+ }+ if (url === '/settings/api/notifications/test-url') {+ return Promise.resolve(new Response(JSON.stringify({+ message: notificationError,+ }), { status: 400, statusText: 'Bad Request' }));+ }+ throw new Error(`Unexpected request: ${url}`);+ }));++ const handledFetch = vi.spyOn(window.api, 'fetchWithErrorHandling');++ try {+ await import('@js/components/settings.js');+ if (handledFetch.mock.calls.length === 0) {+ document.dispatchEvent(new Event('DOMContentLoaded'));+ }+ await Promise.resolve();+ await Promise.resolve();+ await vi.advanceTimersByTimeAsync(151);++ const backupCallsAfterFailure = handledFetch.mock.calls.filter(+ ([url]) => url === URLS.SETTINGS_API.BACKUP_STATUS+ );+ const backupContent = document.getElementById('ldr-backup-status-content');+ expect(backupCallsAfterFailure).toHaveLength(1);+ expect(backupContent.textContent).toContain('Could not load backup status.');+ expect(backupContent.textContent).not.toContain('Backups disabled');++ backupResponse = () => new Response(JSON.stringify({+ enabled: false,+ count: 0,+ backups: [],+ }), { status: 200 });+ document.body.insertAdjacentHTML('beforeend', `+ <input id="notifications-service-url" value="json://example">+ <button type="button" id="test-notification-button">Test</button>+ <div id="test-notification-result" style="display: none;"></div>+ `);+ document.querySelector('[data-tab="app"]').click();+ await vi.advanceTimersByTimeAsync(151);++ const backupCallsAfterValidResponse = handledFetch.mock.calls.filter(+ ([url]) => url === URLS.SETTINGS_API.BACKUP_STATUS+ );+ expect(backupCallsAfterValidResponse).toHaveLength(2);+ expect(+ document.getElementById('ldr-backup-status-content').textContent+ ).toContain('Backups disabled');++ document.getElementById('test-notification-button').click();+ await vi.advanceTimersByTimeAsync(1);++ const notificationResult = document.getElementById('test-notification-result');+ expect(notificationResult.textContent).toBe(`Test failed: ${notificationError}`);+ expect(notificationResult.querySelector('img')).toBeNull();+ } finally {+ handledFetch.mockRestore();+ vi.unstubAllGlobals();+ vi.useRealTimers();+ }+ });+});diff --git a/tests/js/services/api.test.js b/tests/js/services/api.test.jsindex 909c178700..0476b245f3 100644--- a/tests/js/services/api.test.js+++ b/tests/js/services/api.test.js@@ -149,4 +149,56 @@ describe('fetchWithErrorHandling — 401 handling', () => {await expect(fetchWithErrorHandling('/api/history')).rejects.toThrow('boom');expect(window.location.href).toBe('http://localhost/dashboard');});++ it('throws the message from a non-2xx JSON body', async () => {+ globalThis.fetch = vi.fn(() =>+ Promise.resolve(new Response(+ '{"message":"settings unavailable"}',+ { status: 503, statusText: 'Service Unavailable' },+ ))+ );++ await expect(fetchWithErrorHandling('/api/settings')).rejects.toThrow(+ 'settings unavailable'+ );+ });++ it('throws the detail from a non-2xx FastAPI JSON body', async () => {+ globalThis.fetch = vi.fn(() =>+ Promise.resolve(new Response(+ '{"detail":"Notification URL is invalid"}',+ { status: 422, statusText: 'Unprocessable Content' },+ ))+ );++ await expect(fetchWithErrorHandling('/api/settings')).rejects.toThrow(+ 'Notification URL is invalid'+ );+ });++ it('uses the HTTP status fallback for a non-2xx JSON null body', async () => {+ globalThis.fetch = vi.fn(() =>+ Promise.resolve(new Response(+ 'null',+ { status: 500, statusText: 'Internal Server Error' },+ ))+ );++ await expect(fetchWithErrorHandling('/api/settings')).rejects.toThrow(+ 'API Error: 500 Internal Server Error'+ );+ });++ it('uses the HTTP status fallback for a non-JSON error body', async () => {+ globalThis.fetch = vi.fn(() =>+ Promise.resolve(new Response(+ '<html>gateway failure</html>',+ { status: 502, statusText: 'Bad Gateway' },+ ))+ );++ await expect(fetchWithErrorHandling('/api/settings')).rejects.toThrow(+ 'API Error: 502 Bad Gateway'+ );+ });});