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.

17.0 KB
Raw Blame
/**
 * Note: URLValidator is available globally via /static/js/security/url-validator.js
 * Follow-up Research JavaScript Module
 *
 * Handles UI interactions for asking follow-up questions on existing research.
 */

class FollowUpResearch {
    constructor() {
        this.parentResearchId = null;
        this.modalElement = null;
        this.modalLoadPromise = null;
        this.submitInProgress = false;
    }

    /**
     * Initialize follow-up button on research results
     */
    init() {
        // Get research ID from page
        this.parentResearchId = this.getResearchIdFromPage();

        SafeLogger.log('Follow-up Research: Parent research ID:', this.parentResearchId);

        // Set up the follow-up button if it exists
        const followUpBtn = document.getElementById('ask-followup-btn');
        if (followUpBtn) {
            if (this.parentResearchId) {
                followUpBtn.onclick = () => this.showFollowUpModal();
            } else {
                SafeLogger.warn('Follow-up Research: No research ID found, disabling button');
                followUpBtn.disabled = true;
                followUpBtn.title = 'No research ID available';
            }
        }

        // Create modal for follow-up questions
        this.createModal();
    }

    /**
     * Get research ID from current page
     */
    getResearchIdFromPage() {
        // Try multiple ways to get research ID

        // 1. From URL path (e.g., /results/abc-123-def)
        const pathMatch = window.location.pathname.match(/\/results\/([a-zA-Z0-9-]+)/);
        if (pathMatch) {
            return pathMatch[1];
        }

        // 2. From URL params
        const urlParams = new URLSearchParams(window.location.search);
        const paramId = urlParams.get('research_id');
        if (paramId) {
            return paramId;
        }

        // 3. From data attribute
        const dataId = document.querySelector('[data-research-id]')?.dataset.researchId;
        if (dataId) {
            return dataId;
        }

        // 4. From window variable (set by results.js)
        if (window.currentResearchId) {
            return window.currentResearchId;
        }

        return null;
    }

    /**
     * Create modal for follow-up questions
     */
    async createModal() {
        // Check if modal already exists
        const existingModal = document.getElementById('followUpModal');
        if (existingModal) {
            this.modalElement = existingModal;
            return;
        }

        // init() starts loading eagerly. If the user clicks before that fetch
        // settles, showFollowUpModal() comes through here too; both callers
        // must own the same request and the same eventual DOM node.
        if (this.modalLoadPromise) {
            await this.modalLoadPromise;
            return;
        }

        const loadPromise = this.loadModalTemplate();
        this.modalLoadPromise = loadPromise;
        try {
            await loadPromise;
        } finally {
            if (this.modalLoadPromise === loadPromise) {
                this.modalLoadPromise = null;
            }
        }
    }

    async loadModalTemplate() {
        // Load modal template from server
        try {
            const response = await fetch('/static/templates/followup_modal.html');
            if (!response.ok) {
                throw new Error(`Failed to load modal template: ${response.status}`);
            }

            const modalHtml = await response.text();
            // bearer:disable javascript_lang_dangerous_insert_html
            // eslint-disable-next-line no-unsanitized/method -- audited 2026-03-28: static template file fetched from app's own static assets
            document.body.insertAdjacentHTML('beforeend', modalHtml);
            this.modalElement = document.getElementById('followUpModal');
            this.attachModalEventHandlers();
            this.addModalStyles();
        } catch (e) {
            SafeLogger.error('Error loading follow-up modal template:', e);
            // Show error message to user
            this.showModalLoadError();
        }
    }

    /**
     * Attach event handlers to modal elements
     */
    attachModalEventHandlers() {
        const startBtn = this.getStartButton();
        // The fetched modal uses the page's registered script, not an attribute.
        if (startBtn) {
            startBtn.addEventListener('click', () => this.submitFollowUp());
        }

        // Clear stale errors when modal is closed
        if (this.modalElement) {
            this.modalElement.addEventListener('hidden.bs.modal', () => {
                window.ui.clearInlineError('followup-error-container');
            });
        }
    }

    getStartButton() {
        return document.getElementById('startFollowUpBtn') ||
            this.modalElement?.querySelector('.modal-footer .btn-primary');
    }

    /**
     * Add modal styles if needed
     */
    addModalStyles() {
        // Add custom CSS if needed
        if (!document.getElementById('followup-modal-styles')) {
            const styles = document.createElement('style');
            styles.id = 'followup-modal-styles';
            styles.nonce = window.LDRTemplateEvents?.styleNonce || '';
            styles.textContent = `
                    .modal-backdrop {
                        position: fixed;
                        top: 0;
                        left: 0;
                        z-index: 1040;
                        width: 100vw;
                        height: 100vh;
                        background-color: rgba(0, 0, 0, 0.5);
                    }
                    #followUpModal {
                        position: fixed;
                        top: 0;
                        left: 0;
                        z-index: 1050;
                        width: 100%;
                        height: 100%;
                        overflow-x: hidden;
                        overflow-y: auto;
                        outline: 0;
                        display: none;
                    }
                    #followUpModal.show {
                        display: flex !important;
                        align-items: center;
                        justify-content: center;
                    }
                    #followUpModal .modal-dialog {
                        position: relative;
                        margin: 1.75rem auto;
                        max-width: 800px;
                    }
                    #followUpModal .modal-content {
                        background: var(--bg-secondary);
                        color: var(--text-primary);
                        border-radius: 0.5rem;
                        box-shadow: var(--card-shadow);
                        border: 1px solid var(--border-color);
                    }
                    #followUpModal .modal-header {
                        border-bottom: 1px solid var(--border-color);
                    }
                    #followUpModal .modal-footer {
                        border-top: 1px solid var(--border-color);
                    }
                    /* Draw the close X in the theme's text color: Bootstrap's
                       icon is black, and inverting it hides it on light
                       themes. Theme the variables so :hover keeps it. */
                    #followUpModal .btn-close {
                        --bs-btn-close-color: var(--text-primary);
                        --bs-btn-close-opacity: 1;
                        --bs-btn-close-hover-opacity: 1;
                        --bs-btn-close-focus-opacity: 1;
                        --bs-btn-close-filter: none;
                        position: relative;
                        background: none;
                        color: var(--bs-btn-close-color);
                        filter: none;
                        opacity: 1;
                    }
                    #followUpModal .btn-close::before,
                    #followUpModal .btn-close::after {
                        content: "";
                        position: absolute;
                        top: 50%;
                        left: 50%;
                        width: 1em;
                        height: 2px;
                        background: currentColor;
                        transform: translate(-50%, -50%) rotate(45deg);
                    }
                    #followUpModal .btn-close::after {
                        transform: translate(-50%, -50%) rotate(-45deg);
                    }
                    @media (forced-colors: active) {
                        #followUpModal .btn-close::before,
                        #followUpModal .btn-close::after {
                            forced-color-adjust: none;
                            background: CanvasText;
                        }
                    }
                    #followUpModal .ldr-form-control,
                    #followUpModal .form-select {
                        background-color: var(--bg-tertiary);
                        color: var(--text-primary);
                        border: 1px solid var(--border-color);
                    }
                    #followUpModal .ldr-form-control:focus,
                    #followUpModal .form-select:focus {
                        background-color: var(--bg-tertiary);
                        color: var(--text-primary);
                        border-color: var(--accent-primary);
                        box-shadow: 0 0 0 0.2rem rgba(var(--accent-primary-rgb), 0.25);
                    }
                    #followUpModal .bg-light {
                        background-color: var(--bg-tertiary) !important;
                    }
                    #followUpModal .text-muted {
                        color: var(--text-muted) !important;
                    }
                    #followUpModal .alert-info {
                        background-color: rgba(var(--accent-tertiary-rgb), 0.1);
                        border-color: rgba(var(--accent-tertiary-rgb), 0.3);
                        color: var(--accent-tertiary);
                    }
            `;
            document.head.appendChild(styles);
        }
    }

    /**
     * Show follow-up modal and load parent context
     */
    async showFollowUpModal() {
        if (!this.modalElement) {
            await this.createModal();
        }

        // Only proceed if modal was successfully created
        if (!this.modalElement) {
            return;
        }

        // Load parent context
        await this.loadParentContext();

        // Show modal
        const modal = new bootstrap.Modal(this.modalElement);
        modal.show();
    }

    /**
     * Show error message when modal template fails to load
     */
    showModalLoadError() {
        const followUpBtn = document.getElementById('ask-followup-btn');
        if (followUpBtn) {
            followUpBtn.disabled = true;
            followUpBtn.title = 'Failed to load follow-up modal template';
        }

        // Show user-friendly error
        alert('Unable to load follow-up interface. Please refresh the page and try again.');
    }

    /**
     * Load parent research context
     */
    async loadParentContext() {
        try {
            // Get CSRF token
            const csrfToken = window.api ? window.api.getCsrfToken() : '';

            const response = await fetch('/api/followup/prepare', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrfToken
                },
                body: JSON.stringify({
                    parent_research_id: this.parentResearchId,
                    question: 'test' // Needs a non-empty question
                })
            });

            const data = await response.json();

            if (data.success) {
                // Display parent context
                document.getElementById('parentContext').style.display = 'block';
                document.getElementById('parentSummary').textContent = data.parent_summary;
                document.getElementById('parentSources').textContent = data.available_sources;
            }
        } catch (error) {
            SafeLogger.error('Error loading parent context:', error);
        }
    }

    /**
     * Submit follow-up research
     */
    async submitFollowUp() {
        window.ui.clearInlineError('followup-error-container');

        const question = document.getElementById('followUpQuestion').value.trim();
        if (!question) {
            window.ui.showInlineError('followup-error-container', 'Please enter a follow-up question');
            return;
        }

        if (!this.parentResearchId) {
            window.ui.showInlineError('followup-error-container', 'No parent research ID available');
            return;
        }

        // A slow /start response used to leave the button active, allowing a
        // rapid double-click to create two independent child researches.
        // Keep ownership on this instance until the request either fails (and
        // can be retried) or succeeds and navigates away.
        if (this.submitInProgress) return;
        this.submitInProgress = true;
        const startBtn = this.getStartButton();
        if (startBtn) startBtn.disabled = true;
        let started = false;

        SafeLogger.log('Submitting follow-up research:', {
            parent_research_id: this.parentResearchId,
            question
        });

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

            // Start follow-up research
            const response = await fetch('/api/followup/start', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrfToken
                },
                body: JSON.stringify({
                    parent_research_id: this.parentResearchId,
                    question
                    // Strategy now comes from database settings
                })
            });

            if (!response.ok) {
                SafeLogger.error('Follow-up API error:', response.status, response.statusText);
                const errorData = await response.json().catch(() => ({}));
                const errorMessage = errorData?.error || errorData?.detail ||
                    errorData?.message || `HTTP error! status: ${response.status}`;
                SafeLogger.error('Response body:', errorMessage);
                throw new Error(errorMessage);
            }

            const data = await response.json();
            SafeLogger.log('Follow-up API response:', data);

            const researchId = data && data.research_id;
            const hasResearchId = (
                (typeof researchId === 'string' && researchId.trim() !== '') ||
                (typeof researchId === 'number' && Number.isFinite(researchId))
            );

            if (data?.success && hasResearchId) {
                // Close modal
                bootstrap.Modal.getInstance(this.modalElement).hide();

                // Redirect to progress page to show the research is running.
                // Single navigation site; no concurrent writers to window.location.
                // Keep the server-generated ID inside one hardcoded /progress/
                // path segment even if a future backend changes its ID format.
                // bearer:disable javascript_lang_open_redirect
                // eslint-disable-next-line require-atomic-updates
                window.location.href = `/progress/${encodeURIComponent(
                    String(researchId).trim()
                )}`;
                started = true;
            } else {
                const message = data?.error || data?.detail || data?.message ||
                    (data?.success
                        ? 'Response did not include a valid research ID'
                        : 'Unknown error');
                window.ui.showInlineError(
                    'followup-error-container',
                    'Error starting follow-up research: ' + message
                );
            }
        } catch (error) {
            SafeLogger.error('Error submitting follow-up:', error);
            window.ui.showInlineError('followup-error-container', 'Failed to start follow-up research: ' + error.message);
        } finally {
            if (!started) {
                this.submitInProgress = false;
                if (startBtn) startBtn.disabled = false;
            }
        }
    }
}

// Initialize on page load
const followUpResearch = new FollowUpResearch();
document.addEventListener('DOMContentLoaded', () => {
    followUpResearch.init();
});

// Helper function for toggling advanced options
function toggleAdvancedOptions(event) {
    event.preventDefault();
    const panel = document.getElementById('advancedOptionsPanel');
    panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
}

// Exposed on window so vitest can exercise getResearchIdFromPage
// (and other future helpers) without spinning up the full followup modal.
window.FollowUpResearch = FollowUpResearch;
// Keep the singleton available to page integrations as well as its listeners.
window.followUpResearch = followUpResearch;