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.

58.5 KB
Raw Blame
/**
 * Direct browser-runtime contracts for the research page's remaining API
 * mutations and initialization path.  The dropdowns are replaced only at the
 * widget boundary so their shipped callbacks still drive research.js itself.
 */

import '@js/config/urls.js';
import '@js/utils/alert-helpers.js';
import '@js/security/xss-protection.js';
import '@js/utils/form-validation.js';
import '@js/services/api.js';
import { API_KEY_PROVIDERS } from '../helpers/api-key-providers.js';

const AVAILABLE_MODELS = '/settings/api/available-models';
// Every model load is a CSRF-protected POST: a GET only reads the server's
// cache. A POST without a query is cache-first, so the manual full refresh
// adds force_refresh=true.
const FULL_REFRESH_URL = `${AVAILABLE_MODELS}?force_refresh=true`;
const FULL_REFRESH_REQUEST = { method: 'POST', headers: { 'X-CSRFToken': 'research-csrf' } };
const AVAILABLE_ENGINES = '/settings/api/available-search-engines';
const SETTINGS = '/settings/api';
const START_RESEARCH = '/api/start_research';
const CHAT_SESSIONS = '/api/chat/sessions';
const AUTH_CONTEXT = 'a'.repeat(64);
const chatFetchWithCsrfRecovery = window.api.fetchWithCsrfRecovery;

const dropdowns = new Map();
const responseOverrides = new Map();
let fetchMock;
let initialSnapshot;

function response(body, { ok = true, status = 200, headers = {} } = {}) {
    return Promise.resolve({
        ok,
        status,
        headers: new globalThis.Headers(headers),
        redirected: false,
        json: vi.fn().mockResolvedValue(body),
        text: vi.fn().mockResolvedValue(''),
    });
}

function deferred() {
    let resolve;
    let reject;
    const promise = new Promise((resolvePromise, rejectPromise) => {
        resolve = resolvePromise;
        reject = rejectPromise;
    });
    return { promise, resolve, reject };
}

function buildForm() {
    const apiKeys = API_KEY_PROVIDERS;
    // eslint-disable-next-line no-unsanitized/property -- static, repository-owned test fixture.
    document.body.innerHTML = `
        <form id="research-form">
            <div id="research-alert" role="alert" style="display:none"></div>
            <div id="research-error-alert" style="display:none"></div>
            <textarea id="query" name="query"></textarea>

            <label class="ldr-mode-option active" data-mode="quick" tabindex="0">
                <input id="mode-quick" type="radio" name="research_mode" value="quick" checked>
            </label>
            <label class="ldr-mode-option" data-mode="detailed" tabindex="-1">
                <input id="mode-detailed" type="radio" name="research_mode" value="detailed">
            </label>
            <label class="ldr-mode-option" data-mode="chat" tabindex="-1">
                <input id="mode-chat" type="radio" name="research_mode" value="chat">
            </label>

            <div class="ldr-privacy-panel" data-scope="adaptive">
                <i id="ldr-privacy-panel-icon"></i>
                <select id="policy_egress_scope">
                    <option value="adaptive" selected>Adaptive</option>
                    <option value="public_only">Public only</option>
                    <option value="private_only">Private only</option>
                    <option value="strict">Primary only</option>
                </select>
                <input id="llm_require_local_endpoint" type="checkbox">
                <input id="embeddings_require_local" type="checkbox">
            </div>

            <button type="button" class="ldr-advanced-options-toggle ldr-open" aria-expanded="true">
                <i class="fas fa-chevron-up"></i><span class="sr-only"></span>
            </button>
            <div class="ldr-advanced-options-panel ldr-expanded">
                <select id="model_provider" data-initial-value="OLLAMA">
                    <option value="OLLAMA">Ollama</option>
                </select>
                <input id="llm.provider_hidden" name="llm.provider">

                <div class="form-group">
                    <input id="model" data-initial-value="">
                    <input id="model_hidden" name="llm.model">
                    <div id="model-dropdown"><div id="model-dropdown-list"></div></div>
                    <button type="button" id="model-refresh"><i></i></button>
                </div>

                <div class="form-group">
                    <input id="search_engine" data-initial-value="searxng">
                    <input id="search_engine_hidden" name="search.tool" value="searxng">
                    <div id="search-engine-dropdown"><div id="search-engine-dropdown-list"></div></div>
                    <button type="button" id="search_engine-refresh"><i></i></button>
                </div>

                <select id="strategy"><option value="source-based">Source based</option></select>
                <input id="iterations" value="2">
                <input id="questions_per_iteration" value="3">
                <input id="notification-toggle" type="checkbox" checked>

                <div id="endpoint_container"><input id="custom_endpoint"></div>
                <div id="anthropic_endpoint_container"><input id="anthropic_endpoint_url"></div>
                <div id="ollama_url_container"><input id="ollama_url"></div>
                <div id="lmstudio_url_container"><input id="lmstudio_url"></div>
                <div id="context_window_container"><input id="context_window"></div>
                ${apiKeys.map(key => `
                    <div id="${key}_api_key_container">
                        <input id="${key}_api_key" type="password">
                    </div>
                `).join('')}
            </div>
            <button id="start-research-btn" type="submit"><span></span></button>
        </form>
    `;
}

function initialSettings() {
    const settings = {
        'llm.provider': { value: 'openai_endpoint', editable: false },
        'llm.model': { value: 'gateway-model', editable: false },
        'llm.openai_endpoint.url': { value: 'https://gateway.example/v1', editable: false },
        'llm.anthropic_endpoint.url': { value: 'https://claude.example/v1', editable: true },
        'llm.ollama.url': { value: 'http://ollama.test', editable: true },
        'llm.lmstudio.url': { value: 'http://lmstudio.test', editable: false },
        'llm.local_context_window_size': { value: 16384, editable: true },
        'search.tool': { value: 'searxng', editable: true },
    };
    for (const key of API_KEY_PROVIDERS) {
        settings[`llm.${key}.api_key`] = {
            value: '[REDACTED]',
            editable: key !== 'google',
        };
    }
    return { settings };
}

function routeFetch(url, init = {}) {
    const override = responseOverrides.get(url);
    if (override) return response(override.body, override);

    if (typeof url === 'string' && url.startsWith(AVAILABLE_MODELS)) {
        return response({
            provider_options: [
                { value: 'OLLAMA', label: 'Ollama', is_cloud: false },
                { value: 'OPENAI_ENDPOINT', label: 'OpenAI-compatible', is_cloud: true },
                { value: 'ANTHROPIC_ENDPOINT', label: 'Anthropic-compatible', is_cloud: true },
            ],
            providers: {
                ollama_models: [{ value: 'qwen3:4b', name: 'Qwen 3', provider: 'OLLAMA' }],
                openai_endpoint_models: [
                    { value: 'gateway-model', name: 'Gateway model', provider: 'OPENAI_ENDPOINT' },
                ],
            },
        });
    }
    if (typeof url === 'string' && url.startsWith(AVAILABLE_ENGINES)) {
        return response({
            engine_options: [
                { value: 'searxng', label: 'SearXNG' },
                { value: 'library', label: 'Search All Collections' },
            ],
        });
    }
    if (url === SETTINGS && (!init.method || init.method === 'GET')) {
        return response(initialSettings());
    }
    return response({ status: 'ok' });
}

function selectMode(value) {
    for (const radio of document.querySelectorAll('input[name="research_mode"]')) {
        radio.checked = radio.value === value;
    }
}

function submit() {
    document.getElementById('research-form').dispatchEvent(
        new Event('submit', { bubbles: true, cancelable: true }),
    );
}

beforeAll(async () => {
    sessionStorage.clear();
    localStorage.clear();
    sessionStorage.setItem('rerunConfig', JSON.stringify({
        query: '<b>re-run this literally</b>',
        mode: 'detailed',
        model: 'stale-history-model',
    }));
    buildForm();

    document.head.replaceChildren();
    for (const [name, content] of [['csrf-token', 'research-csrf'], ['auth-context', AUTH_CONTEXT]]) {
        const meta = document.createElement('meta');
        meta.name = name;
        meta.content = content;
        document.head.appendChild(meta);
    }
    window.api = {
        getCsrfToken: vi.fn(() => document.querySelector('meta[name="csrf-token"]').content),
        fetchWithCsrfRecovery: chatFetchWithCsrfRecovery,
    };
    window.ui = { showAlert: vi.fn(), showMessage: vi.fn() };
    window.RESEARCH_STATUS = { QUEUED: 'queued', IN_PROGRESS: 'in_progress' };
    window.setupCustomDropdown = vi.fn((input, _list, getOptions, onSelect) => {
        dropdowns.set(input.id, { getOptions, onSelect });
        return {};
    });
    window.updateDropdownOptions = vi.fn();

    fetchMock = vi.fn(routeFetch);
    vi.stubGlobal('fetch', fetchMock);
    vi.stubGlobal('requestIdleCallback', vi.fn(callback => callback()));

    await import('@js/components/research.js');
    await import('@js/components/settings_sync.js');
    document.dispatchEvent(new Event('DOMContentLoaded'));

    await vi.waitFor(() => {
        expect(document.getElementById('model_hidden').value).toBe('gateway-model');
        expect(dropdowns.has('model')).toBe(true);
        expect(dropdowns.has('search_engine')).toBe(true);
    });

    initialSnapshot = {
        query: document.getElementById('query').value,
        rerunConfig: sessionStorage.getItem('rerunConfig'),
        detailedChecked: document.getElementById('mode-detailed').checked,
        detailedActive: document.querySelector('[data-mode="detailed"]').classList.contains('active'),
        notification: document.getElementById('research-alert').textContent,
        provider: document.getElementById('model_provider').value,
        providerDisabled: document.getElementById('model_provider').disabled,
        model: document.getElementById('model').value,
        modelDisabled: document.getElementById('model').disabled,
        endpoint: document.getElementById('custom_endpoint').value,
        endpointDisabled: document.getElementById('custom_endpoint').disabled,
        anthropicEndpoint: document.getElementById('anthropic_endpoint_url').value,
        ollamaUrl: document.getElementById('ollama_url').value,
        lmstudioUrl: document.getElementById('lmstudio_url').value,
        contextWindow: document.getElementById('context_window').value,
        openaiKey: document.getElementById('openai_api_key').value,
        orcarouterKey: document.getElementById('orcarouter_api_key').value,
        apiKeyValues: Array.from(
            document.querySelectorAll('input[type="password"]'),
            input => input.value,
        ),
        googleKeyDisabled: document.getElementById('google_api_key').disabled,
        activeProviderContainer: document.getElementById('endpoint_container').style.display,
    };
});

beforeEach(() => {
    document.querySelector('meta[name="csrf-token"]').content = 'research-csrf';
    document.querySelector('meta[name="auth-context"]').content = AUTH_CONTEXT;
    responseOverrides.clear();
    fetchMock.mockClear();
    fetchMock.mockImplementation(routeFetch);
    window.ui.showAlert.mockClear();
    window.ui.showMessage.mockClear();
    document.getElementById('query').value = 'A current research query';
    document.getElementById('model_hidden').value = 'gateway-model';
    document.getElementById('research-alert').replaceChildren();
    document.getElementById('research-alert').style.display = 'none';
    document.getElementById('research-error-alert').replaceChildren();
    document.getElementById('research-error-alert').style.display = 'none';
    document.querySelectorAll('.ldr-loading-overlay').forEach(element => element.remove());
    selectMode('quick');
});

afterAll(() => {
    vi.restoreAllMocks();
    vi.unstubAllGlobals();
    sessionStorage.clear();
    localStorage.clear();
    delete window.api;
    delete window.ui;
    delete window.RESEARCH_STATUS;
    delete window.setupCustomDropdown;
    delete window.updateDropdownOptions;
});

it('applies one history rerun after initialization without trusting stale settings', () => {
    expect(initialSnapshot).toMatchObject({
        query: '<b>re-run this literally</b>',
        rerunConfig: null,
        detailedChecked: true,
        detailedActive: true,
    });
    expect(initialSnapshot.notification).toContain('Re-running previous research');
    expect(document.querySelector('#research-alert b')).toBeNull();
});

it('hydrates the editable settings envelope and reconciles its provider and model', () => {
    expect(initialSnapshot).toMatchObject({
        provider: 'OPENAI_ENDPOINT',
        providerDisabled: true,
        model: 'Gateway model',
        modelDisabled: true,
        endpoint: 'https://gateway.example/v1',
        endpointDisabled: true,
        anthropicEndpoint: 'https://claude.example/v1',
        ollamaUrl: 'http://ollama.test',
        lmstudioUrl: 'http://lmstudio.test',
        contextWindow: '16384',
        openaiKey: '',
        orcarouterKey: '',
        googleKeyDisabled: true,
        activeProviderContainer: 'block',
    });
    expect(initialSnapshot.apiKeyValues).toHaveLength(API_KEY_PROVIDERS.length);
    expect(initialSnapshot.apiKeyValues)
        .toEqual(Array(API_KEY_PROVIDERS.length).fill(''));
});

it('replaces one redacted API key through the canonical FastAPI setting route', async () => {
    const input = document.getElementById('openai_api_key');
    expect(initialSnapshot.apiKeyValues)
        .toEqual(Array(API_KEY_PROVIDERS.length).fill(''));

    input.value = 'replacement-openai-key';
    input.dispatchEvent(new Event('change', { bubbles: true }));

    await vi.waitFor(() => {
        const writes = fetchMock.mock.calls.filter(([url, options]) => (
            url === '/settings/api/llm.openai.api_key'
            && options.method === 'PUT'
        ));
        expect(writes).toHaveLength(1);
    });
    expect(fetchMock).toHaveBeenCalledWith(
        '/settings/api/llm.openai.api_key',
        {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': 'research-csrf',
            },
            body: JSON.stringify({ value: 'replacement-openai-key' }),
        },
    );
});

it('never echoes the API key value in the success toast', async () => {
    const input = document.getElementById('openai_api_key');
    input.value = 'sk-ws-super-secret';
    input.dispatchEvent(new Event('change', { bubbles: true }));

    await vi.waitFor(() => {
        expect(window.ui.showMessage).toHaveBeenCalledWith(
            'openai api_key updated',
            'success',
            2000,
        );
    });
    for (const call of window.ui.showMessage.mock.calls) {
        expect(String(call[0])).not.toContain('sk-ws-super-secret');
    }
});

it('consumes the targeted refresh response after an API-key save', async () => {
    responseOverrides.set('/settings/api/available-models?refresh_provider=openai', {
        body: {
            provider_options: [
                { value: 'OLLAMA', label: 'Ollama', is_cloud: false },
                { value: 'QWEN', label: 'QwenCloud', is_cloud: true },
            ],
            providers: {
                ollama_models: [{ value: 'qwen3:4b', provider: 'OLLAMA' }],
                qwen_models: [{ value: 'qwen3.8-max', provider: 'QWEN' }],
            },
        },
    });

    const input = document.getElementById('openai_api_key');
    input.value = 'replacement-openai-key';
    input.dispatchEvent(new Event('change', { bubbles: true }));

    await vi.waitFor(() => {
        // The targeted response is actually consumed: the provider
        // dropdown is repopulated from its provider_options.
        expect(document.querySelector('#model_provider option[value="QWEN"]'))
            .not.toBeNull();
    });
});

it('discards a superseded targeted refresh response', async () => {
    const startedRefreshes = [];
    const refreshOptions = [];
    // Intercept PUTs and targeted model fetches so we control resolution
    // order: key saves succeed immediately, targeted refreshes pend until
    // we resolve them explicitly.
    fetchMock.mockImplementation((url, options = {}) => {
        if (typeof url === 'string' && url.startsWith('/settings/api/available-models?refresh_provider=')) {
            const provider = url.split('=')[1];
            startedRefreshes.push(provider);
            refreshOptions.push(options);
            const pending = deferred();
            refreshResponses.set(provider, pending);
            return pending.promise;
        }
        if (options.method === 'PUT') {
            return Promise.resolve({
                ok: true,
                status: 200,
                json: vi.fn().mockResolvedValue({ status: 'ok' }),
                text: vi.fn().mockResolvedValue(''),
            });
        }
        return routeFetch(url, options);
    });
    const refreshResponses = new Map();

    const qwenInput = document.getElementById('qwen_api_key');
    qwenInput.value = 'replacement-qwen-key';
    qwenInput.dispatchEvent(new Event('change', { bubbles: true }));
    const openaiInput = document.getElementById('openai_api_key');
    openaiInput.value = 'another-openai-key';
    openaiInput.dispatchEvent(new Event('change', { bubbles: true }));

    await vi.waitFor(() => {
        expect(startedRefreshes).toEqual(['qwen', 'openai']);
    });
    // Both targeted refreshes are CSRF-protected POSTs.
    for (const options of refreshOptions) {
        expect(options).toEqual({
            method: 'POST',
            headers: { 'X-CSRFToken': 'research-csrf' },
        });
    }

    // The NEWER (openai) refresh settles first with its own catalog...
    refreshResponses.get('openai').resolve(response({
        provider_options: [
            { value: 'XAI', label: 'xAI', is_cloud: true },
        ],
        providers: {},
    }));
    await vi.waitFor(() => {
        expect(document.querySelector('#model_provider option[value="XAI"]'))
            .not.toBeNull();
    });

    // ...then the STALE (qwen) refresh lands late with a different
    // catalog. The generation guard must discard it: the provider
    // dropdown keeps the newer response's options.
    //
    // Wait for the stale `.then(data => ...)` handler to have actually
    // run, not for a fixed number of microtask ticks (the chain from
    // resolve() to that handler is ~6 ticks deep, so a short tick count
    // asserts before it runs and passes even with the guard removed).
    // Both branches of the handler - the superseded unwind and the
    // normal render - clear the model field's 'ldr-loading' class, and
    // the render (populateModelProviders) is synchronous inside it, so
    // re-arming the class and waiting for its removal proves the whole
    // handler has finished.
    const modelField = document.getElementById('model').parentNode;
    modelField.classList.add('ldr-loading');
    refreshResponses.get('qwen').resolve(response({
        provider_options: [
            { value: 'QWEN', label: 'QwenCloud', is_cloud: true },
        ],
        providers: {},
    }));
    await vi.waitFor(() => {
        expect(modelField.classList.contains('ldr-loading')).toBe(false);
    });
    expect(document.querySelector('#model_provider option[value="XAI"]'))
        .not.toBeNull();
    expect(document.querySelector('#model_provider option[value="QWEN"]'))
        .toBeNull();
});

it('reveals only the QwenCloud API-key field when QWEN is the provider', async () => {
    const provider = document.getElementById('model_provider');
    provider.disabled = false;
    const qwenOption = document.createElement('option');
    qwenOption.value = 'QWEN';
    provider.appendChild(qwenOption);
    provider.value = 'QWEN';
    provider.dispatchEvent(new Event('change', { bubbles: true }));

    expect(document.getElementById('qwen_api_key_container').style.display).toBe('block');
    expect(document.getElementById('atlascloud_api_key_container').style.display).toBe('none');
    expect(document.getElementById('xai_api_key_container').style.display).toBe('none');
    expect(document.getElementById('endpoint_container').style.display).toBe('none');

    await vi.waitFor(() => {
        expect(fetchMock).toHaveBeenCalledWith('/settings/api/llm.provider', expect.objectContaining({
            method: 'PUT',
            body: JSON.stringify({ value: 'qwen' }),
        }));
    });
});

it.each(API_KEY_PROVIDERS.filter(key => key !== 'openai'))(
    'persists the %s API key through the canonical FastAPI setting route',
    async (key) => {
        const input = document.getElementById(`${key}_api_key`);
        input.value = `replacement-${key}-key`;
        input.dispatchEvent(new Event('change', { bubbles: true }));

        await vi.waitFor(() => {
            const writes = fetchMock.mock.calls.filter(([url, options]) => (
                url === `/settings/api/llm.${key}.api_key`
                && options.method === 'PUT'
            ));
            expect(writes).toHaveLength(1);
        });
        expect(fetchMock).toHaveBeenCalledWith(
            `/settings/api/llm.${key}.api_key`,
            {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': 'research-csrf',
                },
                body: JSON.stringify({ value: `replacement-${key}-key` }),
            },
        );
        // Saving a provider key must refresh just that provider's model
        // catalog (bypassing the 24h server cache for it alone).
        // The targeted refresh is state-changing server-side (it calls the
        // provider with the stored key and rewrites its cached rows), so
        // it must be a CSRF-protected POST, never a bare GET.
        await vi.waitFor(() => {
            expect(fetchMock).toHaveBeenCalledWith(
                `/settings/api/available-models?refresh_provider=${key}`,
                { method: 'POST', headers: { 'X-CSRFToken': 'research-csrf' } },
            );
        });
        expect(fetchMock).not.toHaveBeenCalledWith(
            `/settings/api/available-models?refresh_provider=${key}`,
        );
        // ...and must never echo the key in the success toast.
        await vi.waitFor(() => {
            expect(window.ui.showMessage).toHaveBeenCalledWith(
                `${key} api_key updated`,
                'success',
                2000,
            );
        });
        for (const call of window.ui.showMessage.mock.calls) {
            expect(String(call[0])).not.toContain(`replacement-${key}-key`);
        }
    },
);

it('reports a rejected custom-model save using FastAPI detail and keeps hidden settings in sync', async () => {
    responseOverrides.set('/settings/api/llm.model', {
        body: { detail: 'model is blocked by policy' },
        ok: false,
        status: 422,
    });

    dropdowns.get('model').onSelect('blocked-model', null);

    await vi.waitFor(() => {
        expect(window.ui.showMessage).toHaveBeenCalledWith(
            'Error updating model: model is blocked by policy',
            'error',
            3000,
        );
    });
    expect(document.getElementById('model_hidden').value).toBe('blocked-model');
    expect(document.getElementById('custom-model-warning').textContent)
        .toContain('Custom model name entered');
    expect(fetchMock).toHaveBeenCalledWith('/settings/api/llm.model', expect.objectContaining({
        method: 'PUT',
        headers: expect.objectContaining({ 'X-CSRFToken': 'research-csrf' }),
        body: JSON.stringify({ value: 'blocked-model' }),
    }));
    expect(window.ui.showMessage).not.toHaveBeenCalledWith(
        expect.stringContaining('Model updated'),
        'success',
        2000,
    );
});

it('preserves same-key setting order while unrelated settings save concurrently', async () => {
    const firstModelResponse = deferred();
    const startedWrites = [];
    fetchMock.mockImplementation((url, options = {}) => {
        if (options.method === 'PUT'
            && ['/settings/api/llm.model', '/settings/api/search.iterations'].includes(url)) {
            const value = JSON.parse(options.body).value;
            startedWrites.push({ url, value });
            if (url === '/settings/api/llm.model' && value === 'model-a') {
                return firstModelResponse.promise;
            }
        }
        return routeFetch(url, options);
    });

    dropdowns.get('model').onSelect('model-a', { label: 'Model A' });
    dropdowns.get('model').onSelect('model-b', { label: 'Model B' });

    const iterations = document.getElementById('iterations');
    iterations.value = '4';
    iterations.dispatchEvent(new Event('change', { bubbles: true }));

    await vi.waitFor(() => {
        expect(startedWrites.filter(write => write.url === '/settings/api/llm.model'))
            .toEqual([{ url: '/settings/api/llm.model', value: 'model-a' }]);
        expect(startedWrites).toContainEqual({
            url: '/settings/api/search.iterations',
            value: 4,
        });
    });

    firstModelResponse.resolve(response({ status: 'ok' }));

    await vi.waitFor(() => {
        expect(startedWrites.filter(write => write.url === '/settings/api/llm.model'))
            .toEqual([
                { url: '/settings/api/llm.model', value: 'model-a' },
                { url: '/settings/api/llm.model', value: 'model-b' },
            ]);
        expect(window.ui.showMessage).toHaveBeenCalledWith(
            'Model updated to: model-b',
            'success',
            2000,
        );
    });
});

it.each([
    {
        failure: 'a rejected request',
        message: 'network unavailable',
        settle: pending => pending.reject(new Error('network unavailable')),
    },
    {
        failure: 'a non-ok response',
        message: 'model save unavailable',
        settle: pending => pending.resolve(response(
            { detail: 'model save unavailable' },
            { ok: false, status: 503 },
        )),
    },
])('continues a same-key setting queue after $failure', async ({ message, settle }) => {
    const firstModelResponse = deferred();
    const startedModels = [];
    fetchMock.mockImplementation((url, options = {}) => {
        if (url === '/settings/api/llm.model' && options.method === 'PUT') {
            const value = JSON.parse(options.body).value;
            startedModels.push(value);
            if (startedModels.length === 1) return firstModelResponse.promise;
        }
        return routeFetch(url, options);
    });

    dropdowns.get('model').onSelect('model-before-failure', { label: 'First model' });
    dropdowns.get('model').onSelect('model-after-failure', { label: 'Second model' });

    await vi.waitFor(() => {
        expect(startedModels).toEqual(['model-before-failure']);
    });

    settle(firstModelResponse);

    await vi.waitFor(() => {
        expect(startedModels).toEqual([
            'model-before-failure',
            'model-after-failure',
        ]);
        expect(window.ui.showMessage).toHaveBeenCalledWith(
            `Error updating model: ${message}`,
            'error',
            3000,
        );
        expect(window.ui.showMessage).toHaveBeenCalledWith(
            'Model updated to: model-after-failure',
            'success',
            2000,
        );
    });
});

it('does not claim a rejected search-engine save succeeded', async () => {
    responseOverrides.set('/settings/api/search.tool', {
        body: { detail: 'engine is not allowed for this scope' },
        ok: false,
        status: 400,
    });

    dropdowns.get('search_engine').onSelect('library', {
        label: 'Search All Collections',
    });
    document.getElementById('search_engine_hidden').value = 'library';
    document.getElementById('search_engine_hidden').dispatchEvent(
        new Event('change', { bubbles: true }),
    );

    await vi.waitFor(() => {
        expect(window.ui.showMessage).toHaveBeenCalledWith(
            'Error updating search.tool: engine is not allowed for this scope',
            'error',
            3000,
        );
    });
    expect(document.getElementById('search_engine_hidden').value).toBe('library');
    expect(fetchMock).toHaveBeenCalledWith('/settings/api/search.tool', expect.objectContaining({
        method: 'PUT',
        headers: expect.objectContaining({ 'X-CSRFToken': 'research-csrf' }),
        body: JSON.stringify({ value: 'library' }),
    }));
    expect(window.ui.showMessage).not.toHaveBeenCalledWith(
        expect.stringContaining('Search engine updated'),
        'success',
        2000,
    );
});

it('assigns one settings writer to every control shared with the base bridge', async () => {
    const provider = document.getElementById('model_provider');
    provider.disabled = false;
    provider.value = 'OLLAMA';
    provider.dispatchEvent(new Event('change', { bubbles: true }));

    dropdowns.get('model').onSelect('qwen3:4b', { label: 'Qwen 3' });
    document.getElementById('model_hidden').value = 'qwen3:4b';
    document.getElementById('model_hidden').dispatchEvent(
        new Event('change', { bubbles: true }),
    );

    dropdowns.get('search_engine').onSelect('library', {
        label: 'Search All Collections',
    });
    document.getElementById('search_engine_hidden').value = 'library';
    document.getElementById('search_engine_hidden').dispatchEvent(
        new Event('change', { bubbles: true }),
    );

    const iterations = document.getElementById('iterations');
    iterations.value = '5';
    iterations.dispatchEvent(new Event('change', { bubbles: true }));
    const questions = document.getElementById('questions_per_iteration');
    questions.value = '2';
    questions.dispatchEvent(new Event('change', { bubbles: true }));
    const ollamaUrl = document.getElementById('ollama_url');
    ollamaUrl.value = 'http://ollama-new.test';
    ollamaUrl.dispatchEvent(new Event('change', { bubbles: true }));

    const strategy = document.getElementById('strategy');
    strategy.value = 'source-based';
    strategy.dispatchEvent(new Event('change', { bubbles: true }));
    const customEndpoint = document.getElementById('custom_endpoint');
    customEndpoint.value = 'https://gateway-new.example/v1';
    customEndpoint.dispatchEvent(new Event('change', { bubbles: true }));

    const expectedWrites = new Map([
        ['/settings/api/llm.provider', 'ollama'],
        ['/settings/api/llm.model', 'qwen3:4b'],
        ['/settings/api/search.tool', 'library'],
        ['/settings/api/search.iterations', 5],
        ['/settings/api/search.questions_per_iteration', 2],
        ['/settings/api/llm.ollama.url', 'http://ollama-new.test'],
        ['/settings/api/search.search_strategy', 'source-based'],
        ['/settings/api/llm.openai_endpoint.url', 'https://gateway-new.example/v1'],
    ]);
    await vi.waitFor(() => {
        for (const url of expectedWrites.keys()) {
            expect(fetchMock.mock.calls.filter(([calledUrl, options = {}]) =>
                calledUrl === url && options.method === 'PUT'
            )).toHaveLength(1);
        }
    });
    for (const [url, value] of expectedWrites) {
        expect(fetchMock).toHaveBeenCalledWith(url, expect.objectContaining({
            method: 'PUT',
            body: JSON.stringify({ value }),
        }));
    }
});

it('never echoes an endpoint URL value in the success toast', async () => {
    const credentialUrl = 'http://user:[email protected]/?api_key=url-secret-key';
    const ollamaUrl = document.getElementById('ollama_url');
    ollamaUrl.value = credentialUrl;
    ollamaUrl.dispatchEvent(new Event('change', { bubbles: true }));

    await vi.waitFor(() => {
        expect(window.ui.showMessage).toHaveBeenCalledWith(
            'ollama url updated',
            'success',
            2000,
        );
    });
    for (const call of window.ui.showMessage.mock.calls) {
        expect(String(call[0])).not.toContain('url-secret');
    }
});

it('does not claim a rejected provider save succeeded', async () => {
    responseOverrides.set('/settings/api/llm.provider', {
        body: { detail: 'provider is operator locked' },
        ok: false,
        status: 403,
    });
    const provider = document.getElementById('model_provider');
    provider.disabled = false;
    // research.js is loaded once for this file, so its provider list is
    // whatever the last applied catalog advertised. concurrentModelCatalog()
    // has no ANTHROPIC_ENDPOINT, and when a test using it ran first, this
    // value selected nothing and the change handler saw ''. Add the option
    // like the QwenCloud test does, so the result does not depend on order.
    if (!provider.querySelector('option[value="ANTHROPIC_ENDPOINT"]')) {
        const anthropicOption = document.createElement('option');
        anthropicOption.value = 'ANTHROPIC_ENDPOINT';
        provider.appendChild(anthropicOption);
    }
    provider.value = 'ANTHROPIC_ENDPOINT';
    expect(provider.value).toBe('ANTHROPIC_ENDPOINT');
    provider.dispatchEvent(new Event('change'));

    await vi.waitFor(() => {
        expect(window.ui.showMessage).toHaveBeenCalledWith(
            'Error updating provider: provider is operator locked',
            'error',
            3000,
        );
    });
    expect(document.getElementById('anthropic_endpoint_container').style.display).toBe('block');
    expect(document.getElementById('llm.provider_hidden').value).toBe('ANTHROPIC_ENDPOINT');
    expect(fetchMock).toHaveBeenCalledWith('/settings/api/llm.provider', expect.objectContaining({
        method: 'PUT',
        headers: expect.objectContaining({ 'X-CSRFToken': 'research-csrf' }),
        body: JSON.stringify({ value: 'anthropic_endpoint' }),
    }));
    expect(window.ui.showMessage).not.toHaveBeenCalledWith(
        expect.stringContaining('Provider updated'),
        'success',
        2000,
    );
});

it('surfaces FastAPI detail from a rejected numeric setting save', async () => {
    responseOverrides.set('/settings/api/search.iterations', {
        body: { detail: 'iterations must be between 1 and 10' },
        ok: false,
        status: 422,
    });
    const iterations = document.getElementById('iterations');
    iterations.value = '99';
    iterations.dispatchEvent(new Event('change'));

    await vi.waitFor(() => {
        expect(window.ui.showMessage).toHaveBeenCalledWith(
            'Error updating search.iterations: iterations must be between 1 and 10',
            'error',
            3000,
        );
    });
    expect(fetchMock).toHaveBeenCalledWith('/settings/api/search.iterations', expect.objectContaining({
        method: 'PUT',
        headers: expect.objectContaining({ 'X-CSRFToken': 'research-csrf' }),
        body: JSON.stringify({ value: 99 }),
    }));
});

it('renders a rejected research detail as text and restores submit ownership', async () => {
    window.__researchDetailExecuted = false;
    responseOverrides.set(START_RESEARCH, {
        body: {
            detail: '<img src=x onerror="window.__researchDetailExecuted=true"> denied',
            field: 'policy_egress_scope',
        },
        ok: false,
        status: 400,
    });

    submit();

    await vi.waitFor(() => {
        expect(document.getElementById('start-research-btn').disabled).toBe(false);
    });
    const alert = document.getElementById('research-alert');
    expect(alert.textContent).toContain('<img src=x onerror=');
    expect(alert.querySelector('img')).toBeNull();
    expect(window.__researchDetailExecuted).toBe(false);
    expect(document.querySelector('.ldr-loading-overlay')).toBeNull();
    expect(fetchMock).toHaveBeenCalledWith(START_RESEARCH, expect.objectContaining({
        method: 'POST',
        headers: expect.objectContaining({ 'X-CSRFToken': 'research-csrf' }),
    }));
    delete window.__researchDetailExecuted;
});

it('surfaces a rejected chat-session detail and leaves the form retryable', async () => {
    selectMode('chat');
    responseOverrides.set(CHAT_SESSIONS, {
        body: { detail: 'chat service is temporarily unavailable' },
        ok: false,
        status: 503,
    });

    submit();

    await vi.waitFor(() => {
        expect(document.getElementById('research-alert').textContent)
            .toContain('Failed to start chat: chat service is temporarily unavailable');
    });
    expect(document.getElementById('start-research-btn').disabled).toBe(false);
    expect(document.querySelector('.ldr-loading-overlay')).toBeNull();
    const creates = fetchMock.mock.calls.filter(([url]) => url === CHAT_SESSIONS);
    expect(creates).toHaveLength(1);
    expect(creates[0][1]).toMatchObject({
        method: 'POST',
        body: JSON.stringify({ initial_query: 'A current research query' }),
    });
    expect(new globalThis.Headers(creates[0][1].headers).get('X-CSRFToken')).toBe('research-csrf');
    expect(new globalThis.Headers(creates[0][1].headers).get('X-LDR-Auth-Context')).toBe(AUTH_CONTEXT);
});

async function withCapturedChatLocation(run) {
    const ownLocation = Object.getOwnPropertyDescriptor(window, 'location');
    const startHref = 'http://localhost/';
    const fakeLocation = { href: startHref, pathname: '/' };
    Object.defineProperty(window, 'location', {
        configurable: true,
        writable: true,
        value: fakeLocation,
    });
    try {
        return await run(fakeLocation, startHref);
    } finally {
        if (ownLocation) {
            Object.defineProperty(window, 'location', ownLocation);
        } else {
            delete window.location;
        }
    }
}

// Exercise both real main-form POSTs and capture its final navigation.
async function submitChatAndCaptureNavigation(sessionId) {
    return withCapturedChatLocation(async (fakeLocation, startHref) => {
        selectMode('chat');
        responseOverrides.set(CHAT_SESSIONS, {
            body: { success: true, session_id: sessionId },
        });
        responseOverrides.set(`${CHAT_SESSIONS}/${encodeURIComponent(sessionId)}/messages`, {
            body: { success: true, research_id: 'started-research' },
        });
        submit();
        await vi.waitFor(() => {
            expect(fakeLocation.href).not.toBe(startHref);
            expect(document.getElementById('start-research-btn').disabled)
                .toBe(false);
        });
        return fakeLocation.href;
    });
}

it('posts the chat query once with its original login before opening a clean URL', async () => {
    const setItem = vi.spyOn(window.sessionStorage, 'setItem');
    try {
        const target = await submitChatAndCaptureNavigation('created-session');
        expect(target).toBe('/chat/created-session');
        expect(setItem).not.toHaveBeenCalled();
        const writes = fetchMock.mock.calls.filter(([url]) => url.startsWith(CHAT_SESSIONS));
        expect(writes.map(([url]) => url)).toEqual([
            CHAT_SESSIONS,
            `${CHAT_SESSIONS}/created-session/messages`,
        ]);
        expect(JSON.parse(writes[0][1].body)).toEqual({ initial_query: 'A current research query' });
        expect(JSON.parse(writes[1][1].body)).toEqual({
            content: 'A current research query', trigger_research: true,
        });
        for (const [, options] of writes) {
            expect(options.method).toBe('POST');
            expect(new globalThis.Headers(options.headers).get('X-CSRFToken')).toBe('research-csrf');
            expect(new globalThis.Headers(options.headers).get('X-LDR-Auth-Context')).toBe(AUTH_CONTEXT);
        }
    } finally {
        setItem.mockRestore();
    }
});

it('starts chat without a storage or URL fallback when browser storage is disabled', async () => {
    const setItem = vi.spyOn(window.sessionStorage, 'setItem')
        .mockImplementation(() => {
            throw new Error('Storage is disabled');
        });
    try {
        const target = await submitChatAndCaptureNavigation('no-storage-session');
        expect(setItem).not.toHaveBeenCalled();
        expect(target).toBe('/chat/no-storage-session');
    } finally {
        setItem.mockRestore();
    }
});

it('holds submit ownership through session creation and message acceptance', async () => {
    const creation = deferred();
    const message = deferred();
    const createdId = 'owned-session';
    const messageUrl = `${CHAT_SESSIONS}/${createdId}/messages`;
    fetchMock.mockImplementation((url, options) => {
        if (url === CHAT_SESSIONS) return creation.promise;
        if (url === messageUrl) return message.promise;
        return routeFetch(url, options);
    });
    await withCapturedChatLocation(async (location, initialHref) => {
        selectMode('chat');
        submit();
        submit();
        expect(fetchMock.mock.calls.filter(([url]) => url === CHAT_SESSIONS)).toHaveLength(1);
        expect(location.href).toBe(initialHref);
        expect(document.getElementById('start-research-btn').disabled).toBe(true);
        expect(fetchMock.mock.calls.some(([url]) => url === messageUrl)).toBe(false);

        // The accepted submission retains its original input across both awaits.
        document.getElementById('query').value = 'A later edit';
        creation.resolve(await response({ success: true, session_id: createdId }));
        await vi.waitFor(() => expect(fetchMock.mock.calls.some(([url]) => url === messageUrl)).toBe(true));
        submit();
        expect(fetchMock.mock.calls.filter(([url]) => url === messageUrl)).toHaveLength(1);
        expect(location.href).toBe(initialHref);
        expect(document.getElementById('start-research-btn').disabled).toBe(true);
        const sent = fetchMock.mock.calls.find(([url]) => url === messageUrl);
        expect(JSON.parse(sent[1].body).content).toBe('A current research query');

        message.resolve(await response({ success: true, research_id: 'accepted-research' }));
        await vi.waitFor(() => {
            expect(location.href).toBe(`/chat/${createdId}`);
            expect(document.getElementById('start-research-btn').disabled).toBe(false);
        });
        expect(document.querySelector('.ldr-loading-overlay')).toBeNull();
    });
});

it.each([
    [400, false], [401, false], [403, false], [404, false],
    [409, false], [429, false], [500, true], [200, true],
])('keeps a rejected message (%s) retryable without replaying it', async (status, uncertain) => {
    const messageUrl = `${CHAT_SESSIONS}/rejected-session/messages`;
    responseOverrides.set(CHAT_SESSIONS, { body: { success: true, session_id: 'rejected-session' } });
    responseOverrides.set(messageUrl, {
        body: { success: false, detail: 'Chat request rejected' },
        ok: status >= 200 && status < 300, status,
    });
    await withCapturedChatLocation(async (location, initialHref) => {
        selectMode('chat');
        submit();
        await vi.waitFor(() => {
            expect(document.getElementById('research-alert').textContent).toContain('Chat request rejected');
            expect(document.getElementById('start-research-btn').disabled).toBe(false);
        });
        expect(location.href).toBe(initialHref);
        expect(document.getElementById('query').value).toBe('A current research query');
        expect(document.querySelector('.ldr-loading-overlay')).toBeNull();
        expect(fetchMock.mock.calls.filter(([url]) => url === CHAT_SESSIONS)).toHaveLength(1);
        expect(fetchMock.mock.calls.filter(([url]) => url === messageUrl)).toHaveLength(1);
        expect(fetchMock.mock.calls.some(([url]) => url === '/auth/csrf-token')).toBe(false);
        const recovery = document.querySelector('#research-alert a');
        if (uncertain) expect(recovery?.getAttribute('href')).toBe('/chat/rejected-session');
        else expect(recovery).toBeNull();
    });
});

it.each(['network', 'invalid-json'])('offers read-only recovery after an uncertain %s message response', async (failure) => {
    const messageUrl = `${CHAT_SESSIONS}/uncertain-session/messages`;
    responseOverrides.set(CHAT_SESSIONS, { body: { success: true, session_id: 'uncertain-session' } });
    fetchMock.mockImplementation((url, options) => {
        if (url === messageUrl) {
            if (failure === 'network') return Promise.reject(new Error('Network interrupted'));
            return Promise.resolve({ ok: true, status: 200, json: () => Promise.reject(new Error('Invalid JSON')) });
        }
        return routeFetch(url, options);
    });
    await withCapturedChatLocation(async (location, initialHref) => {
        selectMode('chat');
        submit();
        await vi.waitFor(() => {
            expect(document.querySelector('#research-alert a')?.getAttribute('href')).toBe('/chat/uncertain-session');
            expect(document.getElementById('start-research-btn').disabled).toBe(false);
        });
        expect(location.href).toBe(initialHref);
        expect(document.getElementById('query').value).toBe('A current research query');
        expect(fetchMock.mock.calls.filter(([url]) => url === CHAT_SESSIONS)).toHaveLength(1);
        expect(fetchMock.mock.calls.filter(([url]) => url === messageUrl)).toHaveLength(1);
        expect(document.querySelector('.ldr-loading-overlay')).toBeNull();
    });
});

it('uses a same-login CSRF refresh only before a rejected handler and sends one message', async () => {
    const id = 'refreshed-session';
    let creates = 0;
    fetchMock.mockImplementation((url, options) => {
        if (url === CHAT_SESSIONS) {
            creates++;
            if (creates === 1) return response({ detail: 'CSRF rejected' }, {
                ok: false, status: 403, headers: { 'X-LDR-CSRF-Rejected': '1' },
            });
            return response({ success: true, session_id: id });
        }
        if (url === '/auth/csrf-token') return response({
            auth_context: AUTH_CONTEXT, csrf_token: 'fresh-same-login',
        });
        return routeFetch(url, options);
    });
    expect(await submitChatAndCaptureNavigation(id)).toBe(`/chat/${id}`);
    const writes = fetchMock.mock.calls.filter(([url]) => url.startsWith(CHAT_SESSIONS));
    expect(writes.map(([url]) => url)).toEqual([CHAT_SESSIONS, CHAT_SESSIONS, `${CHAT_SESSIONS}/${id}/messages`]);
    expect(writes.map(([, options]) => new globalThis.Headers(options.headers).get('X-CSRFToken')))
        .toEqual(['research-csrf', 'fresh-same-login', 'fresh-same-login']);
    expect(writes.map(([, options]) => new globalThis.Headers(options.headers).get('X-LDR-Auth-Context')))
        .toEqual([AUTH_CONTEXT, AUTH_CONTEXT, AUTH_CONTEXT]);
});

it('does not replay either write under a replacement login during CSRF recovery', async () => {
    responseOverrides.set(CHAT_SESSIONS, {
        body: { detail: 'CSRF rejected' }, ok: false, status: 403,
        headers: { 'X-LDR-CSRF-Rejected': '1' },
    });
    responseOverrides.set('/auth/csrf-token', {
        body: { detail: 'Your sign-in changed' }, ok: false, status: 409,
    });
    await withCapturedChatLocation(async (location, initialHref) => {
        selectMode('chat');
        submit();
        await vi.waitFor(() => {
            expect(document.getElementById('research-alert').textContent).toContain('Your sign-in changed');
            expect(document.getElementById('start-research-btn').disabled).toBe(false);
        });
        expect(location.href).toBe(initialHref);
        expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([CHAT_SESSIONS, '/auth/csrf-token']);
        expect(new globalThis.Headers(fetchMock.mock.calls[1][1].headers).get('X-LDR-Auth-Context')).toBe(AUTH_CONTEXT);
    });
});

it('fails without sending when the protected request helper is unavailable', async () => {
    const saved = window.api.fetchWithCsrfRecovery;
    delete window.api.fetchWithCsrfRecovery;
    try {
        selectMode('chat');
        submit();
        expect(document.getElementById('research-alert').textContent).toContain('Reload this page');
        expect(fetchMock).not.toHaveBeenCalled();
        expect(document.getElementById('start-research-btn').disabled).toBe(false);
        expect(document.querySelector('.ldr-loading-overlay')).toBeNull();
    } finally {
        window.api.fetchWithCsrfRecovery = saved;
    }
});

it('anchors the custom-model hint under ldr-prefixed research markup', async () => {
    // The research page wraps the model dropdown in `.ldr-form-group` only.
    // Reverting the prefixed selector makes `closest('.form-group')` return
    // null, and the warning element is built and then dropped on the floor.
    document.getElementById('custom-model-warning')?.remove();
    const wrapper = document.getElementById('model-dropdown').parentElement;
    wrapper.className = 'ldr-form-group';
    try {
        expect(wrapper.closest('.form-group')).toBeNull();

        dropdowns.get('model').onSelect('a-model-not-in-the-list', null);

        await vi.waitFor(() => {
            expect(document.getElementById('custom-model-warning')).not.toBeNull();
        });
        const warning = document.getElementById('custom-model-warning');
        expect(warning.parentElement).toBe(wrapper);
        expect(warning.textContent).toContain('Custom model name entered');
        expect(warning.style.display).toBe('block');
    } finally {
        wrapper.className = 'form-group';
    }
});

// These fixtures model the server's early snapshot of the other providers:
// each targeted response has fresh models for its target and old models for
// the other provider, even when both requests eventually succeed.
function concurrentModelCatalog(qwen = ['qwen-before-save'], openai = ['openai-before-save']) {
    const models = (values, provider) => values.map(value => ({ value, label: value, provider }));
    return {
        provider_options: [
            { value: 'QWEN', label: 'QwenCloud', is_cloud: true },
            { value: 'OPENAI', label: 'OpenAI', is_cloud: true },
            { value: 'OLLAMA', label: 'Ollama', is_cloud: false },
            { value: 'OPENAI_ENDPOINT', label: 'OpenAI-compatible', is_cloud: true },
        ],
        providers: {
            qwen_models: models(qwen, 'QWEN'),
            openai_models: models(openai, 'OPENAI'),
            ollama_models: models(['qwen3:4b'], 'OLLAMA'),
            openai_endpoint_models: models(['gateway-model'], 'OPENAI_ENDPOINT'),
        },
    };
}

async function concurrentModelRequests() {
    // Seed the private cache through the real refresh handler, so each case
    // begins with the same catalog even though this runtime is initialized once.
    const refreshButton = document.getElementById('model-refresh');
    responseOverrides.set(FULL_REFRESH_URL, {
        body: concurrentModelCatalog(),
    });
    refreshButton.click();
    await vi.waitFor(() => expect(refreshButton.classList.contains('ldr-loading')).toBe(false));
    // The manual full refresh is a CSRF-protected POST ?force_refresh=true:
    // a GET carrying force_refresh=true answers 405, and a POST without it
    // would reuse the server's cache.
    expect(fetchMock).toHaveBeenCalledWith(FULL_REFRESH_URL, FULL_REFRESH_REQUEST);

    const requests = [];
    fetchMock.mockImplementation((url, options = {}) => {
        if (typeof url === 'string' && url.startsWith(AVAILABLE_MODELS)) {
            const provider = new URL(url, 'http://localhost').searchParams.get('refresh_provider');
            const pending = deferred();
            requests.push({ url, provider, options, pending });
            return pending.promise;
        }
        if (options.method === 'PUT') return response({ status: 'ok' });
        return routeFetch(url, options);
    });
    return {
        requests,
        async saveKey(provider, value) {
            const count = requests.length;
            const input = document.getElementById(`${provider}_api_key`);
            input.value = value;
            input.dispatchEvent(new Event('change', { bubbles: true }));
            await vi.waitFor(() => expect(requests).toHaveLength(count + 1));
            expect(requests[count].provider).toBe(provider);
            return requests[count];
        },
        async refreshAll() {
            const count = requests.length;
            refreshButton.click();
            await vi.waitFor(() => expect(requests).toHaveLength(count + 1));
            expect(requests[count].provider).toBeNull();
            expect(requests[count].url).toBe(FULL_REFRESH_URL);
            expect(requests[count].options).toEqual(FULL_REFRESH_REQUEST);
            return requests[count];
        },
    };
}

async function settleModelRequest(request, catalog, options) {
    const field = document.getElementById('model').parentNode;
    field.classList.add('ldr-loading');
    request.pending.resolve(response(catalog, options));
    await vi.waitFor(() => expect(field.classList.contains('ldr-loading')).toBe(false));
}

function modelValuesForProvider(provider) {
    const select = document.getElementById('model_provider');
    // Enable the fixture's controls to exercise an ordinary editable form.
    select.disabled = false;
    document.getElementById('model').disabled = false;
    select.value = provider;
    expect(select.value).toBe(provider);
    select.dispatchEvent(new Event('change', { bubbles: true }));
    return dropdowns.get('model').getOptions().map(option => option.value);
}

it.each([
    ['qwen', 'openai'],
    ['openai', 'qwen'],
])('keeps both targeted updates when %s finishes before %s', async (first, second) => {
    const harness = await concurrentModelRequests();
    const requests = {
        qwen: await harness.saveKey('qwen', 'new-qwen-key'),
        openai: await harness.saveKey('openai', 'new-openai-key'),
    };
    const catalogs = {
        qwen: concurrentModelCatalog(['qwen-after-save']),
        openai: concurrentModelCatalog(undefined, ['openai-after-save']),
    };
    await settleModelRequest(requests[first], catalogs[first]);
    await settleModelRequest(requests[second], catalogs[second]);
    expect(modelValuesForProvider('QWEN')).toEqual(['qwen-after-save']);
    expect(modelValuesForProvider('OPENAI')).toEqual(['openai-after-save']);
});

it('keeps a successful targeted update when the newer other-provider request fails', async () => {
    const harness = await concurrentModelRequests();
    const qwen = await harness.saveKey('qwen', 'new-qwen-key');
    const openai = await harness.saveKey('openai', 'new-openai-key');
    await settleModelRequest(qwen, concurrentModelCatalog(['qwen-after-save']));
    await settleModelRequest(openai, {}, { ok: false, status: 503 });
    expect(modelValuesForProvider('QWEN')).toEqual(['qwen-after-save']);
});

it.each([true, false])('ignores an older same-provider response (success=%s)', async olderSucceeds => {
    const harness = await concurrentModelRequests();
    const older = await harness.saveKey('qwen', 'older-qwen-key');
    const newer = await harness.saveKey('qwen', 'replacement-qwen-key');
    await settleModelRequest(newer, concurrentModelCatalog(['qwen-new-key-model']));
    await settleModelRequest(older, concurrentModelCatalog(['qwen-old-key-model']), {
        ok: olderSucceeds,
        status: olderSucceeds ? 200 : 503,
    });
    expect(modelValuesForProvider('QWEN')).toEqual(['qwen-new-key-model']);
});

it.each([true, false])('merges a full reload with a newer target (full finishes first=%s)', async fullFirst => {
    const harness = await concurrentModelRequests();
    const full = await harness.refreshAll();
    const qwen = await harness.saveKey('qwen', 'new-qwen-key');
    const finishFull = () => settleModelRequest(full, concurrentModelCatalog(undefined, ['openai-full-refresh']));
    const finishTarget = () => settleModelRequest(qwen, concurrentModelCatalog(['qwen-after-save']));
    if (fullFirst) {
        await finishFull();
        await finishTarget();
    } else {
        await finishTarget();
        await finishFull();
    }
    expect(modelValuesForProvider('QWEN')).toEqual(['qwen-after-save']);
    expect(modelValuesForProvider('OPENAI')).toEqual(['openai-full-refresh']);
});

it('preserves a newer empty target list when an older full reload lands', async () => {
    const harness = await concurrentModelRequests();
    const full = await harness.refreshAll();
    const qwen = await harness.saveKey('qwen', 'new-qwen-key');
    await settleModelRequest(qwen, concurrentModelCatalog([]));
    await settleModelRequest(full, concurrentModelCatalog());
    expect(modelValuesForProvider('QWEN')).not.toContain('qwen-before-save');
});

it('does not restore cloud models from a target superseded by a policy reload', async () => {
    const harness = await concurrentModelRequests();
    const qwen = await harness.saveKey('qwen', 'new-qwen-key');
    const checkbox = document.getElementById('llm_require_local_endpoint');
    checkbox.checked = true;
    checkbox.dispatchEvent(new Event('change', { bubbles: true }));
    await vi.waitFor(() => expect(harness.requests).toHaveLength(2));
    const policyRequest = harness.requests[1];
    expect(policyRequest.provider).toBeNull();
    const localCatalog = concurrentModelCatalog([], []);
    localCatalog.provider_options.forEach(option => {
        if (option.is_cloud) option.disabled = true;
    });
    delete localCatalog.providers.openai_endpoint_models;
    await settleModelRequest(policyRequest, localCatalog);
    await settleModelRequest(qwen, concurrentModelCatalog(['qwen-after-save']));
    expect(document.querySelector('#model_provider option[value="QWEN"]').disabled).toBe(true);
    expect(modelValuesForProvider('QWEN')).not.toContain('qwen-after-save');
    checkbox.checked = false;
});

it('ignores an older full reload after a newer full reload has completed', async () => {
    const harness = await concurrentModelRequests();
    const older = await harness.refreshAll();
    const newer = await harness.refreshAll();
    await settleModelRequest(newer, concurrentModelCatalog(['qwen-newer-full']));
    await settleModelRequest(older, concurrentModelCatalog(['qwen-older-full']));
    expect(modelValuesForProvider('QWEN')).toEqual(['qwen-newer-full']);
});

it('keeps current provider restrictions when an independent older target responds', async () => {
    const harness = await concurrentModelRequests();
    const qwen = await harness.saveKey('qwen', 'new-qwen-key');
    const openai = await harness.saveKey('openai', 'new-openai-key');
    const currentCatalog = concurrentModelCatalog([], ['openai-after-save']);
    currentCatalog.provider_options.find(option => option.value === 'QWEN').disabled = true;
    await settleModelRequest(openai, currentCatalog);
    await settleModelRequest(qwen, concurrentModelCatalog(['qwen-after-save']));
    expect(document.querySelector('#model_provider option[value="QWEN"]').disabled).toBe(true);
    expect(modelValuesForProvider('QWEN')).not.toContain('qwen-after-save');
    expect(modelValuesForProvider('OPENAI')).toEqual(['openai-after-save']);
});