Skip to content

~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.

31.7 KB
Raw Blame
/**
 * Tests for services/ui.js
 *
 * Tests UI utility functions: progress bars, spinners, error display,
 * inline errors, escapeHtmlFallback, and notification system.
 */

import DOMPurify from 'dompurify';

import { installMathMlNamespaceApproximation } from '../happy-dom-mathml-namespace-approximation.js';

const RealDOMPurify = DOMPurify;
import '@js/security/xss-protection.js';
import '@js/services/ui.js';

// services/ui.js's safeSetHTML now fails CLOSED: with no DOMPurify on the page
// it assigns the markup to textContent instead of innerHTML, so showSpinner /
// showError / showMessage produce no elements at all and every
// `querySelector(...)` below returns null. Production always has the sanitizer
// (base.html loads security/xss-protection.js on every page and the Vite
// bundle publishes window.DOMPurify), so install it here to mirror that rather
// than exercise the sanitizer-missing degradation.
//
// This runs after the imports above (ES module evaluation order), which is why
// xss-protection.js's load-time `afterSanitizeAttributes` tabnabbing hook is
// not registered for this suite -- nothing here asserts on rel="noopener".
globalThis.DOMPurify = DOMPurify;
window.DOMPurify = DOMPurify;

const ui = window.ui;

// showSpinner, showError and showAlert render through safeSetHTML, which
// only parses markup when a supported DOMPurify is bound (as on every page
// that loads the Vite bundle). Bind the real one for the blocks that assert
// rendered structure; the fail-closed fallback is covered separately below.
function bindRealDOMPurify() {
    let saved;
    beforeEach(() => {
        saved = globalThis.DOMPurify;
        globalThis.DOMPurify = RealDOMPurify;
    });
    afterEach(() => {
        if (saved === undefined) {
            delete globalThis.DOMPurify;
        } else {
            globalThis.DOMPurify = saved;
        }
    });
}

describe('ui service', () => {
    describe('updateProgressBar', () => {
        let fill, pct;

        beforeEach(() => {
            fill = document.createElement('div');
            fill.id = 'test-fill';
            pct = document.createElement('span');
            pct.id = 'test-pct';
            document.body.appendChild(fill);
            document.body.appendChild(pct);
        });

        afterEach(() => {
            fill.remove();
            pct.remove();
        });

        it('sets width and text for percentage', () => {
            ui.updateProgressBar(fill, pct, 42);
            expect(fill.style.width).toBe('42%');
            expect(pct.textContent).toBe('42%');
        });

        it('clamps percentage to 0-100', () => {
            ui.updateProgressBar(fill, pct, -10);
            expect(fill.style.width).toBe('0%');
            expect(pct.textContent).toBe('0%');

            ui.updateProgressBar(fill, pct, 150);
            expect(fill.style.width).toBe('100%');
            expect(pct.textContent).toBe('100%');
        });

        it('handles null/undefined percentage as 0', () => {
            ui.updateProgressBar(fill, pct, null);
            expect(fill.style.width).toBe('0%');
        });

        it('adds ldr-complete class at 100%', () => {
            ui.updateProgressBar(fill, pct, 100);
            expect(fill.classList.contains('ldr-complete')).toBe(true);
        });

        it('removes ldr-complete class when below 100%', () => {
            fill.classList.add('ldr-complete');
            ui.updateProgressBar(fill, pct, 50);
            expect(fill.classList.contains('ldr-complete')).toBe(false);
        });

        it('accepts string IDs instead of elements', () => {
            ui.updateProgressBar('test-fill', 'test-pct', 75);
            expect(fill.style.width).toBe('75%');
            expect(pct.textContent).toBe('75%');
        });

        it('rounds percentage text', () => {
            ui.updateProgressBar(fill, pct, 33.7);
            expect(pct.textContent).toBe('34%');
        });
    });

    describe('showSpinner / hideSpinner', () => {
        bindRealDOMPurify();
        let container;

        beforeEach(() => {
            container = document.createElement('div');
            container.id = 'spinner-container';
            document.body.appendChild(container);
        });

        afterEach(() => {
            container.remove();
        });

        it('creates a spinner element in the container', () => {
            ui.showSpinner(container, 'Loading data...');
            expect(container.querySelector('.ldr-loading-spinner')).not.toBeNull();
        });

        it('displays the message text', () => {
            ui.showSpinner(container, 'Please wait');
            expect(container.textContent).toContain('Please wait');
        });

        it('escapes HTML in the message', () => {
            ui.showSpinner(container, '<script>alert(1)</script>');
            expect(container.innerHTML).not.toContain('<script>');
        });

        it('hideSpinner removes the spinner', () => {
            ui.showSpinner(container);
            expect(container.querySelector('.ldr-loading-spinner')).not.toBeNull();
            ui.hideSpinner(container);
            expect(container.querySelector('.ldr-loading-spinner')).toBeNull();
        });

        it('hideSpinner does nothing when no spinner exists', () => {
            expect(() => ui.hideSpinner(container)).not.toThrow();
        });

        it('accepts string IDs', () => {
            ui.showSpinner('spinner-container', 'Test');
            expect(container.querySelector('.ldr-loading-spinner')).not.toBeNull();
            ui.hideSpinner('spinner-container');
            expect(container.querySelector('.ldr-loading-spinner')).toBeNull();
        });
    });

    describe('showError', () => {
        bindRealDOMPurify();
        let container;

        beforeEach(() => {
            container = document.createElement('div');
            container.id = 'error-container';
            document.body.appendChild(container);
        });

        afterEach(() => {
            container.remove();
        });

        it('shows error message in container', () => {
            ui.showError(container, 'Something went wrong');
            expect(container.textContent).toContain('Something went wrong');
        });

        it('escapes HTML in error message', () => {
            ui.showError(container, '<img onerror="xss">');
            expect(container.innerHTML).not.toContain('<img');
        });

        it('creates error element with icon', () => {
            ui.showError(container, 'Error');
            expect(container.querySelector('.ldr-error-message')).not.toBeNull();
            expect(container.querySelector('.fa-exclamation-circle')).not.toBeNull();
        });
    });

    describe('showInlineError / clearInlineError', () => {
        let container;

        beforeEach(() => {
            container = document.createElement('div');
            container.id = 'inline-error-container';
            document.body.appendChild(container);
        });

        afterEach(() => {
            container.remove();
        });

        it('creates an inline error element', () => {
            const el = ui.showInlineError(container, 'Field is required');
            expect(el).not.toBeNull();
            expect(el.classList.contains('ldr-inline-error')).toBe(true);
            expect(el.textContent).toContain('Field is required');
        });

        it('sets role="alert" for accessibility', () => {
            const el = ui.showInlineError(container, 'Error');
            expect(el.getAttribute('role')).toBe('alert');
        });

        it('adds dismiss button by default', () => {
            const el = ui.showInlineError(container, 'Error');
            const closeBtn = el.querySelector('.ldr-inline-error-close');
            expect(closeBtn).not.toBeNull();
            expect(closeBtn.getAttribute('aria-label')).toBe('Dismiss error');
        });

        it('dismiss button removes error', () => {
            const el = ui.showInlineError(container, 'Error');
            const closeBtn = el.querySelector('.ldr-inline-error-close');
            closeBtn.click();
            expect(container.querySelector('.ldr-inline-error')).toBeNull();
        });

        it('replaces existing inline error', () => {
            ui.showInlineError(container, 'First error');
            ui.showInlineError(container, 'Second error');
            const errors = container.querySelectorAll('.ldr-inline-error');
            expect(errors.length).toBe(1);
            expect(errors[0].textContent).toContain('Second error');
        });

        it('clearInlineError removes all errors', () => {
            ui.showInlineError(container, 'Error 1');
            ui.clearInlineError(container);
            expect(container.querySelector('.ldr-inline-error')).toBeNull();
        });

        it('returns null for non-existent container', () => {
            expect(ui.showInlineError('#nonexistent', 'Error')).toBeNull();
        });

        it('accepts string ID for container', () => {
            const el = ui.showInlineError('inline-error-container', 'Test');
            expect(el).not.toBeNull();
        });

        it('uses textContent (not innerHTML) for message', () => {
            const el = ui.showInlineError(container, '<script>xss</script>');
            const span = el.querySelector('span');
            expect(span.textContent).toBe('<script>xss</script>');
            expect(span.innerHTML).not.toContain('<script>');
        });
    });

    describe('showMessage', () => {
        afterEach(() => {
            // Persistent banners stay in the DOM by design; clean up
            // between tests so each test starts fresh.
            document
                .getElementById('notification-banner-polite')
                ?.remove();
            document
                .getElementById('notification-banner-assertive')
                ?.remove();
        });

        it('shows the polite banner for success messages', () => {
            ui.showMessage('Saved!', 'success');
            const polite = document.getElementById(
                'notification-banner-polite',
            );
            expect(polite).not.toBeNull();
            expect(polite.textContent).toContain('Saved!');
            expect(polite.getAttribute('role')).toBe('status');
            expect(polite.getAttribute('aria-live')).toBe('polite');
        });

        it('shows the assertive banner for error messages', () => {
            ui.showMessage('Error occurred', 'error');
            const assertive = document.getElementById(
                'notification-banner-assertive',
            );
            expect(assertive).not.toBeNull();
            expect(assertive.textContent).toContain('Error occurred');
            expect(assertive.getAttribute('role')).toBe('alert');
            expect(assertive.getAttribute('aria-live')).toBe('assertive');
        });

        it('uses the assertive banner for warnings', () => {
            ui.showMessage('Heads up', 'warning');
            const assertive = document.getElementById(
                'notification-banner-assertive',
            );
            expect(assertive.textContent).toContain('Heads up');
        });

        it('uses the polite banner for info messages', () => {
            ui.showMessage('FYI', 'info');
            const polite = document.getElementById(
                'notification-banner-polite',
            );
            expect(polite.textContent).toContain('FYI');
        });

        it('escapes HTML by using textContent', () => {
            ui.showMessage('<img src=x onerror=alert(1)>', 'info');
            const polite = document.getElementById(
                'notification-banner-polite',
            );
            // textContent is set, not innerHTML, so the markup is text.
            expect(polite.textContent).toContain(
                '<img src=x onerror=alert(1)>',
            );
            expect(polite.querySelector('img')).toBeNull();
        });

        it('reuses the same banner element across calls', () => {
            ui.showMessage('First', 'success');
            const firstNode = document.getElementById(
                'notification-banner-polite',
            );
            ui.showMessage('Second', 'info');
            const secondNode = document.getElementById(
                'notification-banner-polite',
            );
            // Same DOM node — live regions must persist for the
            // screen reader to announce subsequent updates.
            expect(secondNode).toBe(firstNode);
            expect(secondNode.textContent).toContain('Second');
            expect(secondNode.textContent).not.toContain('First');
        });

        it('switches between banners when type changes', () => {
            ui.showMessage('Saved', 'success');
            ui.showMessage('Boom', 'error');
            const polite = document.getElementById(
                'notification-banner-polite',
            );
            const assertive = document.getElementById(
                'notification-banner-assertive',
            );
            expect(assertive.textContent).toContain('Boom');
            // Polite is hidden via transform but its prior text
            // is still in the DOM; the visible banner is assertive.
            expect(polite.style.transform).toContain('-100%');
        });
    });
});

describe('renderMarkdown', () => {
    it('returns warning HTML for null/empty input', () => {
        const result = ui.renderMarkdown(null);
        expect(result).toContain('No content available');
    });

    it('returns plaintext fallback when marked is unavailable', () => {
        // happy-dom doesn't have `marked` loaded
        const result = ui.renderMarkdown('# Hello World');
        // Should escape HTML and show as plaintext
        expect(result).toContain('Hello World');
    });
});

describe('renderMarkdown with real Marked, KaTeX and DOMPurify', () => {
    // Configure a real marked + KaTeX + DOMPurify pipeline for this block only.
    // The setup mirrors app.js so renderMarkdown takes the marked-rendering
    // branch instead of falling through to the plaintext-escape fallback.
    beforeAll(async () => {
        // happy-dom does not parse <math> into the MathML namespace on its
        // own (no foreign-content support at all), so without this,
        // DOMPurify's own namespace-validity check (a real mXSS defense: a
        // MathML-only tag name observed in the HTML namespace is force-
        // removed) strips the MathML accessibility subtree (annotation,
        // semantics, mrow, ...) even though those elements survive in real
        // browsers. installMathMlNamespaceApproximation() is a coarse,
        // tag-name-based approximation good enough for that -- see its
        // header for exactly what it does and does not model, and why it
        // must never be installed in a suite (like
        // tests/js/security/mxss-reparse-invariant.test.js) that asserts a
        // namespace-confusion invariant.
        installMathMlNamespaceApproximation();
        const { Marked } = await import('marked');
        const markedKatex = (await import('marked-katex-extension')).default;
        const m = new Marked();
        // Mirror app.js so the test exercises the production config.
        m.use(markedKatex({ throwOnError: false, errorColor: 'currentColor' }));
        globalThis.marked = m;
        // DOMPurify captures native accessors when an instance is created.
        // Create this benign-rendering instance AFTER the namespace shim;
        // the module's default instance captured happy-dom's HTML getter.
        const createDOMPurify = DOMPurify;
        globalThis.DOMPurify = createDOMPurify(window);
    });
    afterAll(() => {
        delete globalThis.marked;
        // Restore, don't delete: this file installs DOMPurify as a global at
        // module scope for safeSetHTML's fail-closed branch, so deleting it
        // here would leave any later describe block without a sanitizer.
        globalThis.DOMPurify = DOMPurify;
    });

    it.each(['smartLists', 'highlight'])('omits obsolete %s from actual Marked options', (option) => {
        const setOptions = vi.spyOn(globalThis.marked, 'setOptions');
        try {
            const result = ui.renderMarkdown('# Options');

            expect(result).toBe('<div class="ldr-markdown-content"><h1>Options</h1>\n</div>');
            expect(setOptions).toHaveBeenCalledTimes(1);
            const [options] = setOptions.mock.calls[0];
            expect(options).toMatchObject({
                breaks: true,
                gfm: true,
                headerIds: true,
                smartypants: false,
            });
            expect(options).not.toHaveProperty(option);
        } finally {
            setOptions.mockRestore();
        }
    });

    it('preserves fenced JavaScript verbatim without Prism token spans', () => {
        const code = 'const args = ["--verbose", \'--output=<file>\'];';
        const template = document.createElement('template');
        // eslint-disable-next-line no-unsanitized/property -- test-only: inspect actual renderer output.
        template.innerHTML = ui.renderMarkdown('```javascript\n' + code + '\n```');

        const renderedCode = template.content.querySelector('.ldr-markdown-content > pre > code.language-javascript');
        expect(renderedCode).not.toBeNull();
        expect(renderedCode.textContent).toBe(code + '\n');
        expect(renderedCode.children).toHaveLength(0);
        expect(template.content.querySelector('span.token')).toBeNull();
    });

    it('preserves headings, links, inline code, line breaks and GFM', () => {
        const template = document.createElement('template');
        // eslint-disable-next-line no-unsanitized/property -- test-only: inspect actual renderer output.
        template.innerHTML = ui.renderMarkdown('# Guide\n\n[Docs](https://example.test/docs "Reference")\nUse `--verbose` and ~~old~~.\n\n- item');

        const root = template.content.querySelector('.ldr-markdown-content');
        expect(root.querySelector('h1').textContent).toBe('Guide');
        const link = root.querySelector('a');
        expect(link.textContent).toBe('Docs');
        expect(link.getAttribute('href')).toBe('https://example.test/docs');
        expect(link.getAttribute('title')).toBe('Reference');
        expect(link.getAttribute('target')).toBe('_blank');
        expect(link.getAttribute('rel')).toBe('noopener noreferrer');
        expect(root.querySelector('p > br')).not.toBeNull();
        expect(root.querySelector('p > code').textContent).toBe('--verbose');
        expect(root.querySelector('del').textContent).toBe('old');
        expect(root.querySelector('ul > li').textContent).toBe('item');
    });

    it('renders raw author HTML as visible text alongside Markdown', () => {
        const rawHtml = '<span class="token keyword">example</span>';
        const template = document.createElement('template');
        // eslint-disable-next-line no-unsanitized/property -- test-only: inspect actual renderer output.
        template.innerHTML = ui.renderMarkdown('# Example\n\n' + rawHtml);

        const root = template.content.querySelector('.ldr-markdown-content');
        expect(root.querySelector('h1').textContent).toBe('Example');
        expect(root.querySelector('p').textContent).toBe(rawHtml);
        expect(root.querySelector('span')).toBeNull();
    });

    // We still assert on the KaTeX HTML rendering branch — that is the
    // visible math layer and the proof that the extension actually ran, and
    // it is what a browser shows.

    it('preserves mathematical semantics in the accessible MathML tree', () => {
        const template = document.createElement('template');
        // eslint-disable-next-line no-unsanitized/property -- test-only: inspect actual renderer output.
        template.innerHTML = ui.renderMarkdown('$\\mathbb{R}+\\mathrm{x}$');
        const math = template.content.querySelector('math');
        expect(math.querySelector('mi[mathvariant="double-struck"]').textContent).toBe('R');
        expect(math.querySelector('mi[mathvariant="normal"]').textContent).toBe('x');
        expect(math.querySelector('annotation').getAttribute('encoding')).toBe('application/x-tex');
        expect(math.querySelector('annotation').textContent).toBe('\\mathbb{R}+\\mathrm{x}');
    });

    it('preserves current KaTeX layout classes for fractions and stretchy braces', () => {
        const template = document.createElement('template');
        // eslint-disable-next-line no-unsanitized/property -- test-only: inspect actual renderer output.
        template.innerHTML = ui.renderMarkdown('$\\overbrace{\\frac{1}{2}}^{n}$');
        for (const name of ['katex-base', 'katex-strut', 'katex-sizing', 'katex-stretchy']) {
            expect(template.content.querySelector(`.${name}`)).not.toBeNull();
        }
    });

    it('renders inline math as KaTeX HTML', () => {
        const result = ui.renderMarkdown('The equation $E=mc^2$ is famous');
        expect(result).toContain('class="katex"');
        expect(result).toContain('class="katex-html"');
        expect(result).toContain('mord mathnormal');
    });

    it('renders display math as a katex-display block', () => {
        const result = ui.renderMarkdown('$$\\sum_{i=1}^n i$$');
        expect(result).toContain('class="katex-display"');
        expect(result).toContain('op-symbol');
    });

    it('renders math alongside other markdown', () => {
        // The leading "Intro." paragraph was a deliberate sacrificial node.
        // DOMPurify >=3.4.8 reads element names through the cached
        // Node.prototype.nodeName getter (anti-clobbering hardening). happy-dom's
        // BASE getter returns "" when invoked that way, so the first top-level
        // node of the sanitized fragment was treated as an unknown tag and
        // unwrapped — its tags dropped, text kept (a leading `<h1>Title</h1>`
        // collapsed to `Title`). Real browsers return the correct tag name and
        // are unaffected, so it was a test-env-only artifact, tracked upstream at
        // https://github.com/capricorn86/happy-dom/issues/2182.
        // tests/js/happy-dom-dompurify-shim.js repairs it globally now, so the
        // prefix is no longer load-bearing — it is kept only so the assertions
        // below stay comparable with the older recorded output.
        const result = ui.renderMarkdown('Intro.\n\n# Title\n\nSome text $x^2$ more text\n\n- list item');
        expect(result).toContain('<h1');
        expect(result).toContain('<li>');
        expect(result).toContain('class="katex"');
    });

    it('does not treat adjacent dollar amounts as math (standard mode)', () => {
        // With marked-katex-extension default (no nonStandard flag),
        // "$10 and $20" must not be parsed as math: the `$` delimiters
        // require whitespace boundaries.
        const result = ui.renderMarkdown('It costs $10 and $20 per unit.');
        expect(result).not.toContain('class="katex"');
    });

    it('renders multi-line display math ($$\\n…\\n$$)', () => {
        // Canonical block form — what LLMs and textbooks typically emit.
        // This pattern caused display math to be silently dropped from PDFs
        // before commit 2c47b529e; locking in the rendering behavior here
        // guards against a related regression in the markdown path.
        const result = ui.renderMarkdown('Para 1\n\n$$\n\\sum_{i=1}^n i\n$$\n\nPara 2');
        expect(result).toContain('class="katex-display"');
        expect(result).toContain('Para 1');
        expect(result).toContain('Para 2');
    });

    it('does not render math inside inline code spans', () => {
        // `$x^2$` inside backticks must stay as literal code, not be parsed
        // as math. This is both a correctness and a defense-in-depth concern
        // (an LLM documenting LaTeX syntax should not have its examples
        // silently rendered).
        const result = ui.renderMarkdown('Use `$x^2$` to write x squared.');
        expect(result).not.toContain('class="katex"');
        expect(result).toContain('<code>$x^2$</code>');
    });

    it('does not render math inside fenced code blocks', () => {
        const result = ui.renderMarkdown('```\n$E=mc^2$\n```');
        expect(result).not.toContain('class="katex"');
        expect(result).toContain('$E=mc^2$');
    });

    it('renders invalid LaTeX without throwing (throwOnError: false)', () => {
        // app.js configures the extension with throwOnError: false so a
        // malformed formula in LLM output degrades gracefully rather than
        // breaking the whole render. Verify the wrapper doesn't blow up.
        expect(() => ui.renderMarkdown('Bad math: $\\frac{a$')).not.toThrow();
        const result = ui.renderMarkdown('Bad math: $\\frac{a$');
        // Either the error span renders or KaTeX recovers — either way the
        // surrounding text must come through.
        expect(result).toContain('Bad math:');
    });
});

describe('favicon status ownership', () => {
    let canvasContext;

    beforeEach(() => {
        document.querySelectorAll('link[rel="icon"], link[rel="shortcut icon"]')
            .forEach(link => link.remove());
        canvasContext = {
            clearRect: vi.fn(),
            fillText: vi.fn(),
            beginPath: vi.fn(),
            arc: vi.fn(),
            fill: vi.fn(),
            fillStyle: '',
            font: '',
            textAlign: '',
            textBaseline: '',
        };
        vi.spyOn(window.HTMLCanvasElement.prototype, 'getContext')
            .mockReturnValue(canvasContext);
        vi.spyOn(window.HTMLCanvasElement.prototype, 'toDataURL')
            .mockReturnValue('data:image/png;base64,favicon');
        vi.stubGlobal('ResearchStates', {
            isCompleted: vi.fn(status => status === 'completed'),
            isFailed: vi.fn(status => status === 'failed'),
            isCancelled: vi.fn(status => status === 'cancelled'),
        });
    });

    afterEach(() => {
        vi.restoreAllMocks();
        vi.unstubAllGlobals();
        delete window.URLValidator;
        document.querySelectorAll('link[rel="icon"], link[rel="shortcut icon"]')
            .forEach(link => link.remove());
    });

    it('creates an encoded canvas favicon through the URL validator', () => {
        window.URLValidator = { safeAssign: vi.fn() };

        ui.createDynamicFavicon('🧪');

        const link = document.querySelector('link[rel="icon"]');
        expect(link).not.toBeNull();
        expect(canvasContext.fillText).toHaveBeenCalledWith('🧪', 32, 32);
        expect(window.URLValidator.safeAssign).toHaveBeenCalledWith(
            link,
            'href',
            'data:image/png;base64,favicon',
        );
    });

    it.each([
        ['completed', '#28a745'],
        ['failed', '#dc3545'],
        ['cancelled', '#6c757d'],
        ['in_progress', '#007bff'],
    ])('maps %s research state to its favicon color', (status, color) => {
        ui.updateFavicon(status);

        const link = document.querySelector('link[rel="icon"]');
        expect(link.href).toBe('data:image/png;base64,favicon');
        expect(canvasContext.fillStyle).toBe(color);
        expect(canvasContext.fillText).toHaveBeenCalledWith('R', 16, 16);
    });

    it('contains canvas failures and leaves the page usable', () => {
        window.HTMLCanvasElement.prototype.getContext.mockReturnValue(null);
        const error = vi.spyOn(SafeLogger, 'error').mockImplementation(() => {});

        expect(() => ui.updateFavicon('completed')).not.toThrow();
        expect(error).toHaveBeenCalledWith(
            'Error updating favicon:',
            expect.any(TypeError),
        );
    });
});

describe('page alerts', () => {
    bindRealDOMPurify();
    beforeEach(() => {
        window.LdrAlertHelpers = {
            mapAlertType: vi.fn(type => (
                type === 'error' ? 'danger' : type
            )),
        };
        document.body.innerHTML = '<div id="filtered-settings-alert"></div>';
        vi.useFakeTimers();
    });

    afterEach(() => {
        vi.useRealTimers();
        delete window.LdrAlertHelpers;
        document.body.replaceChildren();
    });

    it('renders and dismisses a safely escaped migration error', () => {
        const payload = '<img src=x onerror="window.pwned=true">';

        ui.showAlert(payload, 'error', false);

        const container = document.getElementById('filtered-settings-alert');
        const alert = container.querySelector('.alert-danger');
        expect(alert.textContent).toContain(payload);
        expect(alert.querySelector('img')).toBeNull();
        expect(window.pwned).toBeUndefined();
        expect(container.style.display).toBe('block');

        alert.querySelector('.ldr-alert-close').click();
        expect(container.children).toHaveLength(0);
        expect(container.style.display).toBe('none');
    });

    it('auto-hides the fallback alert container after five seconds', () => {
        document.body.innerHTML = '<div id="research-alert"></div>';

        ui.showAlert('Still working', 'info', false);
        const container = document.getElementById('research-alert');
        expect(container.children).toHaveLength(1);

        vi.advanceTimersByTime(5000);
        expect(container.children).toHaveLength(0);
        expect(container.style.display).toBe('none');
    });

    it('does not duplicate an inline alert when the toast owns feedback', () => {
        ui.showAlert('Saved', 'success');

        expect(document.getElementById('filtered-settings-alert').children)
            .toHaveLength(0);
    });
});

describe('safeSetHTML fails closed without a supported DOMPurify', () => {
    // DOMPurify.isSupported can be false, null or undefined in a broken DOM
    // environment, and sanitize() then returns its input unchanged. Only an
    // instance reporting exactly true may be trusted; anything else (and a
    // missing DOMPurify) must render the markup as text, never as HTML.
    const PAYLOAD = '<img src=x onerror="window.__uiPwned=1">';
    let container;
    let saved;

    beforeEach(() => {
        saved = globalThis.DOMPurify;
        container = document.createElement('div');
        document.body.appendChild(container);
    });

    afterEach(() => {
        container.remove();
        if (saved === undefined) {
            delete globalThis.DOMPurify;
        } else {
            globalThis.DOMPurify = saved;
        }
        delete window.__uiPwned;
    });

    function expectPlainText(sanitize) {
        ui.showError(container, PAYLOAD);
        expect(container.children).toHaveLength(0);
        expect(container.querySelector('img')).toBeNull();
        expect(container.textContent).toContain('<div class="ldr-error-message">');
        expect(window.__uiPwned).toBeUndefined();
        if (sanitize) {
            expect(sanitize).not.toHaveBeenCalled();
        }

        ui.showSpinner(container, 'Loading');
        expect(container.children).toHaveLength(0);
        expect(container.textContent).toContain('ldr-loading-spinner');
    }

    it('renders text when DOMPurify is absent', () => {
        delete globalThis.DOMPurify;
        expectPlainText(null);
    });

    it.each([
        ['false', { isSupported: false }],
        ['null', { isSupported: null }],
        ['undefined', { isSupported: undefined }],
        ['missing', {}],
    ])('renders text when isSupported is %s', (_label, extra) => {
        // A passthrough sanitize, as DOMPurify's own is when unsupported.
        const sanitize = vi.fn(html => html);
        globalThis.DOMPurify = { ...extra, sanitize };
        expectPlainText(sanitize);
    });

    it('sanitizes through a supported DOMPurify', () => {
        const sanitize = vi.fn(() => '<div class="ldr-error-message">ok</div>');
        globalThis.DOMPurify = { isSupported: true, sanitize };
        ui.showError(container, 'boom');
        expect(sanitize).toHaveBeenCalled();
        expect(sanitize.mock.calls[0][0]).toContain('boom');
        expect(container.querySelector('.ldr-error-message')).not.toBeNull();
    });
});