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.

16.1 KB
Raw Blame
/**
 * Research form handling with settings management and warnings
 * Note: URLValidator is available globally via /static/js/security/url-validator.js
 */

// Global settings cache for warning logic
let globalSettings = {};

document.addEventListener('DOMContentLoaded', function() {
    // Initialize the research form
    initResearchForm();
});

/**
 * Initialize the research form with values from settings
 */
function initResearchForm() {
    // Get form elements
    const iterationsInput = document.getElementById('iterations');
    const questionsInput = document.getElementById('questions_per_iteration');

    // Fetch all settings at once (more efficient)
    fetch(URLS.SETTINGS_API.BASE)
        .then(response => {
            if (!response.ok) {
                throw new Error('Failed to fetch settings');
            }
            return response.json();
        })
        .then(data => {
            if (data && data.status === 'success' && data.settings) {
                // Find our specific settings
                const settings = data.settings;

                // Cache settings globally for warning logic
                globalSettings = settings;

                // Look for the iterations setting
                for (const key in settings) {
                    const setting = settings[key];
                    if (key === 'search.iterations' && iterationsInput) {
                        iterationsInput.value = setting.value;
                    }

                    if (key === 'search.questions_per_iteration' && questionsInput) {
                        questionsInput.value = setting.value;
                    }
                }

                // Initialize warnings after settings are loaded
                initializeWarnings();
            }
        })
        .catch(_error => {
            // Form will use default values if settings can't be loaded
        });

    // Add our settings saving to the form submission process
    patchFormSubmitHandler();
}

/**
 * Patch the existing form submit handler to include our settings saving functionality
 */
function patchFormSubmitHandler() {
    // Get the form element
    const form = document.getElementById('research-form');
    if (!form) return;

    // Monitor for form submissions using the capture phase to run before other handlers
    form.addEventListener('submit', function() {
        // Save research settings first, before the main form handler processes the submission
        saveResearchSettings();

        // Let the event continue normally to the other handlers
    }, true); // true enables capture phase
}

/**
 * Save research settings to the database
 */
function saveResearchSettings() {
    const iterationsInput = document.getElementById('iterations');
    const questionsInput = document.getElementById('questions_per_iteration');

    // Only save if the elements exist (not on follow-up modal)
    if (!iterationsInput || !questionsInput) {
        return;
    }

    const iterations = iterationsInput.value;
    const questions = questionsInput.value;

    // Get CSRF token
    const csrfToken = window.api ? window.api.getCsrfToken() : '';

    if (!csrfToken) {
        SafeLogger.warn('CSRF token not found, skipping settings save');
        return;
    }

    // Save settings
    fetch(URLS.SETTINGS_API.SAVE_ALL_SETTINGS, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': csrfToken
        },
        body: JSON.stringify({
            'search.iterations': parseInt(iterations, 10),
            'search.questions_per_iteration': parseInt(questions, 10)
        })
    })
    .then(response => response.json())
    .then(_data => {
        SafeLogger.log('Research settings saved');
    })
    .catch(error => {
        SafeLogger.error('Error saving research settings:', error);
    });
}

/**
 * Initialize warning system
 */
function initializeWarnings() {

    // Check warnings on form load
    checkAndDisplayWarnings();

    // Monitor form changes for dynamic warnings
    setupWarningListeners();

    // Clear any stale warnings immediately when initializing
    setTimeout(() => {
        checkAndDisplayWarnings();
    }, 100);
}

/**
 * Setup event listeners for settings changes
 */
function setupWarningListeners() {
    // Monitor provider changes directly and refetch settings
    const providerSelect = document.getElementById('model_provider');
    if (providerSelect) {
        providerSelect.addEventListener('change', function() {
            // Wait a bit longer for the saveProviderSetting API call to complete
            setTimeout(refetchSettingsAndUpdateWarnings, 500);
        });
    }

    // Hook into the existing saveProviderSetting function if it exists
    // This will trigger when the research.js calls saveProviderSetting
    if (typeof window.saveProviderSetting === 'function') {
        const originalSaveProviderSetting = window.saveProviderSetting;
        window.saveProviderSetting = function(...args) {
            // Call the original function
            const result = originalSaveProviderSetting.apply(this, args);
            // After it completes, refetch settings and update warnings
            setTimeout(refetchSettingsAndUpdateWarnings, 200);
            return result;
        };
    }

    // Monitor search engine changes
    const searchEngineInput = document.getElementById('search_engine');
    if (searchEngineInput) {
        searchEngineInput.addEventListener('change', function() {
            // Refresh warnings immediately when search engine changes
            setTimeout(checkAndDisplayWarnings, 100);
        });
    }

    const strategySelect = document.getElementById('strategy');
    if (strategySelect) {
        strategySelect.addEventListener('change', function() {
            // Strategy is saved via settings_sync.js handler
            // Just update warnings after change
            setTimeout(checkAndDisplayWarnings, 100);
        });
    }

    // Use the global socket manager to listen for settings changes (backup)
    const socketInstance = window.socket ? (window.socket.getSocketInstance() || window.socket.init()) : null;
    if (socketInstance) {
        socketInstance.on('settings_changed', function(data) {
            // Update global settings cache
            if (data.settings) {
                Object.assign(globalSettings, data.settings);
            }
            // Recheck warnings with new settings
            setTimeout(checkAndDisplayWarnings, 100);
        });
    }
}

/**
 * Refetch settings from the server and update warnings
 */
function refetchSettingsAndUpdateWarnings() {

    fetch(URLS.SETTINGS_API.BASE)
        .then(response => {
            if (!response.ok) {
                throw new Error('Failed to fetch settings');
            }
            return response.json();
        })
        .then(data => {
            if (data && data.status === 'success' && data.settings) {
                // Update global settings cache
                globalSettings = data.settings;
            }
            // Recheck warnings from backend (not from cached settings)
            setTimeout(checkAndDisplayWarnings, 100);
        })
        .catch(_error => {
            // Still try to check warnings from backend
            setTimeout(checkAndDisplayWarnings, 100);
        });
}

/**
 * Manually clear all warnings (useful for debugging stale warnings)
 */
function clearAllWarnings() {
    updateWarnings([]);
}

let warningsRequestGeneration = 0;
// Capture the renderer before replacing its classic-script window binding.
const renderResearchWarnings = displayWarnings;

// Make functions globally available for other scripts
window.refetchSettingsAndUpdateWarnings = refetchSettingsAndUpdateWarnings;
window.displayWarnings = updateWarnings;
window.clearAllWarnings = clearAllWarnings;
window.checkAndDisplayWarnings = checkAndDisplayWarnings;

function validWarnings(warnings) {
    return Array.isArray(warnings) && warnings.every(warning =>
        warning !== null && typeof warning === 'object' && !Array.isArray(warning)
    );
}

function setWarningRefreshStatus(message) {
    let status = document.getElementById('research-warning-refresh-status');
    if (!message) {
        status?.remove();
        return;
    }
    const container = document.getElementById('research-notices')
        || document.getElementById('research-alert');
    if (!container) return;
    if (!status) {
        status = document.createElement('p');
        status.id = 'research-warning-refresh-status';
        status.setAttribute('role', 'status');
        status.setAttribute('aria-live', 'polite');
        container.before(status);
    }
    status.textContent = message;
}

// Settings saves and explicit clears supersede any older in-flight read.
// Keep this public update path separate from the renderer so every producer
// shares the same ordering regardless of the page's notice layout.
function updateWarnings(warnings) {
    if (!validWarnings(warnings)) return;
    warningsRequestGeneration += 1;
    setWarningRefreshStatus('');
    renderResearchWarnings(warnings);
}

/**
 * Check warning conditions by fetching from backend
 */
function checkAndDisplayWarnings() {
    const requestGeneration = ++warningsRequestGeneration;

    // Get warnings from backend API instead of calculating locally
    return fetch(URLS.SETTINGS_API.WARNINGS)
        .then(response => {
            if (!response.ok) {
                throw new Error('Failed to fetch warnings');
            }
            return response.json();
        })
        .then(data => {
            if (requestGeneration !== warningsRequestGeneration) return;
            if (!data || !validWarnings(data.warnings)) {
                throw new Error('Invalid warnings response');
            }
            updateWarnings(data.warnings);
        })
        .catch(_error => {
            if (requestGeneration !== warningsRequestGeneration) return;
            // Keep the last successful notices until a valid response arrives.
            setWarningRefreshStatus('Could not refresh notices. Refresh the page to try again.');
        });
}

/**
 * Display warnings in the alert container
 */
function displayWarnings(warnings) {
    const alertContainer = document.getElementById('research-alert');
    if (!alertContainer) return;

    if (warnings.length === 0) {
        alertContainer.style.display = 'none';
        alertContainer.innerHTML = '';
        return;
    }

    // Security: escapeHtml applied to API-controlled warning fields before innerHTML insertion
    // bearer:disable javascript_lang_manual_html_sanitization
    const esc = window.escapeHtml || (s => String(s || '').replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":"&#39;"})[m]));
    // Wrap LDR_… env-var tokens (optionally with their =value) in <code> so
    // the copy-paste remedy stands out from the prose. Runs on the
    // ALREADY-ESCAPED string and only ever inserts <code> tags around
    // matched text, so it cannot introduce markup injection. A trailing
    // sentence period is excluded from the =value capture.
    const withCodeTokens = (escaped) => escaped.replace(
        /\bLDR_[A-Z0-9_]+(?:=[^\s,)]*[^\s,.)])?/g,
        m => `<code style="font-size: 13px; padding: 1px 4px; border-radius: 3px; background: rgba(127,127,127,0.15); word-break: break-all;">${m}</code>`
    );
    const warningsHtml = warnings.map(warning => {
        // Use success styling for recommendations/tips, warning for others
        const isInfo = warning.type === 'searxng_recommendation' || warning.type === 'legacy_server_config' || warning.type === 'backup_info';
        const alertClass = isInfo ? 'ldr-alert-info' : 'ldr-alert-warning';

        // The browser treats /\host and /<TAB>/host as protocol-relative
        // URLs too. Resolve the path before deciding whether it stays here.
        let safeActionUrl = null;
        if (typeof warning.actionUrl === 'string'
            && warning.actionUrl.startsWith('/')
            && !warning.actionUrl.startsWith('//')) {
            try {
                if (new URL(warning.actionUrl, window.location.href).origin === window.location.origin) {
                    safeActionUrl = warning.actionUrl;
                }
            } catch (_error) {
                // A malformed optional action has no link.
            }
        }
        const actionHtml = safeActionUrl
            ? `<a href="${esc(safeActionUrl)}" class="ldr-alert-action">
                  ${esc(warning.actionLabel || 'View details')}
                  <span aria-hidden="true">→</span>
               </a>`
            : '';
        // Only render the dismiss control for warnings that declare a
        // dismissKey. Banners with dismissKey == null are deliberately
        // non-dismissible; rendering the button would call dismissWarning('null')
        // and POST a bogus "null" settings key.
        const dismissHtml = warning.dismissKey
            ? `<button type="button" class="ldr-warning-dismiss" data-dismiss-key="${esc(warning.dismissKey)}" style="
                background: none;
                border: none;
                color: inherit;
                cursor: pointer;
                padding: 4px;
                font-size: 16px;
                flex-shrink: 0;
                opacity: 0.7;
            ">&times;</button>`
            : '';
        return `
        <div class="ldr-alert ${alertClass} warning-banner warning-${esc(warning.type)}" style="
            border-radius: 6px;
            padding: 12px 16px;
            margin-bottom: 8px;
            display: flex;
            align-items: flex-start;
            gap: 12px;
        ">
            <span style="font-size: 16px; flex-shrink: 0;">${esc(warning.icon)}</span>
            <div style="flex: 1;">
                <div style="font-weight: 600; margin-bottom: 4px;">
                    ${esc(warning.title)}
                </div>
                <div style="font-size: 14px; line-height: 1.4;">
                    ${withCodeTokens(esc(warning.message))}
                </div>
                ${actionHtml}
            </div>
            ${dismissHtml}
        </div>
        `;
    }).join('');

    // bearer:disable javascript_lang_dangerous_insert_html
    // eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: variable built from escaped/numeric values above
    alertContainer.innerHTML = warningsHtml;
    // Bind dismissals without inline JavaScript. HTML escaping alone is not a
    // JavaScript-string escape, so putting an API-provided key inside onclick
    // would make quote handling fragile even though the visible HTML is safe.
    alertContainer.querySelectorAll('.ldr-warning-dismiss[data-dismiss-key]').forEach(button => {
        button.addEventListener('click', () => dismissWarning(button.dataset.dismissKey));
    });
    alertContainer.style.display = 'block';
}

/**
 * Dismiss a warning by updating the setting
 */
async function dismissWarning(dismissKey) {

    // Get CSRF token
    const csrfToken = window.api ? window.api.getCsrfToken() : '';

    // Update dismissal setting
    try {
        const response = await fetch(URLS.SETTINGS_API.SAVE_ALL_SETTINGS, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            },
            body: JSON.stringify({
                [dismissKey]: true
            })
        });
        const data = await response.json();
        if (!response.ok || data.status !== 'success') {
            throw new Error(
                data.error || data.message || data.detail || 'Failed to dismiss warning'
            );
        }
        // Update global settings cache
        globalSettings[dismissKey] = { value: true };
        // Recheck warnings
        return checkAndDisplayWarnings();
    } catch (error) {
        SafeLogger.error('Failed to dismiss warning:', error);
        return undefined;
    }
}

// Explicit global contract for templates and direct browser-runtime tests.
window.dismissWarning = dismissWarning;

/**
 * Helper function to get settings
 */
function getSetting(key, defaultValue) {
    return globalSettings[key] ? globalSettings[key].value : defaultValue;
}