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.

50.0 KB
Raw Blame
{% extends "base.html" %}
{% from "components/custom_dropdown.html" import render_dropdown %}

{% block title %}{{ 'Edit' if subscription else 'Create' }} News Subscription - LDR{% endblock %}

{% block extra_head %}
<link rel="stylesheet" href="/static/css/custom_dropdown.css">
<link rel="stylesheet" href="/static/css/news.css">
<link rel="stylesheet" href="/static/css/subscription_form.css">
{% endblock %}

{% block content %}
<div class="ldr-subscription-form-container">
    <div class="ldr-page-header">
        <h1>
            <i aria-hidden="true" class="bi bi-bell-fill"></i>
            {{ 'Edit' if subscription else 'Create' }} News Subscription
        </h1>
    </div>

    <!-- Alert Container -->
    <div id="subscription-alert" class="ldr-settings-alert-container" role="alert"></div>

    <form id="subscription-form" class="ldr-form-card">
        <!-- Basic Information Section -->
        <div class="ldr-form-section">
            <h2 class="ldr-section-title">
                <i aria-hidden="true" class="bi bi-info-circle"></i> Basic Information
            </h2>

            <div class="mb-3">
                <label for="subscription-query" class="ldr-form-label">Search Query or Topic</label>
                <textarea class="form-control" id="subscription-query" rows="4" required
                          placeholder="e.g., AI breakthroughs in healthcare, climate change impacts on agriculture, latest cryptocurrency regulations">{% if subscription %}{{ subscription.query_or_topic }}{% endif %}</textarea>
                <div class="ldr-form-text">
                    Enter keywords, topics, or detailed search queries. You can use natural language or specific terms.
                    Use YYYY-MM-DD for dynamic date replacement.
                </div>
            </div>

            <div class="mb-3">
                <label for="subscription-name" class="ldr-form-label">Subscription Name</label>
                <input type="text" class="form-control" id="subscription-name"
                       placeholder="e.g., AI Healthcare News, Climate Agriculture Updates"
                       {% if subscription %}value="{{ subscription.name or '' }}"{% endif %}>
                <div class="ldr-form-text">Optional - give your subscription a memorable name</div>
            </div>

            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="subscription-interval" class="ldr-form-label">Update Frequency (minutes)</label>
                    <input type="number" class="form-control" id="subscription-interval"
                           min="1" step="1" value="{% if subscription %}{{ subscription.refresh_interval_minutes|int if subscription.refresh_interval_minutes else 1440 }}{% else %}1440{% endif %}" required>
                    <div class="ldr-form-text">
                        Common values: 1 (every minute), 60 (hourly), 1440 (daily), 10080 (weekly)
                        <br>
                        <small id="subscription-jitter-info" class="text-muted">A random jitter will be added to prevent all subscriptions from running at once</small>
                    </div>
                </div>

                <div class="col-md-6 mb-3">
                    <label for="subscription-folder" class="ldr-form-label">Folder</label>
                    <select class="form-select" id="subscription-folder">
                        <option value="">Uncategorized</option>
                        <!-- Folders will be loaded dynamically -->
                    </select>
                </div>
            </div>
        </div>

        <!-- Model Configuration Section -->
        <div class="ldr-form-section">
            <h2 class="ldr-section-title">
                <i aria-hidden="true" class="bi bi-cpu"></i> Model Configuration
            </h2>

            <div class="mb-3">
                <label for="subscription-provider" class="ldr-form-label">Model Provider</label>
                <select class="form-select" id="subscription-provider">
                    <option value="">Loading providers...</option>
                </select>
                <div class="ldr-form-text">Select the LLM provider to use</div>
            </div>

            <div class="mb-3" id="custom-endpoint-container" style="display: none;">
                <label for="subscription-custom-endpoint" class="ldr-form-label">Custom Endpoint</label>
                <input type="url" class="form-control" id="subscription-custom-endpoint"
                       placeholder="https://api.example.com/v1"
                       value="{% if subscription and subscription.custom_endpoint %}{{ subscription.custom_endpoint }}{% else %}{{ default_settings.custom_endpoint }}{% endif %}">
                <div class="ldr-form-text">Enter the OpenAI-compatible API endpoint URL</div>
            </div>

            <div class="mb-3">
                {{ render_dropdown(
                    input_id="subscription-model",
                    dropdown_id="subscription-model-dropdown",
                    placeholder="Enter or select a model",
                    label="Language Model",
                    help_text="Select the AI model to use for this subscription (leave empty for default)",
                    show_refresh=True,
                    data_initial_value=(subscription.model if subscription else '')
                ) }}
                <div class="ldr-form-text">
                    Not sure which model to use? Compare community results on the
                    <a href="https://huggingface.co/datasets/local-deep-research/ldr-benchmarks" target="_blank" rel="noopener noreferrer">LDR benchmarks dataset</a>.
                </div>
            </div>

            <div class="mb-3">
                {{ render_dropdown(
                    input_id="subscription-search-engine",
                    dropdown_id="subscription-search-engine-dropdown",
                    placeholder="Select the search engine to use",
                    label="Search Engine",
                    help_text="Select the search engine to use for research",
                    data_initial_value=(subscription.search_engine if subscription else default_settings.search_engine)
                ) }}
            </div>

            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="subscription-iterations" class="ldr-form-label">Search Iterations</label>
                    <input type="number" class="form-control" id="subscription-iterations"
                           min="1" max="10" value="{{ subscription.search_iterations if subscription else default_settings.iterations }}">
                    <div class="ldr-form-text">Number of research cycles to perform</div>
                </div>

                <div class="col-md-6 mb-3">
                    <label for="subscription-questions" class="ldr-form-label">Questions Per Iteration</label>
                    <input type="number" class="form-control" id="subscription-questions"
                           min="1" max="20" value="{{ subscription.questions_per_iteration if subscription else default_settings.questions_per_iteration }}">
                    <div class="ldr-form-text">Follow-up questions in each cycle</div>
                </div>
            </div>

            <div class="mb-3">
                <label for="subscription-strategy" class="ldr-form-label">Search Strategy</label>
                <select class="form-select" id="subscription-strategy">
                    {% for s in strategies %}
                    <option value="{{ s.name }}" {% if (subscription and subscription.search_strategy == s.name) or (not subscription and default_settings.search_strategy == s.name) %}selected{% endif %}>{{ s.label }}</option>
                    {% endfor %}
                </select>
                <div class="ldr-form-text">Choose the search strategy that best fits your needs</div>
            </div>
        </div>

        <!-- Status Section -->
        <div class="ldr-form-section">
            <h2 class="ldr-section-title">
                <i aria-hidden="true" class="bi bi-toggle-on"></i> Status & Options
            </h2>

            <div class="form-check mb-3">
                <input class="form-check-input" type="checkbox" id="subscription-active"
                       {% if not subscription or subscription.is_active %}checked{% endif %}>
                <label class="form-check-label" for="subscription-active">
                    Active (subscription will run automatically)
                </label>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="ldr-btn-group-actions">
            <a href="/news" class="btn btn-secondary">
                <i aria-hidden="true" class="bi bi-arrow-left"></i> Cancel
            </a>
            <button type="button" class="btn btn-info" id="test-subscription-btn">
                <i aria-hidden="true" class="bi bi-play-circle"></i> Test Run
            </button>
            {% if not subscription %}
            <button type="button" class="btn btn-success" id="create-and-run-btn">
                <i aria-hidden="true" class="bi bi-rocket-takeoff"></i> Create & Run Now
            </button>
            {% endif %}
            <button type="submit" class="btn btn-primary">
                <i aria-hidden="true" class="bi bi-save"></i> {{ 'Update' if subscription else 'Create' }} Subscription
            </button>
        </div>
    </form>
</div>

<script defer src="/static/js/components/custom_dropdown.js"></script>
<script nonce="{{ csp_nonce }}">
// Global variables
let currentProvider = {{ (subscription.model_provider if subscription else default_settings.model_provider) | tojson }};
let defaultModel = {{ (subscription.model if subscription else default_settings.model) | tojson }};
let defaultSearchEngine = {{ (subscription.search_engine if subscription else default_settings.search_engine) | tojson }};
let defaultCustomEndpoint = {{ (subscription.custom_endpoint if subscription else default_settings.custom_endpoint) | tojson }};
let modelOptions = [];
let modelDropdownInstance = null;
let searchEngineOptions = [];
let searchEngineDropdownInstance = null;
let subscriptionActionInFlight = false;
let subscriptionNavigationPending = false;

function isValidResearchId(researchId) {
    return (typeof researchId === 'string' && researchId.trim() !== '') ||
        (typeof researchId === 'number' && Number.isFinite(researchId));
}

function scheduleSubscriptionRedirect(url) {
    subscriptionNavigationPending = true;
    setTimeout(() => {
        subscriptionNavigationPending = false;
        subscriptionActionInFlight = false;
        window.location.href = url;
    }, 1500);
}

// Debug: Log initial values from server
console.log('Initial values from server:', {
    currentProvider: currentProvider,
    defaultModel: defaultModel,
    defaultSearchEngine: defaultSearchEngine,
    defaultCustomEndpoint: defaultCustomEndpoint
});

// Get model options function for dropdown
function getModelOptions() {
    return modelOptions;
}

// Get search engine options function for dropdown
function getSearchEngineOptions() {
    return searchEngineOptions;
}

// Initialize dropdowns
function initializeDropdowns() {
    console.log('Initializing dropdowns...');
    console.log('setupCustomDropdown available?', typeof setupCustomDropdown);
    console.log('Default values - Model:', defaultModel, 'Search Engine:', defaultSearchEngine, 'Provider:', currentProvider);
    console.log('Available search engines:', searchEngineOptions);

    if (typeof setupCustomDropdown !== 'undefined') {
        // Model dropdown
        const modelInput = document.getElementById('subscription-model');
        const modelDropdownList = document.getElementById('subscription-model-dropdown-list');

        if (modelInput && modelDropdownList) {
            console.log('Initializing model dropdown');
            modelDropdownInstance = setupCustomDropdown(
                modelInput,
                modelDropdownList,
                getModelOptions,
                function(value, item) {
                    console.log('Model selected:', value);
                },
                true,  // allowCustomValues
                'No models available'
            );
            console.log('Model dropdown instance created:', modelDropdownInstance);

            // Set initial value if available
            if (defaultModel && modelDropdownInstance.setValue) {
                console.log('Setting initial model value:', defaultModel);
                modelDropdownInstance.setValue(defaultModel, false);
            }
        } else {
            console.error('Model dropdown elements not found');
        }

        // Search engine dropdown
        const searchEngineInput = document.getElementById('subscription-search-engine');
        const searchEngineDropdownList = document.getElementById('subscription-search-engine-dropdown-list');

        if (searchEngineInput && searchEngineDropdownList) {
            console.log('Initializing search engine dropdown');
            searchEngineDropdownInstance = setupCustomDropdown(
                searchEngineInput,
                searchEngineDropdownList,
                getSearchEngineOptions,
                function(value, item) {
                    console.log('Search engine selected:', value);
                },
                false,  // don't allow custom values
                'No search engines available'
            );
            console.log('Search engine dropdown instance created:', searchEngineDropdownInstance);

            // Set initial value if available
            if (defaultSearchEngine && searchEngineDropdownInstance.setValue) {
                console.log('Setting initial search engine value:', defaultSearchEngine);
                // setValue matches exact-first, then case-insensitively
                searchEngineDropdownInstance.setValue(defaultSearchEngine, false);
            }
        } else {
            console.error('Search engine dropdown elements not found');
        }
    } else {
        console.error('setupCustomDropdown is not available');
        // Try again in a bit
        setTimeout(initializeDropdowns, 500);
    }
}

// Load search engines
async function loadSearchEngines() {
    try {
        // Issue #5204: ask the endpoint for the scope-aware variant
        // of the engine list when the user has a saved egress scope.
        // The news-subscription form has no per-form scope selector,
        // so the filter follows the user's saved setting — picking an
        // engine that conflicts with it is impossible by default, and
        // the subscribe-time backend check stays as the second backstop.
        const scope = {{ (default_settings.egress_scope or "adaptive") | tojson }};
        const primary = {{ (subscription.search_engine if subscription else default_settings.search_engine) | tojson }};
        const filterScope = (scope && scope !== 'unprotected') ? scope : null;
        let url = '/settings/api/available-search-engines';
        if (filterScope) {
            const parts = [`egress_scope=${encodeURIComponent(filterScope)}`];
            if (primary) parts.push(`primary=${encodeURIComponent(primary)}`);
            url += '?' + parts.join('&');
        }

        const response = await fetch(url, {
            credentials: 'same-origin'
        });
        const data = await response.json();

        if (data.engine_options) {
            // Map the egress annotation onto the disabled contract
            // the custom dropdown already understands (same contract
            // the research.js loader uses). An option without an egress
            // field is left enabled. Note that a denial can arrive even
            // on an unprotected / no-scope response: the guarded
            // engine-URL overlay is scope-independent, so it stamps
            // `private_url_unapproved` on every variant of the payload.
            searchEngineOptions = data.engine_options.map((engine) => {
                const egress = engine.egress;
                const isDenied = !!egress && egress.allowed === false;
                const display = engine.display_name || engine.label || engine.value || 'engine';
                let disabledReason = null;
                if (isDenied && egress) {
                    switch (egress.reason) {
                        case 'scope_mismatch_private_only':
                            disabledReason = 'Blocked: not a local source under Private only';
                            break;
                        case 'scope_mismatch_public_only':
                            disabledReason = 'Blocked: local source under Public only';
                            break;
                        case 'strict_not_primary':
                            disabledReason = 'Blocked: only the primary search engine is allowed under Strict';
                            break;
                        case 'unclassified':
                        case 'engine_unknown':
                            disabledReason = `Blocked: ${display} is not recognized by the egress policy`;
                            break;
                        case 'engine_denied':
                            disabledReason = `Blocked: ${display} is denied by the egress policy`;
                            break;
                        case 'private_url_unapproved':
                            // Same wording as research.js. Deliberately not
                            // "see the warning banner": that banner is
                            // suppressed once dismissed, and it comes from
                            // the same DNS-free check as this overlay, so it
                            // stays silent on exactly the URLs the overlay
                            // misses. Name the operator-side remedy rather
                            // than the egress policy, which did not deny it.
                            disabledReason = `Disabled: ${display}'s private instance URL needs server-operator approval (env-only: allow private IPs, add the origin to search.private_engine_url_allowlist, or env-lock the engine's URL setting)`;
                            break;
                        default:
                            disabledReason = `Blocked by egress policy (${egress.reason})`;
                            break;
                    }
                }
                return {
                    ...engine,
                    disabled: isDenied,
                    disabled_reason: disabledReason,
                };
            });

            // Update dropdown if it exists
            if (window.updateDropdownOptions) {
                const searchEngineInput = document.getElementById('subscription-search-engine');
                window.updateDropdownOptions(searchEngineInput, searchEngineOptions);
            }
        }
    } catch (error) {
        console.error('Error loading search engines:', error);
        searchEngineOptions = [{ value: 'searxng', label: 'SearXNG' }];
    }
}

// Load models for a specific provider
async function loadModelsForProvider(provider) {
    console.log('Loading models for provider:', provider);

    try {
        // Fetch available models
        const response = await fetch('/settings/api/available-models', {
            method: 'POST',
            credentials: 'same-origin',
            headers: { 'X-CSRFToken': getCSRFToken() }
        });
        const data = await response.json();

        if (data.providers) {
            // Get models for the selected provider
            const providerKey = `${provider.toLowerCase()}_models`;
            const models = data.providers[providerKey] || [];

            console.log('Available providers:', Object.keys(data.providers));
            console.log(`Looking for key: ${providerKey}`);
            console.log(`Found ${models.length} models for ${provider}`);

            // Update model options
            modelOptions = models.length > 0 ? models : [{ value: '', label: 'No models available' }];
            console.log('Model options for provider', provider, ':', modelOptions);

            // Update dropdown if it exists
            if (window.updateDropdownOptions) {
                const modelInput = document.getElementById('subscription-model');
                window.updateDropdownOptions(modelInput, modelOptions);

                // After updating options, restore the default model value if it matches the provider
                if (modelDropdownInstance && defaultModel) {
                    // Check if the default model exists in the new options
                    const modelExists = modelOptions.some(m => m.value === defaultModel);
                    if (modelExists) {
                        console.log('Restoring model value after provider change:', defaultModel);
                        modelDropdownInstance.setValue(defaultModel, false);
                    }
                }
            }
        }
    } catch (error) {
        console.error('Error loading models:', error);
        modelOptions = [{ value: '', label: 'Error loading models' }];

        // Update dropdown with error state
        if (window.updateDropdownOptions) {
            const modelInput = document.getElementById('subscription-model');
            window.updateDropdownOptions(modelInput, modelOptions);
        }
    }
}

// Load providers
async function loadProviders() {
    const providerSelect = document.getElementById('subscription-provider');

    try {
        const response = await fetch('/settings/api/available-models', {
            method: 'POST',
            credentials: 'same-origin',
            headers: { 'X-CSRFToken': getCSRFToken() }
        });
        const data = await response.json();

        if (data.provider_options) {
            providerSelect.innerHTML = '<option value="">Select a provider</option>';

            data.provider_options.forEach(provider => {
                const option = document.createElement('option');
                option.value = provider.value;
                // The endpoint advertises every provider and marks the ones
                // the egress policy blocks, rather than omitting them, so a
                // configured cloud key is still visible as such. Render that
                // state here too — otherwise a blocked provider looks
                // perfectly selectable and the subscription is rejected at
                // creation time with no hint as to why.
                const isDisabled = provider.disabled === true;
                option.disabled = isDisabled;
                option.textContent = isDisabled && provider.disabled_reason
                    ? `${provider.label} — ${provider.disabled_reason}`
                    : provider.label;
                // Handle case-insensitive comparison for provider names
                option.selected = !isDisabled && (
                    provider.value.toUpperCase() === (currentProvider || '').toUpperCase() ||
                    (!currentProvider && provider.default)
                );
                providerSelect.appendChild(option);
            });

            // Add change handler
            providerSelect.addEventListener('change', async (e) => {
                currentProvider = e.target.value;

                // Show/hide custom endpoint field
                const customEndpointContainer = document.getElementById('custom-endpoint-container');
                if (currentProvider.toUpperCase() === 'OPENAI_ENDPOINT' ||
                    currentProvider === 'custom' ||
                    currentProvider === 'openai_compatible') {
                    customEndpointContainer.style.display = 'block';
                } else {
                    customEndpointContainer.style.display = 'none';
                }

                // Reload models for new provider
                await loadModelsForProvider(currentProvider);
            });

            // Load models for initial provider
            if (currentProvider || data.provider_options.some(p => p.default)) {
                const initialProvider = currentProvider || data.provider_options.find(p => p.default)?.value;
                if (initialProvider) {
                    // Check if we need to show custom endpoint field on load
                    const customEndpointContainer = document.getElementById('custom-endpoint-container');
                    if (initialProvider.toUpperCase() === 'OPENAI_ENDPOINT' ||
                        initialProvider === 'custom' ||
                        initialProvider === 'openai_compatible') {
                        customEndpointContainer.style.display = 'block';
                    }

                    await loadModelsForProvider(initialProvider);
                }
            }

            // Set default selected value for provider. `select.value = x`
            // happily selects a disabled <option>, which would undo the
            // guarded selection the forEach loop above already made and
            // resubmit a policy-blocked provider on the edit path — the
            // same footgun applyEvaluationProvider() guards against in
            // benchmark.html. The create path also compares a lowercase
            // `llm.provider` default against uppercase option values, so
            // match case-insensitively instead of wiping the selection on
            // a case mismatch.
            if (currentProvider) {
                const match = Array.from(providerSelect.options).find(
                    opt => opt.value.toUpperCase() === currentProvider.toUpperCase()
                );
                if (match && !match.disabled) {
                    providerSelect.value = match.value;
                    currentProvider = match.value;
                } else if (match && match.disabled) {
                    console.log('Subscription provider blocked by egress policy:', currentProvider);
                }
                // No match at all: leave the selection the forEach loop
                // above already established rather than clearing it.
            }
        }
    } catch (error) {
        console.error('Error loading providers:', error);
        providerSelect.innerHTML = '<option value="">Error loading providers</option>';
    }
}

// Initialize page
document.addEventListener('DOMContentLoaded', async function() {
    console.log('DOMContentLoaded fired for subscription form');
    console.log('setupCustomDropdown available?', typeof setupCustomDropdown);
    console.log('window.setupCustomDropdown available?', typeof window.setupCustomDropdown);

    // Log subscription data if editing
    {% if subscription %}
    console.log('Editing subscription - Search Engine:', '{{ subscription.search_engine }}');
    console.log('Full subscription data:', {{ subscription | tojson }});
    {% endif %}

    try {
        // Initialize interval for existing subscription
        {% if subscription and subscription.refresh_interval_minutes %}
        // Already handled in the input value attribute
        {% endif %}

        // Load jitter info
        loadJitterInfo();
        // Initialize dropdowns after a short delay to ensure DOM is ready
        setTimeout(() => {
            initializeDropdowns();
        }, 100);

    // Load providers, models, and search engines
    await loadProviders();
    await loadSearchEngines();

    // Re-initialize dropdowns with loaded options
    setTimeout(() => {
        console.log('Re-initializing dropdowns with loaded data');
        initializeDropdowns();

        // After reinitializing, set the default values again
        // This ensures the user's saved settings are properly displayed
        if (modelDropdownInstance && defaultModel) {
            console.log('Restoring model value after reinitialization:', defaultModel);
            modelDropdownInstance.setValue(defaultModel, false);
        }

        if (searchEngineDropdownInstance && defaultSearchEngine) {
            console.log('Restoring search engine value after reinitialization:', defaultSearchEngine);
            searchEngineDropdownInstance.setValue(defaultSearchEngine, false);
        }
    }, 500);

    // Load folders
    loadSubscriptionFolders();

    // Handle form submission
    document.getElementById('subscription-form').addEventListener('submit', handleSubscriptionSubmit);

    // Handle test run
    const testBtn = document.getElementById('test-subscription-btn');
    if (testBtn) {
        console.log('Adding click handler to test button');
        testBtn.addEventListener('click', handleTestRun);
    } else {
        console.error('Test button not found!');
    }

    // Handle create and run button
    const createAndRunBtn = document.getElementById('create-and-run-btn');
    if (createAndRunBtn) {
        console.log('Adding click handler to create and run button');
        createAndRunBtn.addEventListener('click', handleCreateAndRun);
    }

    // Handle model refresh button
    const modelRefreshBtn = document.querySelector('.ldr-custom-dropdown-with-refresh .ldr-custom-dropdown-refresh-btn');
    if (modelRefreshBtn) {
        modelRefreshBtn.addEventListener('click', async function(e) {
            e.preventDefault();
            e.stopPropagation();

            // Add loading class
            modelRefreshBtn.classList.add('ldr-loading');

            try {
                // Reload models for current provider
                if (currentProvider) {
                    await loadModelsForProvider(currentProvider);
                }

                // Remove loading class
                modelRefreshBtn.classList.remove('ldr-loading');

                // Click the input to show refreshed options
                const modelInput = document.getElementById('subscription-model');
                if (modelInput) {
                    modelInput.focus();
                    modelInput.click();
                }
            } catch (error) {
                console.error('Error refreshing models:', error);
                modelRefreshBtn.classList.remove('ldr-loading');
            }
        });
    }

    // Handle URL parameters for prefilling
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.has('query')) {
        document.getElementById('subscription-query').value = urlParams.get('query');
    }
    if (urlParams.has('name')) {
        document.getElementById('subscription-name').value = urlParams.get('name');
    }
    // Store source_id if provided (from history page)
    if (urlParams.has('source_id')) {
        window.sourceResearchId = urlParams.get('source_id');
    }

    console.log('Subscription form initialization complete');
    } catch (error) {
        console.error('Error initializing subscription form:', error);
        showAlert('Error initializing form: ' + error.message, 'error');
    }
});

// Load subscription folders
async function loadSubscriptionFolders() {
    try {
        // Canonical route is /news/api/subscription/folders (the router
        // mounts /news/api and the function lives at /subscription/folders).
        // Earlier /news/api/folders was a Flask-era guess that 404'd, so
        // the folder dropdown silently stayed empty.
        const response = await fetch('/news/api/subscription/folders', {
            credentials: 'same-origin'
        });
        if (response.ok) {
            const data = await response.json();
            const folders = Array.isArray(data) ? data : (data.folders || []);
            const select = document.getElementById('subscription-folder');

            // Clear existing options except first
            while (select.options.length > 1) {
                select.remove(1);
            }

            // Add folders
            folders.forEach(folder => {
                const option = document.createElement('option');
                option.value = folder.id;
                option.textContent = folder.name;
                select.appendChild(option);
            });

            // Set selected folder if editing
            {% if subscription and subscription.folder_id %}
            select.value = "{{ subscription.folder_id }}";
            {% endif %}
        } else {
            console.error('Failed to load folders:', response.status, response.statusText);
        }
    } catch (error) {
        console.error('Error loading folders:', error);
    }
}

// Handle form submission
async function handleSubscriptionSubmit(e) {
    e.preventDefault();

    const query = document.getElementById('subscription-query').value;
    const name = document.getElementById('subscription-name').value || query.substring(0, 50);
    const intervalMinutes = parseInt(document.getElementById('subscription-interval').value);
    const folder = document.getElementById('subscription-folder').value;
    const isActive = document.getElementById('subscription-active').checked;

    // Model configuration
    const modelHidden = document.getElementById('subscription-model_hidden');
    const model = modelHidden ? modelHidden.value : '';
    const provider = document.getElementById('subscription-provider').value || currentProvider || '';
    const customEndpoint = document.getElementById('subscription-custom-endpoint').value;
    if (model && model.includes(':')) {
        const parts = model.split(':');
        modelProvider = parts[0];
    }

    // Search configuration
    const searchEngineHidden = document.getElementById('subscription-search-engine_hidden');
    const searchEngineInput = document.getElementById('subscription-search-engine');
    // Try hidden field first, then input field
    const searchEngine = (searchEngineHidden && searchEngineHidden.value) ? searchEngineHidden.value :
                        (searchEngineInput && searchEngineInput.value) ? searchEngineInput.value : null;

    // Check if search engine was selected
    if (!searchEngine) {
        showAlert('Please select a search engine', 'warning');
        return;
    }

    const iterations = document.getElementById('subscription-iterations').value;
    const questionsPerIteration = document.getElementById('subscription-questions').value;
    const strategy = document.getElementById('subscription-strategy').value;

    if (subscriptionActionInFlight) {
        return;
    }
    subscriptionActionInFlight = true;

    try {
        const url = {% if subscription %}'/news/api/subscriptions/{{ subscription.id }}'{% else %}'/news/api/subscribe'{% endif %};
        const method = {% if subscription %}'PUT'{% else %}'POST'{% endif %};

        const response = await fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCSRFToken()
            },
            body: JSON.stringify({
                user_id: localStorage.getItem('userId') || 'anonymous',
                query: query,
                name: name,
                subscription_type: 'search',
                refresh_minutes: intervalMinutes, // Convert minutes to hours (can be fractional)
                folder_id: folder || null,
                is_active: isActive,
                model_provider: provider,
                model: model,
                custom_endpoint: customEndpoint || null,
                search_engine: searchEngine,
                search_iterations: parseInt(iterations),
                questions_per_iteration: parseInt(questionsPerIteration),
                search_strategy: strategy,
                source_id: window.sourceResearchId || null
            })
        });

        if (response.ok) {
            const data = await response.json();
            showAlert('Subscription {{ "updated" if subscription else "created" }} successfully!', 'success');

            // Redirect to appropriate page after a short delay
            {% if subscription %}
            // Editing - go back to subscriptions page
            scheduleSubscriptionRedirect('/news/subscriptions');
            {% else %}
            // Creating - go to news feed
            scheduleSubscriptionRedirect('/news');
            {% endif %}
        } else {
            const error = await response.json();
            showAlert('Error: ' + (error.error || 'Failed to save subscription'), 'error');
        }
    } catch (error) {
        showAlert('Error: ' + error.message, 'error');
    } finally {
        if (!subscriptionNavigationPending) {
            subscriptionActionInFlight = false;
        }
    }
}

// A subscription saved from the news page before #7860 can hold the whole
// "PROVIDER:model" selection as its model, with the first segment as its
// provider. Resolve it the way scheduled runs do (resolve_subscription_model
// in news/subscription_runner.py). The news page's model field is free text,
// so this is a heuristic: a first segment that is exactly an uppercase
// built-in provider key, the form the dropdown's options use, is stripped;
// any other first segment naming the provider is a typed model tag, which
// runs whole on the default provider.
function resolveSavedSubscriptionModel(provider, model) {
    // The same keys as knownProviders in news.js (a test pins both to the
    // registry), so this works before the provider list has loaded.
    const knownProviders = new Set([
        'ANTHROPIC', 'ANTHROPIC_ENDPOINT', 'ATLASCLOUD', 'DEEPSEEK', 'GOOGLE',
        'IONOS', 'LLAMACPP', 'LMSTUDIO', 'OLLAMA', 'OPENAI', 'OPENAI_ENDPOINT',
        'OPENROUTER', 'ORCAROUTER', 'QWEN', 'REQUESTY', 'XAI',
    ]);
    // resolve_subscription_model keeps a provider only when it names a
    // built-in provider key (compared after trimming, as it strips the
    // saved value first). Any other provider is not a provider choice and
    // is dropped, so the run falls back to the user's default provider
    // with the model kept whole.
    if (provider && !knownProviders.has(provider.trim().toUpperCase())) {
        provider = '';
    }
    const separator = model.indexOf(':');
    const head = model.slice(0, separator);
    if (!provider || separator <= 0 || head.toUpperCase() !== provider.toUpperCase()) {
        return { provider, model };
    }
    if (knownProviders.has(head)) {
        return { provider, model: model.slice(separator + 1) };
    }
    return { provider: '', model };
}

// Handle test run
async function handleTestRun(event, actionAlreadyOwned = false) {
    if (event) {
        event.preventDefault();
        event.stopPropagation();
    }

    console.log('Test Run button clicked');

    let ownsSubscriptionAction = false;
    try {
        const query = document.getElementById('subscription-query').value;
        console.log('Query value:', query);
        if (!query) {
            showAlert('Please enter a query first', 'warning');
            return;
        }

    // Collect all configuration
    const modelHidden = document.getElementById('subscription-model_hidden');
    const { provider, model } = resolveSavedSubscriptionModel(
        document.getElementById('subscription-provider').value || currentProvider || '',
        modelHidden ? modelHidden.value : '',
    );
    const customEndpoint = document.getElementById('subscription-custom-endpoint').value;
    const searchEngineHidden = document.getElementById('subscription-search-engine_hidden');
    const searchEngineInput = document.getElementById('subscription-search-engine');
    // Try hidden field first, then input field
    let searchEngine = (searchEngineHidden && searchEngineHidden.value) ? searchEngineHidden.value :
                      (searchEngineInput && searchEngineInput.value) ? searchEngineInput.value : null;

    // Check if search engine was selected
    if (!searchEngine) {
        showAlert('Please select a search engine', 'warning');
        return;
    }

    if (!actionAlreadyOwned) {
        if (subscriptionActionInFlight) {
            return;
        }
        subscriptionActionInFlight = true;
        ownsSubscriptionAction = true;
    }

    const iterations = document.getElementById('subscription-iterations').value;
    const questions = document.getElementById('subscription-questions').value;
    const strategy = document.getElementById('subscription-strategy').value || 'source-based';

    console.log('Query length:', query.length);
    console.log('Search engine hidden field value:', searchEngineHidden ? searchEngineHidden.value : 'field not found');
    console.log('Search engine input field value:', searchEngineInput ? searchEngineInput.value : 'field not found');
    console.log('Search engine being used:', searchEngine);

    // Show loading state
    showAlert('Starting test run...', 'info');

    try {
        // Prepare the request data
        const requestData = {
            query: query,
            mode: 'quick',
            strategy: strategy,
            metadata: {
                is_news_search: true,
                search_type: 'news_analysis',
                display_in: 'news_feed',
                triggered_by: 'subscription_test_run'
            }
        };

        // Add optional parameters
        if (provider) requestData.model_provider = provider;
        if (model) requestData.model = model;
        if (customEndpoint) requestData.custom_endpoint = customEndpoint;
        // searchEngine is required now, we already checked it's not null
        requestData.search_engine = searchEngine;
        if (iterations) requestData.iterations = parseInt(iterations);
        if (questions) requestData.questions_per_iteration = parseInt(questions);

        console.log('Sending research request:', requestData);

        // POST directly to the research API
        const response = await fetch('/api/start_research', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCSRFToken()
            },
            body: JSON.stringify(requestData)
        });

        console.log('Research API response status:', response.status);

        if (!response.ok) {
            let errorMessage = 'Error starting research';
            try {
                const errorData = await response.json();
                errorMessage = errorData.error || errorData.message || errorMessage;
            } catch (e) {
                errorMessage = `${errorMessage}: ${response.statusText}`;
            }

            if (response.status === 401) {
                showAlert('Please log in to test subscriptions. Redirecting to login...', 'error');
                setTimeout(() => {
                    window.location.href = '/auth/login?next=' + encodeURIComponent(window.location.href);
                }, 2000);
                return;
            }

            showAlert(errorMessage, 'error');
            return;
        }

        const data = await response.json();
        console.log('Research started:', data);

        if (['success', 'queued'].includes(data.status) &&
            isValidResearchId(data.research_id)) {
            showAlert('Research started successfully! Redirecting to news page...', 'success');

            // Store the research ID and query so the news page can track it
            sessionStorage.setItem('activeTestRunResearchId', data.research_id);
            sessionStorage.setItem('activeTestRunQuery', query);

            // Redirect to news page after a short delay
            scheduleSubscriptionRedirect('/news');
        } else {
            showAlert('Unexpected response from server', 'error');
        }

    } catch (error) {
        console.error('Error starting test run:', error);
        showAlert('Error: ' + error.message, 'error');
    }
    } catch (outerError) {
        console.error('Error in handleTestRun:', outerError);
        showAlert('An unexpected error occurred', 'error');
    } finally {
        if (ownsSubscriptionAction && !subscriptionNavigationPending) {
            subscriptionActionInFlight = false;
        }
    }
}

// Handle create and run button click
async function handleCreateAndRun(event) {
    if (event) {
        event.preventDefault();
        event.stopPropagation();
    }

    console.log('Create and Run button clicked');

    if (subscriptionActionInFlight) {
        return;
    }
    subscriptionActionInFlight = true;

    try {
        // First create the subscription
        const query = document.getElementById('subscription-query').value;
        const name = document.getElementById('subscription-name').value || query.substring(0, 50);
        const intervalMinutes = parseInt(document.getElementById('subscription-interval').value);
        const folder = document.getElementById('subscription-folder').value;
        const isActive = document.getElementById('subscription-active').checked;

        // Model configuration
        const modelHidden = document.getElementById('subscription-model_hidden');
        const model = modelHidden ? modelHidden.value : '';
        const provider = document.getElementById('subscription-provider').value || currentProvider || '';
        const customEndpoint = document.getElementById('subscription-custom-endpoint').value;

        // Search configuration
        const searchEngineHidden = document.getElementById('subscription-search-engine_hidden');
        const searchEngine = searchEngineHidden ? searchEngineHidden.value : 'searxng';
        const iterations = document.getElementById('subscription-iterations').value;
        const questionsPerIteration = document.getElementById('subscription-questions').value;
        const strategy = document.getElementById('subscription-strategy').value;

        // Show loading state
        showAlert('Creating subscription and starting research...', 'info');

        // Create subscription
        const createResponse = await fetch('/news/api/subscribe', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCSRFToken()
            },
            body: JSON.stringify({
                user_id: localStorage.getItem('userId') || 'anonymous',
                query: query,
                name: name,
                subscription_type: 'search',
                refresh_minutes: intervalMinutes,
                folder_id: folder || null,
                is_active: isActive,
                model_provider: provider,
                model: model,
                custom_endpoint: customEndpoint || null,
                search_engine: searchEngine,
                search_iterations: parseInt(iterations),
                questions_per_iteration: parseInt(questionsPerIteration),
                search_strategy: strategy,
                source_id: window.sourceResearchId || null
            })
        });

        if (!createResponse.ok) {
            const error = await createResponse.json();
            showAlert('Error: ' + (error.error || 'Failed to create subscription'), 'error');
            return;
        }

        const createData = await createResponse.json();
        console.log('Subscription created:', createData);
        console.log('Full response data:', JSON.stringify(createData, null, 2));

        // Now run the subscription using the test run functionality
        console.log('Subscription created, now starting immediate research run');
        await handleTestRun(undefined, true);

    } catch (error) {
        console.error('Error in create and run:', error);
        showAlert('Error: ' + error.message, 'error');
    } finally {
        if (!subscriptionNavigationPending) {
            subscriptionActionInFlight = false;
        }
    }
}

// Show alert
function showAlert(message, type) {
    const alertContainer = document.getElementById('subscription-alert');
    alertContainer.innerHTML = `
        <div class="alert alert-${window.escapeHtml(type === 'error' ? 'danger' : type)} alert-dismissible fade show" role="alert">
            ${window.escapeHtml(message)}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    alertContainer.style.display = 'block';
}

// Get CSRF token
function getCSRFToken() {
    const token = document.querySelector('meta[name="csrf-token"]');
    return token ? token.content : '';
}

// Load jitter settings from server
async function loadJitterInfo() {
    try {
        const response = await fetch('/news/api/scheduler/status', {
            credentials: 'same-origin',
            headers: {
                'X-CSRFToken': getCSRFToken()
            }
        });
        if (response.ok) {
            const data = await response.json();
            // FastAPI exposes the scheduler configuration under `config`.
            // Keep the legacy `settings` fallback for older deployments, and
            // normalize before interpolating the value into the static hint.
            const rawMaxJitter = data.config?.max_jitter_seconds
                ?? data.settings?.max_jitter_seconds
                ?? 300;
            const numericMaxJitter = (
                typeof rawMaxJitter === 'number' ||
                (typeof rawMaxJitter === 'string' && rawMaxJitter.trim() !== '')
            ) ? Number(rawMaxJitter) : NaN;
            const maxJitter = Number.isFinite(numericMaxJitter) &&
                numericMaxJitter >= 0 ? numericMaxJitter : 300;

            // Calculate jitter range in human-readable format
            const formatJitter = (seconds) => {
                if (seconds === 0) return '0';
                if (seconds < 60) return `${seconds} second${seconds !== 1 ? 's' : ''}`;
                const minutes = Math.round(seconds/60);
                if (minutes < 60) return `${minutes} minute${minutes !== 1 ? 's' : ''}`;
                const hours = Math.round(seconds/3600);
                return `${hours} hour${hours !== 1 ? 's' : ''}`;
            };

            let jitterText;
            if (maxJitter === 0) {
                jitterText = `<i aria-hidden="true" class="bi bi-info-circle"></i> No jitter configured. Subscriptions will run exactly at scheduled times.`;
            } else {
                jitterText = `<i aria-hidden="true" class="bi bi-shuffle"></i> A random delay up to <strong>${formatJitter(maxJitter)}</strong> will be added to prevent all subscriptions from running simultaneously.`;
            }

            jitterText += ` <a href="/settings#news_scheduler" class="text-muted" style="font-size: 0.85em;"><i aria-hidden="true" class="bi bi-gear"></i> Change in settings</a>`;

            const element = document.getElementById('subscription-jitter-info');
            if (element) {
                element.innerHTML = jitterText;
            }
        }
    } catch (error) {
        console.error('Error loading jitter info:', error);
    }
}
</script>
{% endblock %}