~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
Revert formatting for json
tombii3103498d63fe
diff --git a/package.json b/package.jsonindex 6bebdf2894..8ff6eb98be 100644--- a/package.json+++ b/package.json@@ -1,33 +1,30 @@{- "name": "local-deep-research-web",- "version": "1.0.0",- "description": "Web frontend for Local Deep Research",- "private": true,- "type": "module",- "scripts": {- "dev": "vite",- "build": "vite build",- "preview": "vite preview",- "update": "npm update",- "audit": "npm audit",- "audit-fix": "npm audit fix"- },- "dependencies": {- "@fortawesome/fontawesome-free": "^7.0.0",- "bootstrap": "^5.3.0",- "bootstrap-icons": "^1.11.0",- "chart.js": "^4.4.0",- "chartjs-adapter-date-fns": "^3.0.0",- "chartjs-plugin-annotation": "^3.0.0",- "date-fns": "^4.1.0",- "highlight.js": "^11.9.0",- "html2canvas": "^1.4.1",- "jspdf": "^3.0.2",- "marked": "^16.2.1",- "socket.io-client": "^4.6.0"- },- "devDependencies": {- "axe-core": "^4.8.0",- "vite": "^7.1.3"- }+ "name": "local-deep-research-web",+ "version": "1.0.0",+ "description": "Web frontend for Local Deep Research",+ "private": true,+ "type": "module",+ "scripts": {+ "dev": "vite",+ "build": "vite build",+ "preview": "vite preview",+ "update": "npm update",+ "audit": "npm audit",+ "audit-fix": "npm audit fix",+ },+ "dependencies": {+ "@fortawesome/fontawesome-free": "^7.0.0",+ "bootstrap": "^5.3.0",+ "bootstrap-icons": "^1.11.0",+ "chart.js": "^4.4.0",+ "chartjs-adapter-date-fns": "^3.0.0",+ "chartjs-plugin-annotation": "^3.0.0",+ "date-fns": "^4.1.0",+ "highlight.js": "^11.9.0",+ "html2canvas": "^1.4.1",+ "jspdf": "^3.0.2",+ "marked": "^16.2.1",+ "socket.io-client": "^4.6.0",+ },+ "devDependencies": {"axe-core": "^4.8.0", "vite": "^7.1.3"},}diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex f037f51285..899e84f194 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -35,39 +35,6 @@ from ...llm.providers.implementations.custom_openai_endpoint import (CustomOpenAIEndpointProvider,)-CATEGORY_CONFIG = {- "llm": {- "type": SettingType.LLM,- "general": "llm_general",- "parameters": "llm_parameters",- "param_keywords": ["temperature", "max_tokens", "batch", "layers"],- },- "search": {- "type": SettingType.SEARCH,- "general": "search_general",- "parameters": "search_parameters",- "param_keywords": [- "iterations",- "results",- "region",- "questions",- "section",- ],- },- "report": {- "type": SettingType.REPORT,- "general": None,- "parameters": "report_parameters",- "param_keywords": [],- },- "app": {- "type": SettingType.APP,- "general": None,- "parameters": "app_interface",- "param_keywords": [],- },-}-# Create a Blueprint for settingssettings_bp = Blueprint("settings", __name__, url_prefix="/settings")@@ -82,85 +49,6 @@ def _get_setting_from_session(key: str, default=None):return default-def normalize_checkbox_form_data(all_settings, form_data):- """- Normalize checkbox form data to handle HTML form behavior where unchecked checkboxes- are not included in form submission.- """- # Validate inputs- if not isinstance(all_settings, dict):- if all_settings is None:- logger.warning(- "all_settings is None in normalize_checkbox_form_data"- )- else:- logger.warning(- f"all_settings has unexpected type: {type(all_settings)}"- )- return form_data if isinstance(form_data, dict) else {}-- if not isinstance(form_data, dict):- if form_data is None:- logger.warning("form_data is None in normalize_checkbox_form_data")- else:- logger.warning(f"form_data has unexpected type: {type(form_data)}")- return {}-- # Detect categories present in the submitted form (by key prefix)- detected_categories = {- c for c in (get_category_from_key(k) for k in form_data.keys()) if c- }-- try:- for key, setting_data in all_settings.items():- # Only process checkbox UI elements with valid dict data- if (- not isinstance(setting_data, dict)- or setting_data.get("ui_element") != "checkbox"- ):- continue-- cat = get_category_from_key(key)- if cat not in detected_categories:- continue-- # If checkbox is missing -> unchecked- if key not in form_data:- form_data[key] = False- else:- v = form_data[key]- form_data[key] = (- v- if isinstance(v, bool)- else str(v).strip().lower() in {"true", "on", "1", "yes"}- )- except Exception:- logger.exception("Error in normalize_checkbox_form_data")- return form_data-- return form_data---def get_category_from_key(key: str) -> Optional[str]:- """- Determine the category of a setting based on its key prefix using CATEGORY_CONFIG.- Supports subcategory routing via param_keywords. Unknown prefixes map to their prefix.- """- parts = key.split(".")- if not parts:- return None-- prefix = parts[0]- cfg = CATEGORY_CONFIG.get(prefix)- if not cfg:- # Dynamic handling for new categories- return prefix-- if cfg["param_keywords"] and any(kw in key for kw in cfg["param_keywords"]):- return cfg["parameters"]- return cfg["general"] or cfg["parameters"]--def calculate_warnings():"""Calculate current warning conditions based on settings"""warnings = []@@ -309,49 +197,74 @@ def save_all_settings():# get_db_settings_manager(db_session)try:- # Try to process JSON data first (expected from JavaScript)+ # Process JSON dataform_data = request.get_json()-- # If no JSON data, fall back to form data (traditional form submission)if not form_data:- logger.info("No JSON data received, falling back to form data")- form_data = request.form.to_dict()- # Remove CSRF token from the data- form_data.pop("csrf_token", None)-- # Handle checkbox settings specifically for traditional form submission- # When unchecked, they won't be in form_data, so we need to explicitly set them to False- settings_manager = SettingsManager(db_session)-- # Get all settings- all_settings = settings_manager.get_all_settings()-- # Normalize checkbox form data using shared helper- form_data = normalize_checkbox_form_data(- all_settings, form_data- )-- logger.info(- f"Processed form data with {len(form_data)} settings"+ return (+ jsonify(+ {+ "status": "error",+ "message": "No settings data provided",+ }+ ),+ 400,)# Track validation errorsvalidation_errors = []+ settings_by_type = {}# Track changes for loggingupdated_settings = []created_settings = []+ # Store original values for better messaging+ original_values = {}+# Update each setting- for key, value in list(form_data.items()):+ for key, value in form_data.items():# Skip corrupted keys or empty strings as keysif not key or not isinstance(key, str) or key.strip() == "":continue- # Load current setting once for reuse in validation/update flow+ # Get the original valuecurrent_setting = (db_session.query(Setting).filter(Setting.key == key).first())+ if current_setting:+ original_values[key] = current_setting.value++ # Determine setting type and category+ if key.startswith("llm."):+ setting_type = SettingType.LLM+ category = "llm_general"+ if (+ "temperature" in key+ or "max_tokens" in key+ or "batch" in key+ or "layers" in key+ ):+ category = "llm_parameters"+ elif key.startswith("search."):+ setting_type = SettingType.SEARCH+ category = "search_general"+ if (+ "iterations" in key+ or "results" in key+ or "region" in key+ or "questions" in key+ or "section" in key+ ):+ category = "search_parameters"+ elif key.startswith("report."):+ setting_type = SettingType.REPORT+ category = "report_parameters"+ elif key.startswith("app."):+ setting_type = SettingType.APP+ category = "app_interface"+ else:+ setting_type = None+ category = None# Special handling for corrupted or empty valuesif value == "[object Object]" or (@@ -393,11 +306,6 @@ def save_all_settings():passif current_setting:- # Check if setting is editable before attempting to save- if not current_setting.editable:- logger.warning(f"Skipping non-editable setting: {key}")- continue-# Validate the settingis_valid, error_message = validate_setting(current_setting, value@@ -409,6 +317,12 @@ def save_all_settings():if success:updated_settings.append(key)+ # Track settings by type for exporting+ if current_setting.type not in settings_by_type:+ settings_by_type[current_setting.type] = []+ settings_by_type[current_setting.type].append(+ current_setting+ )else:# Add to validation errorsvalidation_errors.append(@@ -419,12 +333,6 @@ def save_all_settings():})else:- # Determine setting type and category using centralized functions- category = get_category_from_key(key)- setting_type = CATEGORY_CONFIG.get(- key.split(".")[0], {}- ).get("type", SettingType.APP)-# Create a new settingnew_setting = {"key": key,@@ -453,6 +361,10 @@ def save_all_settings():if db_setting:created_settings.append(key)+ # Track settings by type for exporting+ if db_setting.type not in settings_by_type:+ settings_by_type[db_setting.type] = []+ settings_by_type[db_setting.type].append(db_setting)else:validation_errors.append({@@ -497,8 +409,10 @@ def save_all_settings():})- # Build success message- if len(updated_settings) == 1 and not created_settings:+ # Customize the success message based on what changed+ success_message = ""+ if len(updated_settings) == 1:+ # For a single update, provide more specific info about what changedkey = updated_settings[0]updated_setting = (db_session.query(Setting).filter(Setting.key == key).first()@@ -508,14 +422,29 @@ def save_all_settings():if updated_settingelse key.split(".")[-1].replace("_", " ").title())- new_value = updated_setting.value if updated_setting else None- if isinstance(new_value, bool):- success_message = (- f"{name} {'enabled' if new_value else 'disabled'}"++ # Format the message+ if key in original_values:+ # Get original value but comment out if not used+ # old_value = original_values[key]+ new_value = (+ updated_setting.value if updated_setting else None)++ # If it's a boolean, use "enabled/disabled" language+ if isinstance(new_value, bool):+ state = "enabled" if new_value else "disabled"+ success_message = f"{name} {state}"+ else:+ # For non-boolean values+ if isinstance(new_value, (dict, list)):+ success_message = f"{name} updated"+ else:+ success_message = f"{name} updated"else:success_message = f"{name} updated"else:+ # Multiple settings or generic messagesuccess_message = f"Settings saved successfully ({len(updated_settings)} updated, {len(created_settings)} created)"# Check if any warning-affecting settings were changed and include warnings@@ -548,9 +477,6 @@ def save_all_settings():f"Bulk settings update affected warning keys, calculated {len(warnings)} warnings")- # Sync server config with updated settings- settings_snapshot = settings_manager.get_settings_snapshot()- sync_from_settings(settings_snapshot)return jsonify(response_data)except Exception:@@ -615,35 +541,33 @@ def save_settings():updated_count = 0failed_count = 0- # Handle checkbox settings specifically- # When unchecked, they won't be in form_data, so we need to explicitly set them to False-- # Get all settings- all_settings = settings_manager.get_all_settings()-- # Normalize checkbox form data using shared helper- form_data = normalize_checkbox_form_data(all_settings, form_data)-# Process each setting- for key, value in list(form_data.items()):+ for key, value in form_data.items():try:- # Try to coerce numeric values- if isinstance(value, str):+ # Handle checkbox values+ if value == "on" or value == "true" or value == "True":+ value = True+ elif (+ value == "off"+ or value == ""+ or value == "false"+ or value == "False"+ ):+ value = False++ # Try to convert numeric values+ if (+ isinstance(value, str)+ and value.replace(".", "").replace("-", "").isdigit()+ ):try:- value = float(value) if "." in value else int(value)+ if "." in value:+ value = float(value)+ else:+ value = int(value)except ValueError:pass # Keep as string- # Check if setting is editable before attempting to save- current_setting = (- db_session.query(Setting)- .filter(Setting.key == key)- .first()- )- if current_setting and not current_setting.editable:- logger.warning(f"Skipping non-editable setting: {key}")- continue-# Save the settingif settings_manager.set_setting(key, value, commit=False):updated_count += 1@@ -1949,8 +1873,6 @@ def fix_corrupted_settings():default_value = 5000elif setting.key == "app.debug":default_value = True- elif setting.key == "app.allow_registrations":- default_value = True# Update the setting with the default value if foundif default_value is not None:diff --git a/src/local_deep_research/web/static/js/components/checkbox_handler.js b/src/local_deep_research/web/static/js/components/checkbox_handler.jsnew file mode 100644index 0000000000..c2fdefcada--- /dev/null+++ b/src/local_deep_research/web/static/js/components/checkbox_handler.js@@ -0,0 +1,84 @@+/**+ * Centralized checkbox with hidden fallback handling+ * Provides reusable functionality across all templates+ */+(function() {+ 'use strict';++ const CheckboxHandler = {+ /**+ * Initialize all checkbox-hidden fallback pairs+ */+ init: function() {+ this.initializeStandardCheckboxes();+ this.initializeJsonCheckboxes();+ this.setupFormSubmissionHandler();+ console.log('Checkbox handler initialized');+ },++ initializeStandardCheckboxes: function() {+ document.querySelectorAll('input[type="checkbox"][data-hidden-fallback]').forEach(checkbox => {+ const hiddenId = checkbox.dataset.hiddenFallback;+ const hiddenInput = document.getElementById(hiddenId);++ if (hiddenInput) {+ // Set initial state: disable hidden when checkbox is checked+ hiddenInput.disabled = checkbox.checked;++ // Add change listener+ checkbox.addEventListener('change', () => {+ hiddenInput.disabled = checkbox.checked;+ });+ }+ });+ },++ initializeJsonCheckboxes: function() {+ document.querySelectorAll('.json-property-control[type="checkbox"][data-hidden-fallback]').forEach(checkbox => {+ const hiddenId = checkbox.dataset.hiddenFallback;+ const hiddenInput = document.getElementById(hiddenId);++ if (hiddenInput) {+ hiddenInput.disabled = checkbox.checked;++ checkbox.addEventListener('change', () => {+ hiddenInput.disabled = checkbox.checked;++ // Trigger JSON update if function exists+ if (typeof updateJsonFromControls === 'function') {+ updateJsonFromControls(checkbox, true);+ }+ });+ }+ });+ },++ setupFormSubmissionHandler: function() {+ // Ensure all hidden inputs are properly configured before form submission+ document.addEventListener('submit', (event) => {+ const form = event.target;+ this.prepareFormSubmission(form);+ });+ },++ prepareFormSubmission: function(form) {+ // Final sync before form submission+ form.querySelectorAll('input[type="checkbox"][data-hidden-fallback]').forEach(checkbox => {+ const hiddenInput = document.getElementById(checkbox.dataset.hiddenFallback);+ if (hiddenInput) {+ hiddenInput.disabled = checkbox.checked;+ }+ });+ }+ };++ // Export for global access+ window.checkboxHandler = CheckboxHandler;++ // Auto-initialize on DOM ready+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', () => CheckboxHandler.init());+ } else {+ CheckboxHandler.init();+ }+})();diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.jsindex 5ccf0c5b9d..51b238443c 100644--- a/src/local_deep_research/web/static/js/components/settings.js+++ b/src/local_deep_research/web/static/js/components/settings.js@@ -387,6 +387,15 @@else if (input.type === 'checkbox') {value = input.checked;shouldSaveImmediately = true; // Checkboxes save immediately++ // Sync with hidden fallback if it exists+ const hiddenFallback = input.dataset.hiddenFallback;+ if (hiddenFallback) {+ const hiddenInput = document.getElementById(hiddenFallback);+ if (hiddenInput) {+ hiddenInput.disabled = input.checked;+ }+ }}// Handle standard selectselse if (input.tagName.toLowerCase() === 'select') {@@ -677,6 +686,15 @@if (control.type === 'checkbox') {value = control.checked;++ // Sync with hidden fallback for JSON checkboxes+ const hiddenFallback = control.dataset.hiddenFallback;+ if (hiddenFallback) {+ const hiddenInput = document.getElementById(hiddenFallback);+ if (hiddenInput) {+ hiddenInput.disabled = control.checked;+ }+ }} else if (control.type === 'number') {value = parseFloat(control.value);} else if (control.tagName === 'SELECT') {@@ -795,11 +813,11 @@if (specificForm) {// Add form submission handlerspecificForm.addEventListener('submit', function(e) {- // Handle checkbox values+ // Handle checkbox values - only for checkboxes without hidden fallbacksconst checkboxes = specificForm.querySelectorAll('input[type="checkbox"]');checkboxes.forEach(checkbox => {- if (!checkbox.checked) {- // Create a hidden input for unchecked boxes+ if (!checkbox.checked && !checkbox.dataset.hiddenFallback) {+ // Only create hidden input for unchecked boxes that don't have fallback inputsconst hidden = document.createElement('input');hidden.type = 'hidden';hidden.name = checkbox.name;@@ -1936,11 +1954,20 @@case 'checkbox':const checked = setting.value === true || setting.value === 'true' ? 'checked' : '';+ const hiddenFallbackId = `${settingId}_hidden_fallback`;inputElement = `<div class="settings-checkbox-container"><label class="checkbox-label" for="${settingId}">+ <!-- Hidden input ensures unchecked state is submitted -->+ <input type="hidden"+ name="${setting.key}"+ id="${hiddenFallbackId}"+ value="false"+ class="checkbox-hidden-fallback">+ <!-- Actual checkbox overrides hidden input when checked --><input type="checkbox" id="${settingId}" name="${setting.key}"class="settings-checkbox"+ data-hidden-fallback="${hiddenFallbackId}"${checked}${!setting.editable ? 'disabled' : ''}>@@ -2069,16 +2096,25 @@// Create appropriate control based on value typeif (typeof value === 'boolean') {+ const hiddenFallbackId = `${controlId}_hidden_fallback`;controlHtml = `<div class="json-property-item boolean-property" onclick="directToggleCheckbox('${controlId}')" data-checkboxid="${controlId}"><div class="checkbox-wrapper"><label class="checkbox-label" for="${controlId}">+ <!-- Hidden input ensures unchecked state is submitted -->+ <input type="hidden"+ name="${setting.key}_${key}"+ id="${hiddenFallbackId}"+ value="false"+ class="checkbox-hidden-fallback">+ <!-- Actual checkbox overrides hidden input when checked --><input type="checkbox"id="${controlId}"name="${setting.key}_${key}"- class="json-property-control"+ class="json-property-control settings-checkbox"data-property="${key}"data-parent-key="${setting.key}"+ data-hidden-fallback="${hiddenFallbackId}"${value ? 'checked' : ''}${!setting.editable ? 'disabled' : ''}><span class="checkbox-text">${formattedName}</span>diff --git a/src/local_deep_research/web/templates/components/settings_form.html b/src/local_deep_research/web/templates/components/settings_form.htmlindex 89286298b9..9ce24be5ec 100644--- a/src/local_deep_research/web/templates/components/settings_form.html+++ b/src/local_deep_research/web/templates/components/settings_form.html@@ -32,12 +32,22 @@{% if value is boolean %}<div class="ldr-checkbox-label">+ <!-- Hidden input ensures unchecked state is submitted -->+ <input type="hidden"+ name="{{ setting.key }}_{{ key }}"+ id="{{ setting_id }}_{{ key }}_hidden_fallback"+ value="false"+ class="checkbox-hidden-fallback">++ <!-- Actual checkbox overrides hidden input when checked --><input type="checkbox"id="{{ setting_id }}_{{ key }}"name="{{ setting.key }}_{{ key }}"- class="ldr-json-property-control"+ value="true"+ class="ldr-json-property-control ldr-settings-checkbox"data-property="{{ key }}"data-parent-key="{{ setting.key }}"+ data-hidden-fallback="{{ setting_id }}_{{ key }}_hidden_fallback"{% if value %}checked{% endif %}{% if not setting.editable %}disabled{% endif %}><span class="ldr-checkbox-text">{{ key|replace("_", " ")|title }}</span>@@ -119,13 +129,22 @@{% elif setting.ui_element == "checkbox" %}<div class="ldr-checkbox-label">- <input- type="checkbox"- id="{{ setting_id }}"- name="{{ setting.key }}"- {% if setting.value == true or setting.value == "true" %}checked{% endif %}- {% if not setting.editable %}disabled{% endif %}- >+ <!-- Hidden input ensures unchecked state is submitted -->+ <input type="hidden"+ name="{{ setting.key }}"+ id="{{ setting_id }}_hidden_fallback"+ value="false"+ class="checkbox-hidden-fallback">++ <!-- Actual checkbox overrides hidden input when checked -->+ <input type="checkbox"+ id="{{ setting_id }}"+ name="{{ setting.key }}"+ value="true"+ {% if setting.value == true or setting.value == "true" %}checked{% endif %}+ {% if not setting.editable %}disabled{% endif %}+ class="ldr-settings-checkbox"+ data-hidden-fallback="{{ setting_id }}_hidden_fallback"><span class="ldr-checkbox-text">{{ setting.name }}</span></div>@@ -210,12 +229,22 @@{% if value is boolean %}<div class="ldr-checkbox-label">+ <!-- Hidden input ensures unchecked state is submitted -->+ <input type="hidden"+ name="{{ setting.key }}_{{ key }}"+ id="{{ setting_id }}_{{ key }}_hidden_fallback"+ value="false"+ class="checkbox-hidden-fallback">++ <!-- Actual checkbox overrides hidden input when checked --><input type="checkbox"id="{{ setting_id }}_{{ key }}"name="{{ setting.key }}_{{ key }}"- class="ldr-json-property-control"+ value="true"+ class="ldr-json-property-control ldr-settings-checkbox"data-property="{{ key }}"data-parent-key="{{ setting.key }}"+ data-hidden-fallback="{{ setting_id }}_{{ key }}_hidden_fallback"{% if value %}checked{% endif %}{% if not setting.editable %}disabled{% endif %}><span class="ldr-checkbox-text">{{ key|replace("_", " ")|title }}</span>diff --git a/src/local_deep_research/web/templates/settings_dashboard.html b/src/local_deep_research/web/templates/settings_dashboard.htmlindex 80e60039cd..cf9ff534e1 100644--- a/src/local_deep_research/web/templates/settings_dashboard.html+++ b/src/local_deep_research/web/templates/settings_dashboard.html@@ -101,5 +101,6 @@{% block page_scripts %}<script src="/static/js/components/custom_dropdown.js"></script>+<script src="/static/js/components/checkbox_handler.js"></script><script src="/static/js/components/settings.js"></script>{% endblock %}diff --git a/tests/ui_tests/test_checkbox_settings.js b/tests/ui_tests/test_checkbox_settings.jsnew file mode 100644index 0000000000..44f50930be--- /dev/null+++ b/tests/ui_tests/test_checkbox_settings.js@@ -0,0 +1,183 @@+const puppeteer = require('puppeteer');+const AuthHelper = require('./auth_helper');+const { getPuppeteerLaunchOptions } = require('./puppeteer_config');++(async () => {+ let browser;+ try {+ console.log('=== Testing Checkbox Hidden Input Solution ===');++ browser = await puppeteer.launch(getPuppeteerLaunchOptions());++ const page = await browser.newPage();+ await page.setViewport({ width: 1920, height: 1080 });++ // Monitor console for logs and errors+ page.on('console', msg => {+ const text = msg.text();+ if (msg.type() === 'error') {+ console.error(`[JS ERROR] ${text}`);+ } else if (text.includes('Checkbox handler initialized')) {+ console.log(`[JS LOG] ${text}`);+ } else if (text.includes('checkbox') || text.includes('hidden')) {+ console.log(`[RELEVANT JS] ${text}`);+ }+ });++ const authHelper = new AuthHelper(page);++ // Create and login test user+ const timestamp = Date.now();+ const testUsername = `checkbox_test_${timestamp}`;+ // Navigate to settings directly since we're testing an existing user+ await page.goto('http://localhost:5000/auth/login', { waitUntil: 'networkidle2' });+ await page.type('input[name="username"]', 'testuser');+ await page.type('input[name="password"]', 'T3st!Secure#2024$LDR');+ await Promise.all([+ page.waitForNavigation({ waitUntil: 'networkidle2', timeout: 60000 }),+ page.click('button[type="submit"]')+ ]);+ console.log('User registered and logged in');++ // Navigate to settings page+ await page.goto('http://localhost:5000/settings', { waitUntil: 'networkidle2' });+ await page.waitForSelector('#settings-form', { timeout: 10000 });+ await new Promise(resolve => setTimeout(resolve, 2000)); // Wait for JS init++ // Verify checkbox handler initialized (check console log)++ // Test standard checkboxes+ console.log('\n--- Testing Standard Checkboxes ---');+ const standardCheckboxes = await page.$$('input[type="checkbox"].settings-checkbox:not(.json-property-control)');+ console.log(`Found ${standardCheckboxes.length} standard checkboxes`);++ if (standardCheckboxes.length > 0) {+ const firstCheckbox = standardCheckboxes[0];+ const checkboxName = await firstCheckbox.evaluate(el => el.name);+ const hiddenFallbackId = await firstCheckbox.evaluate(el => el.dataset.hiddenFallback);+ const hiddenInput = await page.$(`#${hiddenFallbackId}`);++ console.log(`Testing checkbox: ${checkboxName}, hidden: ${hiddenFallbackId}`);++ // Check initial state+ const isChecked = await firstCheckbox.evaluate(el => el.checked);+ const hiddenDisabled = await hiddenInput.evaluate(el => el.disabled);+ console.log(`Initial: checked=${isChecked}, hidden disabled=${hiddenDisabled} (should be ${isChecked})`);++ // Toggle checkbox+ await firstCheckbox.click();+ await page.waitForTimeout(500);++ const newChecked = await firstCheckbox.evaluate(el => el.checked);+ const newHiddenDisabled = await hiddenInput.evaluate(el => el.disabled);+ console.log(`After toggle: checked=${newChecked}, hidden disabled=${newHiddenDisabled} (should be ${newChecked})`);++ // Toggle back if needed+ if (newChecked !== isChecked) {+ await firstCheckbox.click();+ }+ }++ // Test JSON property checkboxes+ console.log('\n--- Testing JSON Property Checkboxes ---');+ const jsonCheckboxes = await page.$$('input[type="checkbox"].json-property-control');+ console.log(`Found ${jsonCheckboxes.length} JSON checkboxes`);++ if (jsonCheckboxes.length > 0) {+ const firstJsonCheckbox = jsonCheckboxes[0];+ const jsonName = await firstJsonCheckbox.evaluate(el => el.name);+ const jsonHiddenFallbackId = await firstJsonCheckbox.evaluate(el => el.dataset.hiddenFallback);+ const jsonHiddenInput = await page.$(`#${jsonHiddenFallbackId}`);++ console.log(`Testing JSON checkbox: ${jsonName}, hidden: ${jsonHiddenFallbackId}`);++ // Check initial state+ const jsonIsChecked = await firstJsonCheckbox.evaluate(el => el.checked);+ const jsonHiddenDisabled = await jsonHiddenInput.evaluate(el => el.disabled);+ console.log(`Initial JSON: checked=${jsonIsChecked}, hidden disabled=${jsonHiddenDisabled} (should be ${jsonIsChecked})`);++ // Toggle+ await firstJsonCheckbox.click();+ await page.waitForTimeout(500);++ const newJsonChecked = await firstJsonCheckbox.evaluate(el => el.checked);+ const newJsonHiddenDisabled = await jsonHiddenInput.evaluate(el => el.disabled);+ console.log(`After JSON toggle: checked=${newJsonChecked}, hidden disabled=${newJsonHiddenDisabled} (should be ${newJsonChecked})`);++ // Toggle back+ if (newJsonChecked !== jsonIsChecked) {+ await firstJsonCheckbox.click();+ }+ }++ // Test form submission (mixed states)+ console.log('\n--- Testing Form Submission ---');+ // Toggle a few checkboxes to create mixed state+ const allCheckboxes = await page.$$('input[type="checkbox"].settings-checkbox');+ for (let i = 0; i < Math.min(3, allCheckboxes.length); i++) {+ await allCheckboxes[i].click();+ await page.waitForTimeout(200);+ }++ // Submit the form+ const submitButton = await page.$('button[type="submit"]');+ if (submitButton) {+ await Promise.all([+ page.waitForNavigation({ waitUntil: 'networkidle2', timeout: 10000 }).catch(() => {}), // Handle if no navigation+ submitButton.click()+ ]);+ await page.waitForTimeout(2000); // Wait for save++ // Check for success message+ const successAlert = await page.$('.alert-success');+ const hasSuccess = successAlert !== null;+ console.log(`Form submission success: ${hasSuccess}`);++ // Check no errors in page+ const errors = await page.evaluate(() => document.querySelectorAll('.alert-error').length);+ console.log(`Page errors after submit: ${errors}`);+ } else {+ console.log('No submit button found');+ }++ // Test AJAX auto-save (change a checkbox and check network)+ console.log('\n--- Testing AJAX Auto-Save ---');+ if (allCheckboxes.length > 0) {+ // Listen for network requests+ const requests = [];+ page.on('request', req => {+ if (req.url().includes('/settings/save_all_settings')) {+ requests.push(req.url() + ' - ' + req.method());+ }+ });++ // Toggle one checkbox+ await allCheckboxes[0].click();+ await page.waitForTimeout(2000); // Wait for debounce++ // Check if save request was made+ const saveRequests = requests.filter(r => r.includes('save_all_settings'));+ console.log(`AJAX save requests: ${saveRequests.length}`);+ if (saveRequests.length > 0) {+ console.log('AJAX auto-save triggered successfully');+ }+ }++ // Verify no JS errors occurred during the test+ const errors = await page.evaluate(() => {+ const errorElements = document.querySelectorAll('.settings-error');+ return errorElements.length;+ });+ console.log(`Validation errors on page: ${errors}`);++ console.log('\n=== Checkbox Test Completed ===');+ console.log('All tests passed if no errors above.');++ } catch (error) {+ console.error('Test failed:', error.message);+ } finally {+ if (browser) {+ await browser.close();+ }+ }+})();