~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(theme): put the previous theme back when a header save fails (#8213)
dodoshell23c454143c58
diff --git a/changelog.d/+theme-save-failure-rollback.bugfix.md b/changelog.d/+theme-save-failure-rollback.bugfix.mdnew file mode 100644index 0000000000..3359b1fdfd--- /dev/null+++ b/changelog.d/+theme-save-failure-rollback.bugfix.md@@ -0,0 +1 @@+Put the previous theme back when saving a theme from the header dropdown or quick toggle fails, instead of keeping it until the next page load silently reverts it. Fixes #8153.diff --git a/src/local_deep_research/web/static/js/services/theme.js b/src/local_deep_research/web/static/js/services/theme.jsindex e7748064de..74ebc8c9ed 100644--- a/src/local_deep_research/web/static/js/services/theme.js+++ b/src/local_deep_research/web/static/js/services/theme.js@@ -39,6 +39,9 @@const THEME_CYCLE = ['hashed', 'light', 'nord', 'dracula'];let themeIntentGeneration = 0;let themeSaveTail = Promise.resolve();+ // The theme to put back if every pending server save fails.+ let themeBeforeSaves = null;+ let pendingThemeSaves = 0;/*** Get user ID from page context (if available)@@ -131,20 +134,24 @@'X-CSRFToken': csrfToken},body: JSON.stringify({ value: theme })+ })+ .then(response => {+ if (!response.ok) throw new Error(`HTTP ${response.status}`);+ return response.json();});+ // The next save starts only once this one's outcome is known, so+ // results reach setTheme in order.const saveRequest = themeSaveTail.then(runSave);themeSaveTail = saveRequest.catch(() => {});return saveRequest- .then(response => {- if (!response.ok) throw new Error(`HTTP ${response.status}`);- return response.json();- }).then(_data => {SafeLogger.log('Theme saved to server:', theme);+ return true;}).catch(error => {SafeLogger.warn('Could not save theme to server (user may not be logged in):', error.message);+ return false;});}@@ -173,7 +180,8 @@* Set theme with both local and server sync*/function setTheme(theme, syncToServer = true) {- themeIntentGeneration++;+ const intentGeneration = ++themeIntentGeneration;+ const previousTheme = getCurrentTheme();// Validate theme using VALID_THEMES arrayif (!VALID_THEMES.includes(theme)) {SafeLogger.warn('Invalid theme:', theme, '- falling back to', DEFAULT_THEME);@@ -183,7 +191,19 @@applyTheme(theme);if (syncToServer) {- saveThemeToServer(theme);+ if (pendingThemeSaves === 0) themeBeforeSaves = previousTheme;+ pendingThemeSaves++;+ saveThemeToServer(theme).then(saved => {+ pendingThemeSaves--;+ // undefined means no CSRF token, so nothing was sent (logged+ // out) and the local choice is the only one there is.+ if (saved) {+ themeBeforeSaves = theme;+ } else if (saved === false && intentGeneration === themeIntentGeneration) {+ // Match what the server still has.+ applyTheme(themeBeforeSaves);+ }+ });}}diff --git a/tests/js/services/theme-lifecycle-runtime.test.js b/tests/js/services/theme-lifecycle-runtime.test.jsindex d808232bc0..0dcdaeb6c1 100644--- a/tests/js/services/theme-lifecycle-runtime.test.js+++ b/tests/js/services/theme-lifecycle-runtime.test.js@@ -203,6 +203,128 @@ it('wires one dropdown change to the migrated settings PUT with CSRF', async ()expect(theme.getCurrentTheme()).toBe('dracula');});+it.each([+ ['an HTTP error', () => Promise.resolve({ ok: false, status: 500 })],+ ['a network error', () => Promise.reject(new Error('offline'))],+])('puts the previous theme back when the dropdown save fails with %s', async (_label, failedSave) => {+ theme.setTheme('nord', false);+ document.body.innerHTML = '<select id="theme-dropdown"></select>';+ vi.mocked(fetch).mockImplementation(failedSave);+ theme.setupHeaderDropdown();++ const dropdown = document.getElementById('theme-dropdown');+ dropdown.value = 'dracula';+ dropdown.dispatchEvent(new Event('change'));+ expect(theme.getCurrentTheme()).toBe('dracula');++ await vi.waitFor(() => {+ expect(theme.getCurrentTheme()).toBe('nord');+ });+ expect(fetch).toHaveBeenCalledOnce();+ expect(document.documentElement.dataset.theme).toBe('nord');+ expect(dropdown.value).toBe('nord');+});++it.each([+ ['fails', false, 'nord'],+ ['succeeds', true, 'dracula'],+])('returns to the last saved theme when an earlier queued save %s', async (_label, firstSaved, expectedTheme) => {+ theme.setTheme('nord', false);+ const saves = [];+ vi.mocked(fetch).mockImplementation(() => new Promise(resolve => {+ saves.push(resolve);+ }));++ theme.setTheme('dracula');+ theme.setTheme('light');+ await vi.waitFor(() => {+ expect(saves).toHaveLength(1);+ });+ saves[0]({+ ok: firstSaved,+ status: firstSaved ? 200 : 500,+ json: vi.fn().mockResolvedValue({ status: 'success' }),+ });+ await vi.waitFor(() => {+ expect(saves).toHaveLength(2);+ });+ expect(theme.getCurrentTheme()).toBe('light');+ saves[1]({ ok: false, status: 500 });++ await vi.waitFor(() => {+ expect(theme.getCurrentTheme()).toBe(expectedTheme);+ });+ expect(document.documentElement.dataset.theme).toBe(expectedTheme);+});++it('returns to the last saved theme when its response body is slow and the queued save fails', async () => {+ theme.setTheme('nord', false);+ let finishFirstBody;+ vi.mocked(fetch)+ .mockResolvedValue({ ok: false, status: 500 })+ .mockResolvedValueOnce({+ ok: true,+ status: 200,+ json: () => new Promise(resolve => {+ finishFirstBody = resolve;+ }),+ });++ theme.setTheme('dracula');+ theme.setTheme('light');+ await vi.waitFor(() => {+ expect(finishFirstBody).toBeDefined();+ });+ expect(theme.getCurrentTheme()).toBe('light');+ finishFirstBody({ status: 'success' });++ await vi.waitFor(() => {+ expect(fetch).toHaveBeenCalledTimes(2);+ });+ await vi.waitFor(() => {+ expect(theme.getCurrentTheme()).toBe('dracula');+ });+ expect(document.documentElement.dataset.theme).toBe('dracula');+});++it('keeps a theme applied after a failing save was sent', async () => {+ theme.setTheme('nord', false);+ let failSave;+ vi.mocked(fetch).mockImplementation(() => new Promise((_resolve, reject) => {+ failSave = reject;+ }));++ theme.setTheme('dracula');+ await vi.waitFor(() => {+ expect(fetch).toHaveBeenCalledOnce();+ });+ // The settings form applies its theme this way and saves it itself.+ theme.setTheme('sepia', false);+ const themeChanges = vi.fn();+ window.addEventListener('themechange', themeChanges);+ failSave(new Error('offline'));+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ window.removeEventListener('themechange', themeChanges);++ expect(fetch).toHaveBeenCalledOnce();+ expect(themeChanges).not.toHaveBeenCalled();+ expect(theme.getCurrentTheme()).toBe('sepia');+});++it('keeps the theme when a missing CSRF token stops the save', async () => {+ theme.setTheme('nord', false);+ window.api.getCsrfToken.mockReturnValue('');++ theme.setTheme('dracula');+ await Promise.resolve();+ await Promise.resolve();++ expect(fetch).not.toHaveBeenCalled();+ expect(theme.getCurrentTheme()).toBe('dracula');+});+it('repopulates an empty dropdown after bfcache restore and tab visibility', () => {document.body.innerHTML = '<select id="theme-dropdown"></select>';const dropdown = document.getElementById('theme-dropdown');diff --git a/tests/js/services/theme.test.js b/tests/js/services/theme.test.jsindex 84d2685be9..c8c4f71b58 100644--- a/tests/js/services/theme.test.js+++ b/tests/js/services/theme.test.js@@ -220,15 +220,15 @@ describe('themeService', () => {);// Should not throw — the .catch in saveThemeToServer turns the- // HTTP 404 into a warning log.- await expect(theme.saveThemeToServer('nord')).resolves.toBeUndefined();+ // HTTP 404 into a warning log and reports the failure to setTheme.+ await expect(theme.saveThemeToServer('nord')).resolves.toBe(false);});it('swallows network errors without rejecting the caller', async () => {window.api.getCsrfToken = () => 'csrf-test-123';globalThis.fetch = vi.fn(() => Promise.reject(new Error('offline')));- await expect(theme.saveThemeToServer('nord')).resolves.toBeUndefined();+ await expect(theme.saveThemeToServer('nord')).resolves.toBe(false);});it('serializes rapid PUTs so the latest theme reaches the server last', async () => {