~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
/**
* Tests for services/theme.js
*
* Tests theme resolution, validation, storage, and settings API ownership.
*/
// Theme metadata must be set BEFORE the module IIFE runs.
// ES module imports are hoisted, so we use dynamic import in beforeAll.
let theme;
function deferred() {
let resolvePromise;
let rejectPromise;
const promise = new Promise((resolve, reject) => {
resolvePromise = resolve;
rejectPromise = reject;
});
return {
promise,
resolve: resolvePromise,
reject: rejectPromise,
};
}
beforeAll(async () => {
// Mirror the shipped choice: "hashed" is the existing Hashed dark
// palette's ID, preferred while light themes still need refinement.
window.LDR_DEFAULT_THEME = 'hashed';
// Set up theme metadata before loading the module
window.LDR_THEME_METADATA = {
'hashed': { label: 'Hashed', icon: 'fa-hashtag', group: 'core' },
'light': { label: 'Light', icon: 'fa-sun', group: 'core' },
'sepia': { label: 'Sepia', icon: 'fa-book', group: 'research' },
'nord': { label: 'Nord', icon: 'fa-snowflake', group: 'dev' },
'dracula': { label: 'Dracula', icon: 'fa-ghost', group: 'dev' },
'system': { label: 'System', icon: 'fa-desktop', group: 'system' },
};
// Stub fetch for server sync calls
globalThis.fetch = vi.fn(() =>
Promise.resolve({ ok: false, status: 404, json: () => Promise.resolve({}) })
);
// Stub api for CSRF
window.api = { getCsrfToken: () => '' };
await import('@js/services/theme.js');
theme = window.themeService;
});
describe('themeService', () => {
afterEach(() => {
localStorage.clear();
});
describe('VALID_THEMES is derived from injected metadata', () => {
it('contains every key from window.LDR_THEME_METADATA', () => {
// Catches a regression where the derivation is removed/hardcoded.
const metadataKeys = Object.keys(window.LDR_THEME_METADATA);
for (const key of metadataKeys) {
expect(theme.VALID_THEMES).toContain(key);
}
});
});
describe('getEffectiveTheme', () => {
it('resolves system to light when prefers-color-scheme is light', () => {
// happy-dom matchMedia returns false for dark mode by default
expect(theme.getEffectiveTheme('system')).toBe('light');
});
it('returns the theme itself for non-system themes', () => {
expect(theme.getEffectiveTheme('hashed')).toBe('hashed');
expect(theme.getEffectiveTheme('light')).toBe('light');
expect(theme.getEffectiveTheme('nord')).toBe('nord');
expect(theme.getEffectiveTheme('sepia')).toBe('sepia');
});
});
describe('getCurrentTheme / setTheme', () => {
it('defaults to hashed when no theme stored', () => {
localStorage.clear();
// Missing preferences must start with the chosen Hashed dark palette.
expect(theme.getCurrentTheme()).toBe('hashed');
});
it('stores and retrieves theme', () => {
theme.setTheme('nord', false);
expect(theme.getCurrentTheme()).toBe('nord');
});
it('falls back to hashed for invalid theme', () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
theme.setTheme('nonexistent-theme', false);
expect(theme.getCurrentTheme()).toBe('hashed');
warnSpy.mockRestore();
});
});
describe('applyTheme', () => {
it('sets data-theme attribute on documentElement', () => {
theme.applyTheme('nord');
expect(document.documentElement.getAttribute('data-theme')).toBe('nord');
});
it('resolves system theme before applying', () => {
theme.applyTheme('system');
const applied = document.documentElement.getAttribute('data-theme');
expect(applied).toBe('light');
});
it('dispatches themechange event', () => {
const handler = vi.fn();
window.addEventListener('themechange', handler);
theme.applyTheme('light');
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0][0].detail.theme).toBe('light');
window.removeEventListener('themechange', handler);
});
});
describe('cycleTheme', () => {
it('cycles through THEME_CYCLE order', () => {
theme.setTheme('hashed', false);
const next = theme.cycleTheme();
expect(next).toBe('light');
});
it('wraps around to first theme after last', () => {
theme.setTheme('dracula', false);
const next = theme.cycleTheme();
expect(next).toBe('hashed');
});
it('starts from beginning when current theme is not in cycle', () => {
theme.setTheme('sepia', false);
const next = theme.cycleTheme();
// sepia is not in cycle, index=-1 → becomes 0 → 'hashed'
expect(next).toBe('hashed');
});
});
describe('clearTheme', () => {
it('removes theme from localStorage', () => {
theme.setTheme('nord', false);
expect(theme.getCurrentTheme()).toBe('nord');
theme.clearTheme();
// Clearing a preference restores the chosen Hashed dark default.
expect(theme.getCurrentTheme()).toBe('hashed');
});
});
describe('clearAllThemes', () => {
it('removes all theme keys from localStorage', () => {
theme.setTheme('nord', false);
localStorage.setItem('ldr-theme-user2', 'light');
theme.clearAllThemes();
expect(localStorage.getItem('ldr-theme-user2')).toBeNull();
});
});
describe('populateThemeDropdown', () => {
it('populates a select element with theme options', () => {
const select = document.createElement('select');
theme.populateThemeDropdown(select);
const optgroups = select.querySelectorAll('optgroup');
expect(optgroups.length).toBeGreaterThan(0);
const options = select.querySelectorAll('option');
expect(options.length).toBe(Object.keys(window.LDR_THEME_METADATA).length);
});
it('does nothing when element is null', () => {
expect(() => theme.populateThemeDropdown(null)).not.toThrow();
});
});
describe('saveThemeToServer', () => {
// Restore each test's fetch mock and CSRF stub so we don't leak
// assertions across the outer describe block's later tests.
let originalGetCsrfToken;
beforeEach(() => {
originalGetCsrfToken = window.api.getCsrfToken;
});
afterEach(() => {
window.api.getCsrfToken = originalGetCsrfToken;
});
it('returns Promise.resolve() without calling fetch when CSRF is missing', async () => {
window.api.getCsrfToken = () => '';
const fetchSpy = vi.fn();
globalThis.fetch = fetchSpy;
await theme.saveThemeToServer('nord');
expect(fetchSpy).not.toHaveBeenCalled();
});
it('PUTs to /settings/api/app.theme with CSRF header and JSON body', async () => {
window.api.getCsrfToken = () => 'csrf-test-123';
globalThis.fetch = vi.fn(() =>
Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({}) })
);
await theme.saveThemeToServer('nord');
expect(globalThis.fetch).toHaveBeenCalledTimes(1);
const [url, init] = globalThis.fetch.mock.calls[0];
expect(url).toBe('/settings/api/app.theme');
expect(init.method).toBe('PUT');
expect(init.headers['Content-Type']).toBe('application/json');
expect(init.headers['X-CSRFToken']).toBe('csrf-test-123');
expect(JSON.parse(init.body)).toEqual({ value: 'nord' });
});
it('swallows non-ok responses without rejecting the caller', async () => {
window.api.getCsrfToken = () => 'csrf-test-123';
globalThis.fetch = vi.fn(() =>
Promise.resolve({ ok: false, status: 404, json: () => Promise.resolve({}) })
);
// Should not throw — the .catch in saveThemeToServer turns the
// 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.toBe(false);
});
it('serializes rapid PUTs so the latest theme reaches the server last', async () => {
window.api.getCsrfToken = () => 'csrf-test-123';
const olderSave = deferred();
const newerSave = deferred();
globalThis.fetch = vi.fn()
.mockImplementationOnce(() => olderSave.promise)
.mockImplementationOnce(() => newerSave.promise);
const olderRequest = theme.saveThemeToServer('light');
const newerRequest = theme.saveThemeToServer('nord');
await Promise.resolve();
expect(globalThis.fetch).toHaveBeenCalledOnce();
expect(JSON.parse(globalThis.fetch.mock.calls[0][1].body))
.toEqual({ value: 'light' });
olderSave.resolve({
ok: true,
json: vi.fn().mockResolvedValue({ status: 'success' }),
});
await olderRequest;
await Promise.resolve();
expect(globalThis.fetch).toHaveBeenCalledTimes(2);
expect(JSON.parse(globalThis.fetch.mock.calls[1][1].body))
.toEqual({ value: 'nord' });
newerSave.resolve({
ok: true,
json: vi.fn().mockResolvedValue({ status: 'success' }),
});
await newerRequest;
});
it('continues the save queue when an older theme write rejects', async () => {
window.api.getCsrfToken = () => 'csrf-test-123';
const olderSave = deferred();
const newerSave = deferred();
globalThis.fetch = vi.fn()
.mockImplementationOnce(() => olderSave.promise)
.mockImplementationOnce(() => newerSave.promise);
const olderRequest = theme.saveThemeToServer('light');
const newerRequest = theme.saveThemeToServer('dracula');
await Promise.resolve();
expect(globalThis.fetch).toHaveBeenCalledOnce();
olderSave.reject(new Error('theme service offline'));
await olderRequest;
await vi.waitFor(() => {
expect(globalThis.fetch).toHaveBeenCalledTimes(2);
});
expect(JSON.parse(globalThis.fetch.mock.calls[1][1].body))
.toEqual({ value: 'dracula' });
newerSave.resolve({
ok: true,
json: vi.fn().mockResolvedValue({ status: 'success' }),
});
await newerRequest;
});
});
it('does not let delayed server hydration undo a newer user theme', async () => {
const staleHydration = deferred();
globalThis.fetch = vi.fn(() => staleHydration.promise);
theme.initializeTheme();
theme.setTheme('nord', false);
staleHydration.resolve({
ok: true,
json: vi.fn().mockResolvedValue({ value: 'light' }),
});
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
expect(theme.getCurrentTheme()).toBe('nord');
expect(document.documentElement.getAttribute('data-theme')).toBe('nord');
});
});