~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
fix(web): preserve 0 chunk overlap in embedding settings and unify defaults across stack (#6076)
S5a8fd7fa0296
diff --git a/changelog.d/+chunk-overlap-zero-hydration.bugfix.md b/changelog.d/+chunk-overlap-zero-hydration.bugfix.mdnew file mode 100644index 0000000000..f95f15fb33--- /dev/null+++ b/changelog.d/+chunk-overlap-zero-hydration.bugfix.md@@ -0,0 +1,14 @@+Fixed the embedding settings form dropping a saved chunk overlap of 0+on reload. The page used a JavaScript truthy check+(`if (settings.chunk_overlap)`) to populate the input field from+`/library/api/rag/settings`; `0` is falsy, so the assignment was+skipped and the HTML default (`value="200"`) silently took over.+The change-tracker also wrapped the snapshot in+`parseInt(...) || 200`, producing the same falsy collapse and firing+a spurious auto-save on the next blur. Both now use an explicit+null/undefined check so a legitimate 0 survives end-to-end.++Centralized local search and embedding defaults into shared constants.+On unconfigured/fallback paths without explicit database settings, the+factory's fallback `normalize_vectors` default is unified to `True`+(matching the settings registry and RAG router defaults).diff --git a/src/local_deep_research/constants.py b/src/local_deep_research/constants.pyindex f74c2ab728..bc9ba9e8cc 100644--- a/src/local_deep_research/constants.py+++ b/src/local_deep_research/constants.py@@ -88,9 +88,21 @@ FILE_PATH_SENTINELS = (FILE_PATH_BLOB_DELETED,)-# --- Default RAG / Local Search text separators ---+# --- Default RAG / Local Search settings ---+# Code-side single source of truth for local search / embedding defaults,+# used by every reader needing a fallback for missing settings.+# Must match the registered defaults in defaults/settings_local_search.json —+# pinned by tests/test_constants.py::test_default_local_search_settings_match_registry.+DEFAULT_LOCAL_SEARCH_PROVIDER: str = "sentence_transformers"+DEFAULT_LOCAL_SEARCH_MODEL: str = "all-MiniLM-L6-v2"+DEFAULT_LOCAL_SEARCH_CHUNK_SIZE: int = 1000+DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP: int = 200+DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE: str = "recursive"DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS: List[str] = ["\n\n", "\n", ". ", " ", ""]DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS_JSON = '["\\n\\n", "\\n", ". ", " ", ""]'+DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC: str = "cosine"+DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS: bool = True+DEFAULT_LOCAL_SEARCH_INDEX_TYPE: str = "flat"# --- Snippet / truncation lengths ---diff --git a/src/local_deep_research/embeddings/splitters/text_splitter_registry.py b/src/local_deep_research/embeddings/splitters/text_splitter_registry.pyindex 8c530d8763..ca3c21a884 100644--- a/src/local_deep_research/embeddings/splitters/text_splitter_registry.py+++ b/src/local_deep_research/embeddings/splitters/text_splitter_registry.py@@ -13,6 +13,13 @@ from typing import Optional, List, Any, TYPE_CHECKINGfrom loguru import logger+from ...constants import (+ DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,+ DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,+ DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE,+ DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS,+)+# ``langchain_text_splitters`` is imported lazily inside ``get_text_splitter``# (see below), NOT at module load. Importing *any* of its submodules runs the# package ``__init__``, which eagerly pulls sentence-transformers, torch,@@ -53,9 +60,9 @@ VALID_SPLITTER_TYPES = [def get_text_splitter(- splitter_type: str = "recursive",- chunk_size: int = 1000,- chunk_overlap: int = 200,+ splitter_type: str = DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE,+ chunk_size: int = DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,+ chunk_overlap: int = DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,text_separators: Optional[List[str]] = None,embeddings: Optional[Embeddings] = None,**kwargs,@@ -229,7 +236,7 @@ def get_text_splitter(# Use custom separators if provided, otherwise use defaultsif text_separators is None:- text_separators = ["\n\n", "\n", ". ", " ", ""]+ text_separators = list(DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS)return RecursiveCharacterTextSplitter(chunk_size=chunk_size,diff --git a/src/local_deep_research/research_library/services/library_rag_service.py b/src/local_deep_research/research_library/services/library_rag_service.pyindex 273164a822..7df533fc2f 100644--- a/src/local_deep_research/research_library/services/library_rag_service.py+++ b/src/local_deep_research/research_library/services/library_rag_service.py@@ -28,7 +28,17 @@ from sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.orm import Sessionfrom ...config.paths import get_cache_directory-from ...constants import DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS+from ...constants import (+ DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,+ DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,+ DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC,+ DEFAULT_LOCAL_SEARCH_INDEX_TYPE,+ DEFAULT_LOCAL_SEARCH_MODEL,+ DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS,+ DEFAULT_LOCAL_SEARCH_PROVIDER,+ DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE,+ DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS,+)from ...database.models.library import (Document,DocumentChunk,@@ -277,15 +287,15 @@ class LibraryRAGService:def __init__(self,username: str,- embedding_model: str = "all-MiniLM-L6-v2",- embedding_provider: str = "sentence_transformers",- chunk_size: int = 1000,- chunk_overlap: int = 200,- splitter_type: str = "recursive",+ embedding_model: str = DEFAULT_LOCAL_SEARCH_MODEL,+ embedding_provider: str = DEFAULT_LOCAL_SEARCH_PROVIDER,+ chunk_size: int = DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,+ chunk_overlap: int = DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,+ splitter_type: str = DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE,text_separators: Optional[list] = None,- distance_metric: str = "cosine",- normalize_vectors: bool = True,- index_type: str = "flat",+ distance_metric: str = DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC,+ normalize_vectors: bool = DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS,+ index_type: str = DEFAULT_LOCAL_SEARCH_INDEX_TYPE,embedding_manager: Optional["LocalEmbeddingManager"] = None,db_password: Optional[str] = None,):@@ -320,7 +330,7 @@ class LibraryRAGService:self.text_separators = (text_separatorsif text_separators is not None- else ["\n\n", "\n", ". ", " ", ""]+ else list(DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS))self.distance_metric = distance_metric# Ensure normalize_vectors is always a proper booleandiff --git a/src/local_deep_research/research_library/services/rag_service_factory.py b/src/local_deep_research/research_library/services/rag_service_factory.pyindex 5c789d9645..dc7fba2913 100644--- a/src/local_deep_research/research_library/services/rag_service_factory.py+++ b/src/local_deep_research/research_library/services/rag_service_factory.py@@ -12,6 +12,14 @@ from typing import Optionalfrom loguru import loggerfrom ...constants import (+ DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,+ DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,+ DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC,+ DEFAULT_LOCAL_SEARCH_INDEX_TYPE,+ DEFAULT_LOCAL_SEARCH_MODEL,+ DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS,+ DEFAULT_LOCAL_SEARCH_PROVIDER,+ DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE,DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS,DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS_JSON,)@@ -79,7 +87,7 @@ def _enforce_embeddings_policy(or DEFAULT_EGRESS_SCOPE)require_local_flag = to_bool(- settings_manager.get_setting("embeddings.require_local") or False+ settings_manager.get_setting("embeddings.require_local", False), False)base_url = settings_manager.get_setting("embeddings.openai.base_url")ollama_url = settings_manager.get_setting("embeddings.ollama.url")@@ -159,9 +167,8 @@ def get_rag_service()# Get current default settings.- # The local_search_* keys are written by the embedding-settings page- # and have no JSON defaults file yet, so explicit fallbacks are- # required to avoid TypeError / None propagation on fresh installs.+ # Explicit fallbacks to centralized constants ensure safe operation+ # on fresh installs before settings are saved to the database.raw_embedding_model = settings.get_setting("local_search_embedding_model")@@ -169,39 +176,52 @@ def get_rag_service("local_search_embedding_provider")# Warn on silent fallback so a regression of #3453 is visible in logs- # instead of being masked by `or`-chained defaults. On fresh installs+ # instead of being masked by fallback defaults. On fresh installs# this fires legitimately until the user saves settings; in a# regression it would fire on every indexing call.if not raw_embedding_model and not raw_embedding_provider:logger.warning("local_search embedding settings are empty; falling back to "- "hardcoded defaults (sentence_transformers/all-MiniLM-L6-v2). "+ f"defaults ({DEFAULT_LOCAL_SEARCH_PROVIDER}/{DEFAULT_LOCAL_SEARCH_MODEL}). ""Expected on fresh installs before settings are saved; ""otherwise check that db_session is being passed to ""SettingsManager (see #3453).")- default_embedding_model = raw_embedding_model or "all-MiniLM-L6-v2"+ default_embedding_model = (+ raw_embedding_model or DEFAULT_LOCAL_SEARCH_MODEL+ )default_embedding_provider = (- raw_embedding_provider or "sentence_transformers"+ raw_embedding_provider or DEFAULT_LOCAL_SEARCH_PROVIDER)- default_chunk_size = int(- settings.get_setting("local_search_chunk_size") or 1000+ raw_chunk_size = settings.get_setting("local_search_chunk_size")+ default_chunk_size = (+ int(raw_chunk_size)+ if raw_chunk_size is not None and str(raw_chunk_size).strip() != ""+ else DEFAULT_LOCAL_SEARCH_CHUNK_SIZE)- default_chunk_overlap = int(- settings.get_setting("local_search_chunk_overlap") or 200+ raw_chunk_overlap = settings.get_setting("local_search_chunk_overlap")+ default_chunk_overlap = (+ int(raw_chunk_overlap)+ if raw_chunk_overlap is not None+ and str(raw_chunk_overlap).strip() != ""+ else DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP)default_splitter_type = (- settings.get_setting("local_search_splitter_type") or "recursive"+ settings.get_setting("local_search_splitter_type")+ or DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE)default_text_separators = _get_default_text_separators(settings)default_distance_metric = (- settings.get_setting("local_search_distance_metric") or "cosine"+ settings.get_setting("local_search_distance_metric")+ or DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC)- default_normalize_vectors = settings.get_bool_setting(- "local_search_normalize_vectors"+ default_normalize_vectors = to_bool(+ settings.get_setting("local_search_normalize_vectors"),+ DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS,)default_index_type = (- settings.get_setting("local_search_index_type") or "flat"+ settings.get_setting("local_search_index_type")+ or DEFAULT_LOCAL_SEARCH_INDEX_TYPE)# If collection_id provided, check for stored settingsdiff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.pyindex 3b0b87ee2f..27a05f2350 100644--- a/src/local_deep_research/web/routers/rag.py+++ b/src/local_deep_research/web/routers/rag.py@@ -46,6 +46,14 @@ from tenacity import (from sqlalchemy.orm import deferfrom ...constants import (+ DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,+ DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,+ DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC,+ DEFAULT_LOCAL_SEARCH_INDEX_TYPE,+ DEFAULT_LOCAL_SEARCH_MODEL,+ DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS,+ DEFAULT_LOCAL_SEARCH_PROVIDER,+ DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE,DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS,DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS_JSON,FILE_PATH_SENTINELS,@@ -644,29 +652,36 @@ def get_current_settings("settings": {"embedding_provider": settings.get_setting("local_search_embedding_provider",- "sentence_transformers",+ DEFAULT_LOCAL_SEARCH_PROVIDER,),"embedding_model": settings.get_setting(- "local_search_embedding_model", "all-MiniLM-L6-v2"+ "local_search_embedding_model",+ DEFAULT_LOCAL_SEARCH_MODEL,),"chunk_size": settings.get_setting(- "local_search_chunk_size", 1000+ "local_search_chunk_size",+ DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,),"chunk_overlap": settings.get_setting(- "local_search_chunk_overlap", 200+ "local_search_chunk_overlap",+ DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,),"splitter_type": settings.get_setting(- "local_search_splitter_type", "recursive"+ "local_search_splitter_type",+ DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE,),"text_separators": _get_text_separators(settings),"distance_metric": settings.get_setting(- "local_search_distance_metric", "cosine"+ "local_search_distance_metric",+ DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC,),"normalize_vectors": settings.get_setting(- "local_search_normalize_vectors", True+ "local_search_normalize_vectors",+ DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS,),"index_type": settings.get_setting(- "local_search_index_type", "flat"+ "local_search_index_type",+ DEFAULT_LOCAL_SEARCH_INDEX_TYPE,),},}@@ -1363,13 +1378,19 @@ async def configure_rag(collection_id = data.get("collection_id")# Get new advanced settings (with defaults)- splitter_type = data.get("splitter_type", "recursive")+ splitter_type = data.get(+ "splitter_type", DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE+ )text_separators = data.get(- "text_separators", ["\n\n", "\n", ". ", " ", ""]+ "text_separators", DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS+ )+ distance_metric = data.get(+ "distance_metric", DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC+ )+ normalize_vectors = data.get(+ "normalize_vectors", DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS)- distance_metric = data.get("distance_metric", "cosine")- normalize_vectors = data.get("normalize_vectors", True)- index_type = data.get("index_type", "flat")+ index_type = data.get("index_type", DEFAULT_LOCAL_SEARCH_INDEX_TYPE)if (not embedding_modeldiff --git a/src/local_deep_research/web/static/js/collection_details.js b/src/local_deep_research/web/static/js/collection_details.jsindex 6075f708a3..adc4628ce3 100644--- a/src/local_deep_research/web/static/js/collection_details.js+++ b/src/local_deep_research/web/static/js/collection_details.js@@ -195,11 +195,11 @@ function displayCollectionEmbeddingSettings() {</div><div class="ldr-info-item"><span class="ldr-info-label">Chunk Size:</span>- <span class="ldr-info-value">${escapeHtml(String(collectionData.chunk_size || 'Not set'))} ${collectionData.chunk_size ? 'characters' : ''}</span>+ <span class="ldr-info-value">${escapeHtml(String(collectionData.chunk_size ?? 'Not set'))} ${collectionData.chunk_size != null ? 'characters' : ''}</span></div><div class="ldr-info-item"><span class="ldr-info-label">Chunk Overlap:</span>- <span class="ldr-info-value">${escapeHtml(String(collectionData.chunk_overlap || 'Not set'))} ${collectionData.chunk_overlap ? 'characters' : ''}</span>+ <span class="ldr-info-value">${escapeHtml(String(collectionData.chunk_overlap ?? 'Not set'))} ${collectionData.chunk_overlap != null ? 'characters' : ''}</span></div>${collectionData.embedding_dimension ? `<div class="ldr-info-item">@@ -928,3 +928,5 @@ window.getProviderLabel = getProviderLabel;window.renderIndexingFailure = renderIndexingFailure;window.hideProgressUI = hideProgressUI;window.startPolling = startPolling;+window.displayCollectionEmbeddingSettings = displayCollectionEmbeddingSettings;+window.setCollectionDataForTesting = (data) => { collectionData = data; };diff --git a/src/local_deep_research/web/static/js/config/constants.js b/src/local_deep_research/web/static/js/config/constants.jsindex 6877b41f3e..b43f7acf0e 100644--- a/src/local_deep_research/web/static/js/config/constants.js+++ b/src/local_deep_research/web/static/js/config/constants.js@@ -16,6 +16,8 @@* the app is broken anyway (base.html renders every page).*/+const _injectedLocalSearchDefaults = (typeof window !== 'undefined' && window.LDR_LOCAL_SEARCH_DEFAULTS) || {};+if (typeof LDR_CONSTANTS !== 'undefined') {if (typeof SafeLogger !== 'undefined') {SafeLogger.warn('LDR_CONSTANTS already defined, skipping redeclaration');@@ -27,7 +29,15 @@ if (typeof LDR_CONSTANTS !== 'undefined') {TEXT: 'text',SEMANTIC: 'semantic',},- DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS: ["\n\n", "\n", ". ", " ", ""],+ DEFAULT_LOCAL_SEARCH_PROVIDER: _injectedLocalSearchDefaults.provider || 'sentence_transformers',+ DEFAULT_LOCAL_SEARCH_MODEL: _injectedLocalSearchDefaults.model || 'all-MiniLM-L6-v2',+ DEFAULT_LOCAL_SEARCH_CHUNK_SIZE: _injectedLocalSearchDefaults.chunk_size ?? 1000,+ DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP: _injectedLocalSearchDefaults.chunk_overlap ?? 200,+ DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE: _injectedLocalSearchDefaults.splitter_type || 'recursive',+ DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS: _injectedLocalSearchDefaults.text_separators || ["\n\n", "\n", ". ", " ", ""],+ DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC: _injectedLocalSearchDefaults.distance_metric || 'cosine',+ DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS: _injectedLocalSearchDefaults.normalize_vectors ?? true,+ DEFAULT_LOCAL_SEARCH_INDEX_TYPE: _injectedLocalSearchDefaults.index_type || 'flat',};}diff --git a/src/local_deep_research/web/static/js/embedding_settings.js b/src/local_deep_research/web/static/js/embedding_settings.jsindex cca88996ca..25d0b3204f 100644--- a/src/local_deep_research/web/static/js/embedding_settings.js+++ b/src/local_deep_research/web/static/js/embedding_settings.js@@ -16,6 +16,23 @@ let openAIEmbeddingBatchSizeAcceptedEditVersion = 0;const OPENAI_EMBEDDING_BATCH_SIZE_KEY = 'embeddings.openai.chunk_size';+/**+ * Helper to resolve centralized local search defaults from LDR_CONSTANTS or window.+ */+function getLocalSearchDefaults() {+ const constants = (typeof LDR_CONSTANTS !== 'undefined' ? LDR_CONSTANTS : (typeof window !== 'undefined' && window.LDR_CONSTANTS)) || {};+ return {+ provider: constants.DEFAULT_LOCAL_SEARCH_PROVIDER || 'sentence_transformers',+ model: constants.DEFAULT_LOCAL_SEARCH_MODEL || 'all-MiniLM-L6-v2',+ chunk_size: constants.DEFAULT_LOCAL_SEARCH_CHUNK_SIZE ?? 1000,+ chunk_overlap: constants.DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP ?? 200,+ splitter_type: constants.DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE || 'recursive',+ text_separators: constants.DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS || ["\n\n", "\n", ". ", " ", ""],+ distance_metric: constants.DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC || 'cosine',+ normalize_vectors: constants.DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS ?? true,+ index_type: constants.DEFAULT_LOCAL_SEARCH_INDEX_TYPE || 'flat',+ };+}// safeFetch/safeFetchWithAuth are now provided by utils/safe-fetch.js loaded in base.html// escapeHtml is the canonical window.escapeHtml from security/xss-protection.js// (loaded first via base.html). Do NOT reintroduce a local fallback — it would@@ -85,11 +102,14 @@ async function loadCurrentSettings() {if (data.success && data.settings) {const settings = data.settings;+ const defaults = getLocalSearchDefaults();// Set providerconst providerSelect = document.getElementById('embedding-provider');if (settings.embedding_provider) {providerSelect.value = settings.embedding_provider;+ } else if (defaults.provider) {+ providerSelect.value = defaults.provider;}// Update models for this provider@@ -100,28 +120,47 @@ async function loadCurrentSettings() {if (settings.embedding_model) {modelSelect.value = settings.embedding_model;updateModelDescription();+ } else if (defaults.model) {+ modelSelect.value = defaults.model;+ updateModelDescription();}- // Set chunk size and overlap- if (settings.chunk_size) {+ // Set chunk size and overlap. Use explicit null/undefined checks so+ // that a legitimate 0 overlap (or 0 chunk size, if ever allowed)+ // isn't dropped by JavaScript truthiness and silently leaves the+ // default in place. The string fields below keep their plain+ // truthy checks: their valid values are always non-empty strings.+ if (settings.chunk_size !== undefined && settings.chunk_size !== null) {document.getElementById('chunk-size').value = settings.chunk_size;+ } else if (defaults.chunk_size !== undefined) {+ document.getElementById('chunk-size').value = defaults.chunk_size;}- if (settings.chunk_overlap) {+ if (settings.chunk_overlap !== undefined && settings.chunk_overlap !== null) {document.getElementById('chunk-overlap').value = settings.chunk_overlap;+ } else if (defaults.chunk_overlap !== undefined) {+ document.getElementById('chunk-overlap').value = defaults.chunk_overlap;}// Set new advanced settingsif (settings.splitter_type) {document.getElementById('splitter-type').value = settings.splitter_type;+ } else if (defaults.splitter_type) {+ document.getElementById('splitter-type').value = defaults.splitter_type;}if (settings.distance_metric) {document.getElementById('distance-metric').value = settings.distance_metric;+ } else if (defaults.distance_metric) {+ document.getElementById('distance-metric').value = defaults.distance_metric;}if (settings.index_type) {document.getElementById('index-type').value = settings.index_type;+ } else if (defaults.index_type) {+ document.getElementById('index-type').value = defaults.index_type;}- if (settings.normalize_vectors !== undefined) {+ if (settings.normalize_vectors !== undefined && settings.normalize_vectors !== null) {document.getElementById('normalize-vectors').checked = settings.normalize_vectors;+ } else if (defaults.normalize_vectors !== undefined) {+ document.getElementById('normalize-vectors').checked = defaults.normalize_vectors;}if (settings.text_separators) {const textSepsEl = document.getElementById('text-separators');@@ -146,18 +185,26 @@ async function loadCurrentSettings() {// Store original values for change tracking (read from DOM after all fields are set)originalValues = {- 'local_search_embedding_provider': document.getElementById('embedding-provider').value,- 'local_search_embedding_model': document.getElementById('embedding-model').value,- 'local_search_chunk_size': parseInt(document.getElementById('chunk-size').value, 10) || 1000,- 'local_search_chunk_overlap': parseInt(document.getElementById('chunk-overlap').value, 10) || 200,- 'local_search_splitter_type': document.getElementById('splitter-type').value,- 'local_search_distance_metric': document.getElementById('distance-metric').value,- 'local_search_index_type': document.getElementById('index-type').value,+ 'local_search_embedding_provider': document.getElementById('embedding-provider').value || defaults.provider,+ 'local_search_embedding_model': document.getElementById('embedding-model').value || defaults.model,+ 'local_search_chunk_size': (function() {+ const el = document.getElementById('chunk-size');+ const v = parseInt(el.value, 10);+ return Number.isNaN(v) ? defaults.chunk_size : v;+ })(),+ 'local_search_chunk_overlap': (function() {+ const el = document.getElementById('chunk-overlap');+ const v = parseInt(el.value, 10);+ return Number.isNaN(v) ? defaults.chunk_overlap : v;+ })(),+ 'local_search_splitter_type': document.getElementById('splitter-type').value || defaults.splitter_type,+ 'local_search_distance_metric': document.getElementById('distance-metric').value || defaults.distance_metric,+ 'local_search_index_type': document.getElementById('index-type').value || defaults.index_type,'local_search_normalize_vectors': document.getElementById('normalize-vectors').checked,'local_search_text_separators': (function() {try {const val = document.getElementById('text-separators').value;- return val ? JSON.parse(val) : LDR_CONSTANTS.DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS;+ return val ? JSON.parse(val) : defaults.text_separators;}catch {return document.getElementById('text-separators').value;@@ -165,12 +212,13 @@ async function loadCurrentSettings() {})(),'embeddings.ollama.url': document.getElementById('ollama-url').value,'embeddings.ollama.num_ctx': (function() {- const v = parseInt(document.getElementById('ollama-num-ctx').value, 10);- return Number.isNaN(v) ? 8192 : v;+ const el = document.getElementById('ollama-num-ctx');+ const v = parseInt(el.value, 10);+ return Number.isNaN(v) ? parseInt(el.defaultValue, 10) : v;})(),[OPENAI_EMBEDDING_BATCH_SIZE_KEY]: (function() {- const value = document.getElementById('openai-embedding-batch-size').value;- return value === '' ? 5 : Number(value);+ const el = document.getElementById('openai-embedding-batch-size');+ return el.value === '' ? parseInt(el.defaultValue, 10) : Number(el.value);})()};@@ -190,13 +238,16 @@ function renderSavedDefaults(settings) {const container = document.getElementById('saved-default-settings');if (!container) return;+ const defaults = getLocalSearchDefaults();+// Get provider display nameconst providerLabels = {'sentence_transformers': 'Sentence Transformers (Local)','ollama': 'Ollama (Local)','openai': 'OpenAI API'};- const providerLabel = providerLabels[settings.embedding_provider] || settings.embedding_provider;+ const effectiveProvider = settings.embedding_provider || defaults.provider;+ const providerLabel = providerLabels[effectiveProvider] || effectiveProvider;// bearer:disable javascript_lang_dangerous_insert_htmlcontainer.innerHTML = `@@ -206,27 +257,27 @@ function renderSavedDefaults(settings) {</div><div class="ldr-info-item"><span class="ldr-info-label">Embedding Model:</span>- <span class="ldr-info-value">${escapeHtml(settings.embedding_model || '')}</span>+ <span class="ldr-info-value">${escapeHtml(settings.embedding_model || defaults.model)}</span></div><div class="ldr-info-item"><span class="ldr-info-label">Document Chunk Size:</span>- <span class="ldr-info-value">${escapeHtml(String(settings.chunk_size ?? 1000))} characters</span>+ <span class="ldr-info-value">${escapeHtml(String(settings.chunk_size ?? defaults.chunk_size))} characters</span></div><div class="ldr-info-item"><span class="ldr-info-label">Chunk Overlap:</span>- <span class="ldr-info-value">${escapeHtml(String(settings.chunk_overlap ?? 200))} characters</span>+ <span class="ldr-info-value">${escapeHtml(String(settings.chunk_overlap ?? defaults.chunk_overlap))} characters</span></div><div class="ldr-info-item"><span class="ldr-info-label">Splitter Type:</span>- <span class="ldr-info-value">${escapeHtml(settings.splitter_type || 'recursive')}</span>+ <span class="ldr-info-value">${escapeHtml(settings.splitter_type || defaults.splitter_type)}</span></div><div class="ldr-info-item"><span class="ldr-info-label">Distance Metric:</span>- <span class="ldr-info-value">${escapeHtml(settings.distance_metric || 'cosine')}</span>+ <span class="ldr-info-value">${escapeHtml(settings.distance_metric || defaults.distance_metric)}</span></div><div class="ldr-info-item"><span class="ldr-info-label">Index Type:</span>- <span class="ldr-info-value">${escapeHtml(settings.index_type || 'flat')}</span>+ <span class="ldr-info-value">${escapeHtml(settings.index_type || defaults.index_type)}</span></div>`;}@@ -308,13 +359,16 @@ function validateOpenAIEmbeddingBatchSize(el) {errorElement.textContent = '';const value = Number(rawValue);- if (Number.isInteger(value) && value >= 1) {+ // Source min from the HTML attribute so a future tweak (e.g. raising+ // min="1" to min="5") doesn't require a matching edit here.+ const min = parseInt(el.min, 10);+ if (Number.isInteger(value) && value >= min) {return true;}el.classList.add('ldr-field-invalid');el.setAttribute('aria-invalid', 'true');- errorElement.textContent = 'Enter a whole number of at least 1.';+ errorElement.textContent = `Enter a whole number of at least ${min}.`;errorElement.style.display = 'block';return false;}@@ -404,14 +458,24 @@ function refreshSavedDefaults() {try { textSeps = JSON.parse(document.getElementById('text-separators').value); }catch { textSeps = []; }+ const defaults = getLocalSearchDefaults();+renderSavedDefaults({- embedding_provider: document.getElementById('embedding-provider').value,- embedding_model: document.getElementById('embedding-model').value,- chunk_size: parseInt(document.getElementById('chunk-size').value, 10) || 1000,- chunk_overlap: parseInt(document.getElementById('chunk-overlap').value, 10) || 200,- splitter_type: document.getElementById('splitter-type').value,- distance_metric: document.getElementById('distance-metric').value,- index_type: document.getElementById('index-type').value,+ embedding_provider: document.getElementById('embedding-provider').value || defaults.provider,+ embedding_model: document.getElementById('embedding-model').value || defaults.model,+ chunk_size: (function() {+ const el = document.getElementById('chunk-size');+ const v = parseInt(el.value, 10);+ return Number.isNaN(v) ? defaults.chunk_size : v;+ })(),+ chunk_overlap: (function() {+ const el = document.getElementById('chunk-overlap');+ const v = parseInt(el.value, 10);+ return Number.isNaN(v) ? defaults.chunk_overlap : v;+ })(),+ splitter_type: document.getElementById('splitter-type').value || defaults.splitter_type,+ distance_metric: document.getElementById('distance-metric').value || defaults.distance_metric,+ index_type: document.getElementById('index-type').value || defaults.index_type,normalize_vectors: document.getElementById('normalize-vectors').checked,text_separators: textSeps});@@ -445,7 +509,12 @@ function attachAutoSaveListeners() {const chunkSizeEl = document.getElementById('chunk-size');function saveChunkSize() {const value = parseInt(chunkSizeEl.value, 10);- if (isNaN(value) || value < 100 || value > 5000) return;+ // Source min/max from the HTML attributes so a future HTML tweak+ // (e.g. raising max="5000" to max="10000") doesn't require a+ // matching edit here.+ const min = parseInt(chunkSizeEl.min, 10);+ const max = parseInt(chunkSizeEl.max, 10);+ if (isNaN(value) || value < min || value > max) return;const oldValue = originalValues['local_search_chunk_size'];saveSetting('local_search_chunk_size', value, 'Document chunk size', oldValue);}@@ -458,7 +527,10 @@ function attachAutoSaveListeners() {openAIEmbeddingBatchSizeEl.addEventListener('input', function() {const rawValue = openAIEmbeddingBatchSizeEl.value.trim();const value = Number(rawValue);- if (Number.isInteger(value) && value >= 1) {+ // Source min from the HTML attribute so a future tweak (e.g. raising+ // min="1" to min="5") doesn't require a matching edit here.+ const min = parseInt(openAIEmbeddingBatchSizeEl.min, 10);+ if (Number.isInteger(value) && value >= min) {openAIEmbeddingBatchSizeEditVersion += 1;}});@@ -506,7 +578,10 @@ function attachAutoSaveListeners() {const chunkOverlapEl = document.getElementById('chunk-overlap');function saveChunkOverlap() {const value = parseInt(chunkOverlapEl.value, 10);- if (isNaN(value) || value < 0 || value > 1000) return;+ // Source min/max from the HTML attributes (see saveChunkSize).+ const min = parseInt(chunkOverlapEl.min, 10);+ const max = parseInt(chunkOverlapEl.max, 10);+ if (isNaN(value) || value < min || value > max) return;const oldValue = originalValues['local_search_chunk_overlap'];saveSetting('local_search_chunk_overlap', value, 'Chunk overlap', oldValue);}@@ -613,9 +688,12 @@ function populateProviders() {providerSelect.appendChild(option);});- // Restore previous value if it exists+ // Restore previous value if it exists, or fall back to default provider, or first option+ const defaults = getLocalSearchDefaults();if (currentValue && Array.from(providerSelect.options).some(opt => opt.value === currentValue)) {providerSelect.value = currentValue;+ } else if (defaults.provider && Array.from(providerSelect.options).some(opt => opt.value === defaults.provider)) {+ providerSelect.value = defaults.provider;} else if (providerSelect.options.length > 0) {providerSelect.value = providerSelect.options[0].value;}@@ -685,9 +763,12 @@ function updateModelOptions() {}// Restore the previously selected model if it still exists in the rebuilt- // list; otherwise fall back to the first non-disabled option.+ // list; otherwise try default model, or fall back to the first non-disabled option.+ const defaults = getLocalSearchDefaults();if (previousValue && Array.from(modelSelect.options).some(opt => opt.value === previousValue && !opt.disabled)) {modelSelect.value = previousValue;+ } else if (defaults.model && Array.from(modelSelect.options).some(opt => opt.value === defaults.model && !opt.disabled)) {+ modelSelect.value = defaults.model;} else if (modelSelect.options.length > 0 && !modelSelect.options[0].disabled) {modelSelect.value = modelSelect.options[0].value;}@@ -1069,7 +1150,9 @@ async function loadOpenAIEmbeddingBatchSize(hydrationVersion) {const hasValidValue = data &&typeof data === 'object' &&Object.prototype.hasOwnProperty.call(data, 'value') &&- (data.value === null || (Number.isInteger(data.value) && data.value >= 1));+ // Source min from the HTML attribute so a future tweak (e.g. raising+ // min="1" to min="5") doesn't require a matching edit here.+ (data.value === null || (Number.isInteger(data.value) && data.value >= parseInt(document.getElementById('openai-embedding-batch-size').min, 10)));if (!hasValidValue ||hydrationVersion !== openAIEmbeddingBatchSizeHydrationVersion ||document.getElementById('embedding-provider').value !== 'openai') {diff --git a/src/local_deep_research/web/template_config.py b/src/local_deep_research/web/template_config.pyindex 56ed131730..5ea99cfcce 100644--- a/src/local_deep_research/web/template_config.py+++ b/src/local_deep_research/web/template_config.py@@ -82,6 +82,15 @@ class _LDRTemplates(Jinja2Templates):}context["research_terminal_states"] = [str(s) for s in terminal]from ..constants import (+ DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,+ DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,+ DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC,+ DEFAULT_LOCAL_SEARCH_INDEX_TYPE,+ DEFAULT_LOCAL_SEARCH_MODEL,+ DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS,+ DEFAULT_LOCAL_SEARCH_PROVIDER,+ DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE,+ DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS,HISTORY_LOGS_DEFAULT_LIMIT,HISTORY_LOGS_HARD_CAP,)@@ -90,6 +99,17 @@ class _LDRTemplates(Jinja2Templates):"default": HISTORY_LOGS_DEFAULT_LIMIT,"hard_cap": HISTORY_LOGS_HARD_CAP,}+ context["local_search_defaults"] = {+ "provider": DEFAULT_LOCAL_SEARCH_PROVIDER,+ "model": DEFAULT_LOCAL_SEARCH_MODEL,+ "chunk_size": DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,+ "chunk_overlap": DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,+ "splitter_type": DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE,+ "text_separators": list(DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS),+ "distance_metric": DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC,+ "normalize_vectors": DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS,+ "index_type": DEFAULT_LOCAL_SEARCH_INDEX_TYPE,+ }kwargs["context"] = context# Inject the app version for every render (main did this viadiff --git a/src/local_deep_research/web/templates/base.html b/src/local_deep_research/web/templates/base.htmlindex 4bd928e188..9c0b6c7dc2 100644--- a/src/local_deep_research/web/templates/base.html+++ b/src/local_deep_research/web/templates/base.html@@ -230,6 +230,7 @@window.RESEARCH_STATUS = Object.freeze({{ research_status_enum | tojson }});window.RESEARCH_TERMINAL_STATES = Object.freeze(new Set({{ research_terminal_states | tojson }}));window.LDR_LOG_LIMITS = Object.freeze({{ log_limits | tojson }});+ window.LDR_LOCAL_SEARCH_DEFAULTS = Object.freeze({{ local_search_defaults | tojson }});</script><!-- Constants and URL Configuration -->diff --git a/src/local_deep_research/web/templates/pages/embedding_settings.html b/src/local_deep_research/web/templates/pages/embedding_settings.htmlindex 59a51d7bc6..a8db2c7635 100644--- a/src/local_deep_research/web/templates/pages/embedding_settings.html+++ b/src/local_deep_research/web/templates/pages/embedding_settings.html@@ -128,12 +128,12 @@<div class="ldr-form-row"><div class="ldr-form-group ldr-col-md-6"><label for="chunk-size">{{ tooltip("Document Chunk Size", "Maximum size of each chunk. Larger values keep more context but reduce search precision; smaller values are more granular but may cut off important context.") }}</label>- <input type="number" id="chunk-size" class="ldr-form-control" value="1000" min="100" max="5000" step="100">+ <input type="number" id="chunk-size" class="ldr-form-control" value="{{ local_search_defaults.chunk_size }}" min="100" max="5000" step="100"><small class="ldr-form-text ldr-text-muted">Characters for recursive/semantic; tokens for token and sentence (sentence is capped by the tokenizer's max length).</small></div><div class="ldr-form-group ldr-col-md-6"><label for="chunk-overlap">{{ tooltip("Chunk Overlap", "Content shared between adjacent chunks to prevent important info from being cut at boundaries. Usually 10-20% of the chunk size.") }}</label>- <input type="number" id="chunk-overlap" class="ldr-form-control" value="200" min="0" max="1000" step="50">+ <input type="number" id="chunk-overlap" class="ldr-form-control" value="{{ local_search_defaults.chunk_overlap }}" min="0" max="1000" step="50"><small class="ldr-form-text ldr-text-muted">Ignored by the semantic splitter (always 0).</small></div></div>@@ -142,10 +142,10 @@<div class="ldr-form-group ldr-col-md-6"><label for="splitter-type">{{ tooltip("Text Splitter Type", "Method used to split documents into chunks.") }}</label><select id="splitter-type" class="ldr-form-control">- <option value="recursive">Recursive (Default - uses separators)</option>- <option value="token">Token-based (Good for LLM context)</option>- <option value="sentence">Sentence-based (Clean boundaries)</option>- <option value="semantic">Semantic (Smart grouping - slower)</option>+ <option value="recursive" {{ 'selected' if local_search_defaults.splitter_type == 'recursive' else '' }}>Recursive (Default - uses separators)</option>+ <option value="token" {{ 'selected' if local_search_defaults.splitter_type == 'token' else '' }}>Token-based (Good for LLM context)</option>+ <option value="sentence" {{ 'selected' if local_search_defaults.splitter_type == 'sentence' else '' }}>Sentence-based (Clean boundaries)</option>+ <option value="semantic" {{ 'selected' if local_search_defaults.splitter_type == 'semantic' else '' }}>Semantic (Smart grouping - slower)</option></select><small class="ldr-form-text ldr-text-muted">Recursive and semantic respect text separators; token and sentence ignore them.@@ -154,9 +154,9 @@<div class="ldr-form-group ldr-col-md-6"><label for="distance-metric">Distance Metric</label><select id="distance-metric" class="ldr-form-control">- <option value="cosine">Cosine Similarity (Recommended)</option>- <option value="l2">Euclidean Distance (L2)</option>- <option value="dot_product">Dot Product</option>+ <option value="cosine" {{ 'selected' if local_search_defaults.distance_metric == 'cosine' else '' }}>Cosine Similarity (Recommended)</option>+ <option value="l2" {{ 'selected' if local_search_defaults.distance_metric == 'l2' else '' }}>Euclidean Distance (L2)</option>+ <option value="dot_product" {{ 'selected' if local_search_defaults.distance_metric == 'dot_product' else '' }}>Dot Product</option></select><small class="ldr-form-text ldr-text-muted">Cosine similarity recommended for text embeddings@@ -165,9 +165,9 @@<div class="ldr-form-group ldr-col-md-6"><label for="index-type">{{ tooltip("Index Type", "Flat: exact but slow for large collections. HNSW: approximate but 50x faster for >10K docs. IVF: good balance for frequently updated collections.") }}</label><select id="index-type" class="ldr-form-control">- <option value="flat">Flat (Exact search, <10K docs)</option>- <option value="hnsw">HNSW (Fast, large collections)</option>- <option value="ivf">IVF (Balanced, updates)</option>+ <option value="flat" {{ 'selected' if local_search_defaults.index_type == 'flat' else '' }}>Flat (Exact search, <10K docs)</option>+ <option value="hnsw" {{ 'selected' if local_search_defaults.index_type == 'hnsw' else '' }}>HNSW (Fast, large collections)</option>+ <option value="ivf" {{ 'selected' if local_search_defaults.index_type == 'ivf' else '' }}>IVF (Balanced, updates)</option></select><small class="ldr-form-text ldr-text-muted">HNSW recommended for >10K documents (50-60× faster)@@ -177,7 +177,7 @@<div class="ldr-form-group"><label>- <input type="checkbox" id="normalize-vectors" checked>+ <input type="checkbox" id="normalize-vectors" {{ 'checked' if local_search_defaults.normalize_vectors else '' }}>Normalize vectors (L2)</label><small class="ldr-form-text ldr-text-muted" style="display: block; margin-left: 25px;">@@ -188,7 +188,7 @@<div class="ldr-form-group"><label for="text-separators">Text Separators (Advanced)</label><textarea id="text-separators" class="ldr-form-control" rows="3"- placeholder='["\n\n", "\n", ". ", " ", ""]'></textarea>+ placeholder='{{ local_search_defaults.text_separators | tojson }}'></textarea><small class="ldr-form-text ldr-text-muted">JSON array of separators. Default works for 80% of use cases. Used by recursive and semantic splitters only — token and sentence ignore this. For code, add language-specific separators like "\nclass", "\ndef".</small>diff --git a/src/local_deep_research/web_search_engines/engines/local_embedding_manager.py b/src/local_deep_research/web_search_engines/engines/local_embedding_manager.pyindex 834ec3beb2..652e0c1248 100644--- a/src/local_deep_research/web_search_engines/engines/local_embedding_manager.py+++ b/src/local_deep_research/web_search_engines/engines/local_embedding_manager.py@@ -4,6 +4,10 @@ from typing import Any, Dict, Optionalfrom ...database.models.library import DocumentChunkfrom ...database.session_context import get_user_db_session+from ...constants import (+ DEFAULT_LOCAL_SEARCH_MODEL,+ DEFAULT_LOCAL_SEARCH_PROVIDER,+)from ...security.log_sanitizer import scrub_errorfrom ...security.secure_logging import loggerfrom ...utilities.url_utils import normalize_url@@ -14,9 +18,9 @@ class LocalEmbeddingManager:def __init__(self,- embedding_model: str = "all-MiniLM-L6-v2",+ embedding_model: str = DEFAULT_LOCAL_SEARCH_MODEL,embedding_device: str = "cpu",- embedding_model_type: str = "sentence_transformers", # or 'ollama'+ embedding_model_type: str = DEFAULT_LOCAL_SEARCH_PROVIDER, # or 'ollama'ollama_base_url: Optional[str] = None,settings_snapshot: Optional[Dict[str, Any]] = None,):diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_library.py b/src/local_deep_research/web_search_engines/engines/search_engine_library.pyindex 2294155a38..99050434be 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_library.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_library.py@@ -9,7 +9,13 @@ from typing import List, Dict, Any, Optionalfrom ..search_engine_base import BaseSearchEngine, Exposure, Sensitivityfrom ...security.secure_logging import logger-from ...constants import SNIPPET_LENGTH_LONG+from ...constants import (+ DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,+ DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,+ DEFAULT_LOCAL_SEARCH_MODEL,+ DEFAULT_LOCAL_SEARCH_PROVIDER,+ SNIPPET_LENGTH_LONG,+)from ...research_library.services.library_rag_service import LibraryRAGServicefrom ...research_library.services.library_service import LibraryServicefrom ...config.thread_settings import get_setting_from_snapshot@@ -87,22 +93,22 @@ class LibraryRAGSearchEngine(BaseSearchEngine):# itself (the misplaced "default").self.embedding_model = get_setting_from_snapshot("local_search_embedding_model",- default="all-MiniLM-L6-v2",+ default=DEFAULT_LOCAL_SEARCH_MODEL,settings_snapshot=settings_snapshot,)self.embedding_provider = get_setting_from_snapshot("local_search_embedding_provider",- default="sentence_transformers",+ default=DEFAULT_LOCAL_SEARCH_PROVIDER,settings_snapshot=settings_snapshot,)self.chunk_size = get_setting_from_snapshot("local_search_chunk_size",- default=1000,+ default=DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,settings_snapshot=settings_snapshot,)self.chunk_overlap = get_setting_from_snapshot("local_search_chunk_overlap",- default=200,+ default=DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,settings_snapshot=settings_snapshot,)diff --git a/tests/embeddings/test_text_splitter_registry.py b/tests/embeddings/test_text_splitter_registry.pyindex d97923cf14..211b674739 100644--- a/tests/embeddings/test_text_splitter_registry.py+++ b/tests/embeddings/test_text_splitter_registry.py@@ -118,6 +118,9 @@ class TestGetTextSplitterRecursive:def test_get_text_splitter_recursive_default_separators(self):"""Test recursive splitter uses default separators."""+ from local_deep_research.constants import (+ DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS,+ )from local_deep_research.embeddings.splitters.text_splitter_registry import (get_text_splitter,)@@ -125,8 +128,7 @@ class TestGetTextSplitterRecursive:splitter = get_text_splitter(splitter_type="recursive")# Default separators- assert "\n\n" in splitter._separators- assert "\n" in splitter._separators+ assert splitter._separators == DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORSclass TestGetTextSplitterToken:diff --git a/tests/js/collection-details.test.js b/tests/js/collection-details.test.jsindex 4ae0fe4dc0..e7f9048fde 100644--- a/tests/js/collection-details.test.js+++ b/tests/js/collection-details.test.js@@ -38,7 +38,7 @@ beforeAll(async () => {window.RESEARCH_TERMINAL_STATES = new Set(['completed', 'suspended', 'failed', 'error', 'cancelled',]);-+ await import('@js/security/xss-protection.js');await import('@js/config/constants.js');await import('@js/collection_details.js');getProviderLabel = window.getProviderLabel;@@ -283,3 +283,55 @@ describe('startPolling terminal-status fallback', () => {expect(pollingBlock[0]).toMatch(/hideProgressUI\(\)/);});});++describe('displayCollectionEmbeddingSettings', () => {+ let container;++ beforeEach(() => {+ document.body.innerHTML = '<div id="collection-embedding-info"></div>';+ container = document.getElementById('collection-embedding-info');+ });++ it('renders chunk_overlap: 0 without collapsing to "Not set"', () => {+ window.setCollectionDataForTesting({+ embedding_model: 'all-MiniLM-L6-v2',+ embedding_model_type: 'sentence_transformers',+ chunk_size: 1000,+ chunk_overlap: 0,+ });++ window.displayCollectionEmbeddingSettings();++ expect(container.textContent).toContain('Chunk Overlap:');+ expect(container.textContent).toContain('0 characters');+ expect(container.textContent).not.toContain('Not set');+ });++ it('renders chunk_overlap: null as "Not set"', () => {+ window.setCollectionDataForTesting({+ embedding_model: 'all-MiniLM-L6-v2',+ embedding_model_type: 'sentence_transformers',+ chunk_size: 1000,+ chunk_overlap: null,+ });++ window.displayCollectionEmbeddingSettings();++ expect(container.textContent).toContain('Chunk Overlap:');+ expect(container.textContent).toContain('Not set');+ });++ it('renders chunk_size: 0 without collapsing to "Not set"', () => {+ window.setCollectionDataForTesting({+ embedding_model: 'all-MiniLM-L6-v2',+ embedding_model_type: 'sentence_transformers',+ chunk_size: 0,+ chunk_overlap: 0,+ });++ window.displayCollectionEmbeddingSettings();++ expect(container.textContent).toContain('Chunk Size:');+ expect(container.textContent).toContain('0 characters');+ });+});diff --git a/tests/js/config/constants.test.js b/tests/js/config/constants.test.jsindex 5c4d5f83f8..17fc65be2d 100644--- a/tests/js/config/constants.test.js+++ b/tests/js/config/constants.test.js@@ -26,12 +26,35 @@ import '@js/config/constants.js';const RS = window.ResearchStates;+import localSearchSchema from '../../../src/local_deep_research/defaults/settings_local_search.json';+describe('LDR_CONSTANTS', () => {it('defines SEARCH_MODE values', () => {expect(window.LDR_CONSTANTS.SEARCH_MODE.HYBRID).toBe('hybrid');expect(window.LDR_CONSTANTS.SEARCH_MODE.TEXT).toBe('text');expect(window.LDR_CONSTANTS.SEARCH_MODE.SEMANTIC).toBe('semantic');});++ it('defines DEFAULT_LOCAL_SEARCH values matching settings_local_search.json', () => {+ expect(window.LDR_CONSTANTS.DEFAULT_LOCAL_SEARCH_PROVIDER)+ .toBe(localSearchSchema.local_search_embedding_provider.value);+ expect(window.LDR_CONSTANTS.DEFAULT_LOCAL_SEARCH_MODEL)+ .toBe(localSearchSchema.local_search_embedding_model.value);+ expect(window.LDR_CONSTANTS.DEFAULT_LOCAL_SEARCH_CHUNK_SIZE)+ .toBe(localSearchSchema.local_search_chunk_size.value);+ expect(window.LDR_CONSTANTS.DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP)+ .toBe(localSearchSchema.local_search_chunk_overlap.value);+ expect(window.LDR_CONSTANTS.DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE)+ .toBe(localSearchSchema.local_search_splitter_type.value);+ expect(window.LDR_CONSTANTS.DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS)+ .toEqual(localSearchSchema.local_search_text_separators.value);+ expect(window.LDR_CONSTANTS.DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC)+ .toBe(localSearchSchema.local_search_distance_metric.value);+ expect(window.LDR_CONSTANTS.DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS)+ .toBe(localSearchSchema.local_search_normalize_vectors.value);+ expect(window.LDR_CONSTANTS.DEFAULT_LOCAL_SEARCH_INDEX_TYPE)+ .toBe(localSearchSchema.local_search_index_type.value);+ });});describe('ResearchStates', () => {diff --git a/tests/js/embedding-settings-zero-value.test.js b/tests/js/embedding-settings-zero-value.test.jsnew file mode 100644index 0000000000..456c02cb63--- /dev/null+++ b/tests/js/embedding-settings-zero-value.test.js@@ -0,0 +1,454 @@+/**+ * Regression tests for the chunk-overlap=0 truthy-check bug.+ *+ * The page used to write `if (settings.chunk_overlap) { ... }` to hydrate+ * the chunk-overlap input from `/library/api/rag/settings`. Because `0`+ * is falsy in JavaScript, a saved overlap of 0 was dropped and the HTML+ * default (value="200") leaked through, making the form lie to the user.+ * The same `value || default` collapse existed in the change-tracking+ * `originalValues` snapshot and in `refreshSavedDefaults`, so an unchanged+ * blur could spuriously fire a save and the "Saved Defaults" panel could+ * flash 200 after a save of 0.+ *+ * These tests exercise the literal production hydration code against a+ * DOM constructed from `embedding_settings.html` and stub the API surface+ * via `safeFetchWithAuth`, so any regression of the truthy-check pattern+ * for numeric settings will fail loudly.+ *+ * Note: the categorical string fields (provider, model, splitter_type,+ * distance_metric, index_type) keep their plain `if (settings.X)` truthy+ * checks because their valid values are always non-empty strings —+ * `0`/`""`/`false` are not legitimate saved values for them, so the+ * narrower fix is correct. `normalize_vectors` already used+ * `!== undefined`. Only the numeric fields are vulnerable.+ */++// --- Per-test mutable API response ------------------------------------------+const apiState = {+ ragSettings: null,+ ollamaUrl: '',+ ollamaNumCtx: 8192,+ openaiBatchSize: 5,+ putCalls: [],+};++function jsonResponse(body) {+ return {+ ok: true,+ status: 200,+ json: () => Promise.resolve(body),+ };+}++globalThis.safeFetchWithAuth = vi.fn(async (url, opts = {}) => {+ if (opts.method === 'PUT' && url.startsWith('/settings/api/')) {+ const body = opts.body ? JSON.parse(opts.body) : {};+ apiState.putCalls.push({ url, body });+ const key = url.replace(/^\/settings\/api\//, '');+ if (key === 'embeddings.ollama.url') apiState.ollamaUrl = body.value;+ if (key === 'embeddings.ollama.num_ctx') apiState.ollamaNumCtx = body.value;+ if (key === 'embeddings.openai.chunk_size') apiState.openaiBatchSize = body.value;+ return jsonResponse({ success: true });+ }+ if (url === '/library/api/rag/models') {+ return jsonResponse({+ success: true,+ provider_options: [+ { value: 'openai', label: 'OpenAI', available: true },+ { value: 'sentence_transformers', label: 'ST', available: true },+ { value: 'ollama', label: 'Ollama', available: true },+ ],+ providers: {+ openai: [+ { value: 'text-embedding-nomic-embed-text-v1.5@q8_0', label: 'nomic', is_embedding: true },+ ],+ sentence_transformers: [+ { value: 'all-MiniLM-L6-v2', label: 'mini', is_embedding: true },+ ],+ ollama: [+ { value: 'nomic-embed-text', label: 'nomic-embed', is_embedding: true },+ ],+ },+ });+ }+ if (url === '/library/api/rag/settings') {+ return jsonResponse({ success: true, settings: apiState.ragSettings });+ }+ if (url === '/settings/api/embeddings.ollama.url') {+ return jsonResponse({ value: apiState.ollamaUrl });+ }+ if (url === '/settings/api/embeddings.ollama.num_ctx') {+ return jsonResponse({ value: apiState.ollamaNumCtx });+ }+ if (url === '/settings/api/embeddings.openai.chunk_size') {+ return jsonResponse({ value: apiState.openaiBatchSize });+ }+ return jsonResponse({ success: true });+});++// --- DOM scaffolding matching the production template ----------------------+function buildDom() {+ document.body.innerHTML = `+ <div class="ldr-library-container">+ <div id="saved-default-settings"></div>+ <select id="embedding-provider"></select>+ <select id="embedding-model"></select>+ <input type="number" id="chunk-size" value="1000">+ <input type="number" id="chunk-overlap" value="200">+ <select id="splitter-type"></select>+ <select id="distance-metric"></select>+ <select id="index-type"></select>+ <input type="checkbox" id="normalize-vectors">+ <textarea id="text-separators"></textarea>+ <div id="ollama-url-group"><input id="ollama-url"></div>+ <div id="ollama-num-ctx-group"><input type="number" id="ollama-num-ctx" value="8192"></div>+ <div id="openai-embedding-batch-size-group">+ <input type="number" id="openai-embedding-batch-size" value="5">+ <div id="openai-embedding-batch-size-error"></div>+ </div>+ <button id="test-config-btn"></button>+ <div id="provider-info"></div>+ <div id="model-description"></div>+ <div id="text-separators-error"></div>+ </div>+ `;+ for (const id of ['embedding-provider', 'splitter-type', 'distance-metric', 'index-type']) {+ document.getElementById(id).innerHTML = `+ <option value="openai">OpenAI</option>+ <option value="sentence_transformers">Sentence Transformers</option>+ <option value="ollama">Ollama</option>+ <option value="recursive">Recursive</option>+ <option value="token">Token</option>+ <option value="sentence">Sentence</option>+ <option value="semantic">Semantic</option>+ <option value="cosine">Cosine</option>+ <option value="l2">Euclidean</option>+ <option value="dot_product">Dot Product</option>+ <option value="flat">Flat</option>+ <option value="hnsw">HNSW</option>+ <option value="ivf">IVF</option>+ `;+ }+ document.getElementById('embedding-model').innerHTML = `+ <option value="all-MiniLM-L6-v2">all-MiniLM-L6-v2</option>+ <option value="text-embedding-nomic-embed-text-v1.5@q8_0">nomic</option>+ <option value="nomic-embed-text">nomic-embed</option>+ `;+}++function defaultSettings(overrides = {}) {+ return {+ embedding_provider: 'openai',+ embedding_model: 'text-embedding-nomic-embed-text-v1.5@q8_0',+ chunk_size: 1000,+ chunk_overlap: 0, // the bug case+ splitter_type: 'token',+ distance_metric: 'cosine',+ index_type: 'flat',+ normalize_vectors: true,+ text_separators: ['\n\n', '\n', '. ', ' ', ''],+ ...overrides,+ };+}++// --- Module setup ----------------------------------------------------------+globalThis.window.escapeHtml = (s) => String(s ?? '');++// Re-import the module on every reload so module-level state+// (`autoSaveListenersAttached`, `originalValues`, `providerOptions`,+// `availableModels`) is reset to a fresh page load. Without this the+// guard at the top of `attachAutoSaveListeners()` short-circuits on+// subsequent reloads and no event listeners are wired up.+async function loadModuleFresh() {+ vi.resetModules();+ // eslint-disable-next-line no-unsanitized/method+ return import('@js/embedding_settings.js?ts=' + Date.now() + Math.random());+}++async function reloadPage() {+ buildDom();+ await loadModuleFresh();+ document.dispatchEvent(new Event('DOMContentLoaded'));+ // Let the awaited chain drain: loadAvailableModels -> loadCurrentSettings+ // -> loadOllamaUrl -> loadOllamaNumCtx -> toggleProviderFields ->+ // renderSavedDefaults -> attachAutoSaveListeners.+ for (let i = 0; i < 25; i++) {+ await new Promise((r) => setTimeout(r, 0));+ }+}++beforeEach(async () => {+ apiState.ragSettings = defaultSettings();+ apiState.putCalls.length = 0;+ await reloadPage();+});++afterEach(() => {+ vi.restoreAllMocks();+ buildDom();+});++// ============================================================================+// Bug-class: settings.chunk_overlap === 0 must populate the input.+// ============================================================================+describe('loadCurrentSettings — numeric settings hydrate inputs', () => {+ it('chunk_overlap=0: input reflects 0, not the HTML default of 200', () => {+ apiState.ragSettings = defaultSettings({ chunk_overlap: 0 });+ buildDom();+ document.dispatchEvent(new Event('DOMContentLoaded'));+ return new Promise((r) => setTimeout(r, 0))+ .then(() => new Promise((r) => setTimeout(r, 0)))+ .then(() => {+ const overlap = document.getElementById('chunk-overlap');+ expect(overlap.value).toBe('0');+ expect(Number(overlap.value)).toBe(0);+ });+ });++ it('chunk_overlap=200: input reflects 200 (no regression)', () => {+ apiState.ragSettings = defaultSettings({ chunk_overlap: 200 });+ buildDom();+ document.dispatchEvent(new Event('DOMContentLoaded'));+ return new Promise((r) => setTimeout(r, 0))+ .then(() => new Promise((r) => setTimeout(r, 0)))+ .then(() => {+ expect(document.getElementById('chunk-overlap').value).toBe('200');+ });+ });++ it('chunk_overlap missing from API: input keeps the HTML default of 200', () => {+ const settings = defaultSettings();+ delete settings.chunk_overlap;+ apiState.ragSettings = settings;+ buildDom();+ document.dispatchEvent(new Event('DOMContentLoaded'));+ return new Promise((r) => setTimeout(r, 0))+ .then(() => new Promise((r) => setTimeout(r, 0)))+ .then(() => {+ expect(document.getElementById('chunk-overlap').value).toBe('200');+ });+ });++ it('chunk_overlap=null from API: input keeps the HTML default of 200', () => {+ apiState.ragSettings = defaultSettings({ chunk_overlap: null });+ buildDom();+ document.dispatchEvent(new Event('DOMContentLoaded'));+ return new Promise((r) => setTimeout(r, 0))+ .then(() => new Promise((r) => setTimeout(r, 0)))+ .then(() => {+ expect(document.getElementById('chunk-overlap').value).toBe('200');+ });+ });++ it('chunk_size=0: input reflects 0 (defensive parity with chunk_overlap)', () => {+ apiState.ragSettings = defaultSettings({ chunk_size: 0 });+ buildDom();+ document.dispatchEvent(new Event('DOMContentLoaded'));+ return new Promise((r) => setTimeout(r, 0))+ .then(() => new Promise((r) => setTimeout(r, 0)))+ .then(() => {+ expect(document.getElementById('chunk-size').value).toBe('0');+ });+ });+});++// ============================================================================+// Categorical string fields keep their truthy checks (they're never falsy).+// ============================================================================+describe('loadCurrentSettings — categorical fields round-trip correctly', () => {+ it('provider/model/splitter/distance/index round-trip through truthy check', () => {+ apiState.ragSettings = defaultSettings({+ embedding_provider: 'sentence_transformers',+ embedding_model: 'all-MiniLM-L6-v2',+ splitter_type: 'semantic',+ distance_metric: 'l2',+ index_type: 'hnsw',+ });+ buildDom();+ document.dispatchEvent(new Event('DOMContentLoaded'));+ return new Promise((r) => setTimeout(r, 0))+ .then(() => new Promise((r) => setTimeout(r, 0)))+ .then(() => {+ expect(document.getElementById('embedding-provider').value).toBe('sentence_transformers');+ expect(document.getElementById('embedding-model').value).toBe('all-MiniLM-L6-v2');+ expect(document.getElementById('splitter-type').value).toBe('semantic');+ expect(document.getElementById('distance-metric').value).toBe('l2');+ expect(document.getElementById('index-type').value).toBe('hnsw');+ });+ });++ it('normalize_vectors=false: checkbox correctly unchecked', () => {+ apiState.ragSettings = defaultSettings({ normalize_vectors: false });+ buildDom();+ document.dispatchEvent(new Event('DOMContentLoaded'));+ return new Promise((r) => setTimeout(r, 0))+ .then(() => new Promise((r) => setTimeout(r, 0)))+ .then(() => {+ expect(document.getElementById('normalize-vectors').checked).toBe(false);+ });+ });+});++// ============================================================================+// Change-tracking: originalValues snapshot must preserve 0 so an unchanged+// blur is correctly detected as a no-op.+// ============================================================================+describe('change-tracking — originalValues snapshot preserves 0', () => {+ it('blurring the chunk-overlap input without changing it does NOT PUT', async () => {+ // Page loaded in beforeEach with chunk_overlap=0; input shows "0".+ const overlap = document.getElementById('chunk-overlap');+ expect(overlap.value).toBe('0');++ const baselinePuts = apiState.putCalls.filter((c) =>+ c.url === '/settings/api/local_search_chunk_overlap'+ ).length;++ overlap.focus();+ overlap.dispatchEvent(new Event('blur'));+ await new Promise((r) => setTimeout(r, 300));++ const afterPuts = apiState.putCalls.filter((c) =>+ c.url === '/settings/api/local_search_chunk_overlap'+ ).length;+ expect(afterPuts).toBe(baselinePuts);+ });++ it('blurring the chunk-size input without changing it does NOT PUT', async () => {+ const size = document.getElementById('chunk-size');+ expect(size.value).toBe('1000');++ const baselinePuts = apiState.putCalls.filter((c) =>+ c.url === '/settings/api/local_search_chunk_size'+ ).length;++ size.focus();+ size.dispatchEvent(new Event('blur'));+ await new Promise((r) => setTimeout(r, 300));++ const afterPuts = apiState.putCalls.filter((c) =>+ c.url === '/settings/api/local_search_chunk_size'+ ).length;+ expect(afterPuts).toBe(baselinePuts);+ });++ it('listener is actually attached: a real change DOES PUT (sanity check)', async () => {+ // Catches a broken test setup where the listener was never wired,+ // which would make the no-op tests above false-pass.+ const overlap = document.getElementById('chunk-overlap');+ expect(overlap.value).toBe('0');++ apiState.putCalls.length = 0;+ overlap.focus();+ overlap.value = '75';+ overlap.dispatchEvent(new Event('blur'));+ await new Promise((r) => setTimeout(r, 300));++ const changePuts = apiState.putCalls.filter((c) =>+ c.url === '/settings/api/local_search_chunk_overlap'+ );+ expect(changePuts).toHaveLength(1);+ expect(changePuts[0].body.value).toBe(75);+ });+});++// ============================================================================+// Source-code guard: the truthy-collapse pattern must not regress.+// ============================================================================+describe('source-code guard against truthy-check regression', () => {+ const { readFileSync } = require('node:fs');+ const { resolve } = require('node:path');+ const SRC = readFileSync(+ resolve(+ __dirname,+ '../../src/local_deep_research/web/static/js/embedding_settings.js',+ ),+ 'utf8',+ );++ it('loadCurrentSettings hydrates chunk_size / chunk_overlap via nullish check', () => {+ const start = SRC.indexOf('async function loadCurrentSettings');+ const end = SRC.indexOf('async function renderSavedDefaults');+ const body = start >= 0 && end > start ? SRC.slice(start, end) : SRC;+ // The numeric fields that have a legitimate 0 value MUST use the+ // nullish form — a re-introduction of `if (settings.chunk_overlap)`+ // is the original bug.+ expect(body).not.toMatch(/if\s*\(\s*settings\.chunk_overlap\s*\)/);+ expect(body).not.toMatch(/if\s*\(\s*settings\.chunk_size\s*\)/);+ });++ it('categorical fields keep their truthy check (they\'re never falsy)', () => {+ // Documenting the intentional asymmetry: the categorical fields+ // use `if (settings.X)` because valid values are non-empty+ // strings. A future refactor that switches them to nullish+ // checks is fine (and would make the test in the previous+ // block cover them) but flipping them BACK to truthy while also+ // changing the schema to allow empty values would re-introduce+ // the bug class. Pin the intent here.+ const start = SRC.indexOf('async function loadCurrentSettings');+ const end = SRC.indexOf('async function renderSavedDefaults');+ const body = start >= 0 && end > start ? SRC.slice(start, end) : SRC;+ expect(body).toMatch(/if\s*\(\s*settings\.embedding_provider\s*\)/);+ expect(body).toMatch(/if\s*\(\s*settings\.embedding_model\s*\)/);+ expect(body).toMatch(/if\s*\(\s*settings\.splitter_type\s*\)/);+ expect(body).toMatch(/if\s*\(\s*settings\.distance_metric\s*\)/);+ expect(body).toMatch(/if\s*\(\s*settings\.index_type\s*\)/);+ expect(body).toMatch(/if\s*\(\s*settings\.text_separators\s*\)/);+ });++ it('originalValues / refreshSavedDefaults do not use `||` as a parseInt fallback (the bug class)', () => {+ // The bug is `parseInt(x) || Y` — parseInt("0") is 0, and `0 || Y`+ // evaluates to Y, dropping the legitimate 0. The fix uses+ // `Number.isNaN(v) ? Y : v` instead.+ //+ // The regex matches `parseInt...||` on the same line, requiring the+ // `||` to come AFTER parseInt (not before, which is the common shape+ // of unrelated `data.value === null || (...)` checks).+ const offendingLines = SRC.split('\n').filter(+ (line) => /parseInt[^\n]*\|\|/.test(line),+ );+ expect(offendingLines).toEqual([]);+ });++ it('renderSavedDefaults does not hardcode categorical fallback strings (HTML is the source)', () => {+ // The categorical fallbacks ('recursive', 'cosine', 'flat') must come+ // from the <select>'s first option, not from a hardcoded literal.+ // If someone changes the HTML default to a new value, the JS fallback+ // should follow automatically — otherwise the saved-defaults panel+ // could lie about the actual default.+ //+ // Extract renderSavedDefaults function body so we don't catch the+ // same string literals used elsewhere (e.g. in tests or comments).+ const start = SRC.indexOf('function renderSavedDefaults(');+ if (start < 0) throw new Error('renderSavedDefaults not found');+ let depth = 0;+ let end = start;+ for (let i = start; i < SRC.length; i++) {+ if (SRC[i] === '{') depth++;+ else if (SRC[i] === '}') {+ depth--;+ if (depth === 0) {+ end = i + 1;+ break;+ }+ }+ }+ const body = SRC.slice(start, end);++ // `|| 'recursive'`, `|| "cosine"`, `|| 'flat'` are the bug pattern.+ expect(body).not.toMatch(/\|\|\s*['"]recursive['"]/);+ expect(body).not.toMatch(/\|\|\s*['"]cosine['"]/);+ expect(body).not.toMatch(/\|\|\s*['"]flat['"]/);+ });++ it('ollama.num_ctx and openai batch size use HTML defaultValue, not hardcoded literals', () => {+ // The numeric fallbacks (8192, 5) must come from the HTML defaultValue,+ // not from a hardcoded literal. The previous bug had similar+ // hardcoded values for chunk_size / chunk_overlap — keep that pattern+ // consistent across all settings.+ const start = SRC.indexOf('originalValues = {');+ const end = SRC.indexOf('};', start) + 2;+ const body = SRC.slice(start, end);+ expect(body).not.toMatch(/\)\s*:\s*8192/);+ expect(body).not.toMatch(/\)\s*:\s*5/);+ });+});diff --git a/tests/research_library/conftest.py b/tests/research_library/conftest.pyindex 07cc320f17..457152b160 100644--- a/tests/research_library/conftest.py+++ b/tests/research_library/conftest.py@@ -12,6 +12,12 @@ import pytestfrom sqlalchemy import create_enginefrom sqlalchemy.orm import Session, sessionmaker+from local_deep_research.constants import (+ DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,+ DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,+ DEFAULT_LOCAL_SEARCH_MODEL,+ DEFAULT_LOCAL_SEARCH_PROVIDER,+)from local_deep_research.database.models import Basefrom local_deep_research.database.models.library import (Collection,@@ -307,10 +313,10 @@ def mock_settings_manager(mocker):mock.get_setting.side_effect = lambda key, default=None: {"research_library.storage_path": "/tmp/test_library","search.engine.web.semantic_scholar.api_key": None,- "local_search_embedding_model": "all-MiniLM-L6-v2",- "local_search_embedding_provider": "sentence_transformers",- "local_search_chunk_size": 1000,- "local_search_chunk_overlap": 200,+ "local_search_embedding_model": DEFAULT_LOCAL_SEARCH_MODEL,+ "local_search_embedding_provider": DEFAULT_LOCAL_SEARCH_PROVIDER,+ "local_search_chunk_size": DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,+ "local_search_chunk_overlap": DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,}.get(key, default)return mockdiff --git a/tests/research_library/services/test_library_rag_service.py b/tests/research_library/services/test_library_rag_service.pyindex 83e74de903..686e3edf48 100644--- a/tests/research_library/services/test_library_rag_service.py+++ b/tests/research_library/services/test_library_rag_service.py@@ -55,6 +55,14 @@ class TestLibraryRAGServiceInit:return_value=mock_integrity,)+ from local_deep_research.constants import (+ DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,+ DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,+ DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC,+ DEFAULT_LOCAL_SEARCH_MODEL,+ DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS,+ DEFAULT_LOCAL_SEARCH_PROVIDER,+ )from local_deep_research.research_library.services.library_rag_service import (LibraryRAGService,)@@ -62,12 +70,14 @@ class TestLibraryRAGServiceInit:service = LibraryRAGService(username="test_user")assert service.username == "test_user"- assert service.embedding_model == "all-MiniLM-L6-v2"- assert service.embedding_provider == "sentence_transformers"- assert service.chunk_size == 1000- assert service.chunk_overlap == 200- assert service.distance_metric == "cosine"- assert service.normalize_vectors is True+ assert service.embedding_model == DEFAULT_LOCAL_SEARCH_MODEL+ assert service.embedding_provider == DEFAULT_LOCAL_SEARCH_PROVIDER+ assert service.chunk_size == DEFAULT_LOCAL_SEARCH_CHUNK_SIZE+ assert service.chunk_overlap == DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP+ assert service.distance_metric == DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC+ assert (+ service.normalize_vectors == DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS+ )def test_init_with_custom_parameters(self, mocker):"""Initializes with custom parameters."""diff --git a/tests/research_library/services/test_library_rag_service_coverage.py b/tests/research_library/services/test_library_rag_service_coverage.pyindex fd59e779bd..69b8a6b922 100644--- a/tests/research_library/services/test_library_rag_service_coverage.py+++ b/tests/research_library/services/test_library_rag_service_coverage.py@@ -18,6 +18,15 @@ from unittest.mock import MagicMock, patchimport pytest+from local_deep_research.constants import (+ DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,+ DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,+ DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC,+ DEFAULT_LOCAL_SEARCH_INDEX_TYPE,+ DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS,+ DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE,+ DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS,+)from local_deep_research.database.models.library import RAGIndexStatus# ---------------------------------------------------------------------------@@ -79,16 +88,16 @@ class TestGetIndexHash:svc = _make_service()h = svc._get_index_hash("c", "m", "p")identity = {- "chunk_overlap": 200,- "chunk_size": 1000,+ "chunk_overlap": DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,+ "chunk_size": DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,"collection_name": "c",- "distance_metric": "cosine",+ "distance_metric": DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC,"embedding_model": "m","embedding_provider": "p",- "index_type": "flat",- "normalize_vectors": True,- "splitter_type": "recursive",- "text_separators": ["\n\n", "\n", ". ", " ", ""],+ "index_type": DEFAULT_LOCAL_SEARCH_INDEX_TYPE,+ "normalize_vectors": DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS,+ "splitter_type": DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE,+ "text_separators": DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS,}expected = hashlib.sha256(json.dumps(diff --git a/tests/research_library/services/test_rag_service_factory.py b/tests/research_library/services/test_rag_service_factory.pyindex 050281464d..e67d025d9a 100644--- a/tests/research_library/services/test_rag_service_factory.py+++ b/tests/research_library/services/test_rag_service_factory.py@@ -12,7 +12,10 @@ from local_deep_research.database.models.library import (Collection,EmbeddingProvider,)-from local_deep_research.constants import DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS+from local_deep_research.constants import (+ DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS,+ DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS,+)from local_deep_research.research_library.services.rag_service_factory import (_get_default_text_separators,get_rag_service,@@ -40,9 +43,8 @@ def mock_settings():"local_search_splitter_type": "recursive","local_search_text_separators": None,"local_search_distance_metric": "cosine",- "local_search_index_type": "flat",+ "local_search_normalize_vectors": True,}.get(key, default)- mgr.get_bool_setting.return_value = Truereturn mgr@@ -131,9 +133,28 @@ class TestGetRagServiceDefaults:assert kwargs["embedding_provider"] == "sentence_transformers"assert kwargs["chunk_size"] == 1000assert kwargs["chunk_overlap"] == 200+ assert kwargs["normalize_vectors"] is Trueassert kwargs["db_password"] is Noneassert service is mock_rag_cls.return_value+ def test_chunk_overlap_zero_preserved(self, mock_db_session, mock_rag_cls):+ """When local_search_chunk_overlap is 0, 0 must not collapse to 200."""+ mgr = MagicMock()+ mgr.get_setting.side_effect = lambda key, default=None: {+ "local_search_embedding_model": "all-MiniLM-L6-v2",+ "local_search_embedding_provider": "sentence_transformers",+ "local_search_chunk_size": 1000,+ "local_search_chunk_overlap": 0,+ "local_search_splitter_type": "recursive",+ "local_search_text_separators": None,+ "local_search_distance_metric": "cosine",+ "local_search_index_type": "flat",+ }.get(key, default)+ with patch(f"{FACTORY_MODULE}.get_settings_manager", return_value=mgr):+ get_rag_service("alice")+ kwargs = mock_rag_cls.call_args.kwargs+ assert kwargs["chunk_overlap"] == 0+def test_passes_db_password(self, patch_settings, mock_db_session, mock_rag_cls):@@ -149,11 +170,8 @@ class TestGetRagServiceDefaults:"""When all settings return None, factory should use hardcoded defaults."""mgr = MagicMock()mgr.get_setting.return_value = None- mgr.get_bool_setting.return_value = None-with patch(f"{FACTORY_MODULE}.get_settings_manager", return_value=mgr):get_rag_service("alice")-kwargs = mock_rag_cls.call_args.kwargsassert kwargs["embedding_model"] == "all-MiniLM-L6-v2"assert kwargs["embedding_provider"] == "sentence_transformers"@@ -161,6 +179,10 @@ class TestGetRagServiceDefaults:assert kwargs["chunk_overlap"] == 200assert kwargs["splitter_type"] == "recursive"assert kwargs["distance_metric"] == "cosine"+ assert (+ kwargs["normalize_vectors"]+ is DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS+ )assert kwargs["index_type"] == "flat"assert kwargs["text_separators"] == DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS@@ -172,11 +194,9 @@ class TestGetRagServiceDefaults:mgr.get_setting.side_effect = lambda key, default=None: {"local_search_text_separators": '["\\n", ". "]',}.get(key, default)- mgr.get_bool_setting.return_value = Truewith patch(f"{FACTORY_MODULE}.get_settings_manager", return_value=mgr):get_rag_service("alice")-kwargs = mock_rag_cls.call_args.kwargsassert kwargs["text_separators"] == ["\n", ". "]@@ -188,11 +208,9 @@ class TestGetRagServiceDefaults:mgr.get_setting.side_effect = lambda key, default=None: {"local_search_text_separators": "not valid json",}.get(key, default)- mgr.get_bool_setting.return_value = Truewith patch(f"{FACTORY_MODULE}.get_settings_manager", return_value=mgr):get_rag_service("alice")-kwargs = mock_rag_cls.call_args.kwargsassert kwargs["text_separators"] == DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS@@ -206,7 +224,6 @@ class TestGetRagServiceDefaults:mgr.get_setting.side_effect = lambda key, default=None: {"local_search_text_separators": "['\\n\\n', '\\n']",}.get(key, default)- mgr.get_bool_setting.return_value = Truewith patch(f"{FACTORY_MODULE}.get_settings_manager", return_value=mgr):get_rag_service("alice")@@ -236,7 +253,6 @@ class TestSettingsManagerReceivesDbSession:fallback when invoked from a background indexing thread (#3453)."""mgr = MagicMock()mgr.get_setting.return_value = None- mgr.get_bool_setting.return_value = Nonewith patch(f"{FACTORY_MODULE}.get_settings_manager", return_value=mgr@@ -261,7 +277,6 @@ class TestSettingsManagerReceivesDbSession:from background threads that have no Flask g."""mgr = MagicMock()mgr.get_setting.return_value = None- mgr.get_bool_setting.return_value = None@contextmanagerdef fake_ctx(*args, **kwargs):@@ -313,6 +328,28 @@ class TestGetRagServiceWithCollection:assert kwargs["chunk_size"] == 500assert kwargs["chunk_overlap"] == 100+ def test_stored_collection_zero_chunk_overlap_preserved(+ self, patch_settings, mock_db_session, mock_rag_cls+ ):+ """When collection has stored chunk_overlap=0, 0 should be used."""+ coll = Collection(+ id=str(uuid.uuid4()),+ name="Zero Overlap Collection",+ is_default=False,+ collection_type="user_collection",+ embedding_model="nomic-embed-text",+ embedding_model_type=EmbeddingProvider.OLLAMA,+ chunk_size=500,+ chunk_overlap=0,+ )+ mock_db_session.add(coll)+ mock_db_session.commit()++ get_rag_service("alice", collection_id=coll.id)++ kwargs = mock_rag_cls.call_args.kwargs+ assert kwargs["chunk_overlap"] == 0+def test_new_collection_uses_defaults(self, patch_settings, mock_db_session, mock_rag_cls):@@ -419,5 +456,34 @@ class TestGetRagServiceWithCollection:get_rag_service("alice", collection_id=coll.id)kwargs = mock_rag_cls.call_args.kwargs- # Default from mock_settings.get_bool_setting is True+ # Falls back to default setting (DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS is True)assert kwargs["normalize_vectors"] is True++ @pytest.mark.parametrize(+ "setting_val,expected",+ [+ (True, True),+ ("true", True),+ ("True", True),+ ("1", True),+ (False, False),+ ("false", False),+ ("False", False),+ ("0", False),+ (None, DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS),+ ],+ )+ def test_normalize_vectors_setting_parsed(+ self, setting_val, expected, mock_db_session, mock_rag_cls+ ):+ """local_search_normalize_vectors setting must be coerced with to_bool, falling back to constant."""+ mgr = MagicMock()+ mgr.get_setting.side_effect = lambda key, default=None: {+ "local_search_normalize_vectors": setting_val,+ }.get(key, default)++ with patch(f"{FACTORY_MODULE}.get_settings_manager", return_value=mgr):+ get_rag_service("alice")++ kwargs = mock_rag_cls.call_args.kwargs+ assert kwargs["normalize_vectors"] is expecteddiff --git a/tests/test_constants.py b/tests/test_constants.pyindex fca48da20d..3aeeb7b351 100644--- a/tests/test_constants.py+++ b/tests/test_constants.py@@ -2,7 +2,19 @@import json-from local_deep_research.constants import DEFAULT_SEARCH_TOOL+from local_deep_research.constants import (+ DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,+ DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,+ DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC,+ DEFAULT_LOCAL_SEARCH_INDEX_TYPE,+ DEFAULT_LOCAL_SEARCH_MODEL,+ DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS,+ DEFAULT_LOCAL_SEARCH_PROVIDER,+ DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE,+ DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS,+ DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS_JSON,+ DEFAULT_SEARCH_TOOL,+)from local_deep_research.defaults import DEFAULTS_DIR@@ -30,3 +42,176 @@ def test_default_search_tool_is_a_registered_option():registry = json.load(f)option_values = {opt["value"] for opt in registry["search.tool"]["options"]}assert DEFAULT_SEARCH_TOOL in option_values+++def test_default_local_search_settings_match_registry():+ """Local search default constants must equal the registered defaults in+ defaults/settings_local_search.json to prevent code/registry drift."""+ path = DEFAULTS_DIR / "settings_local_search.json"+ assert path.exists()+ with open(path, encoding="utf-8-sig") as f:+ registry = json.load(f)++ assert (+ registry["local_search_embedding_provider"]["value"]+ == DEFAULT_LOCAL_SEARCH_PROVIDER+ )+ assert (+ registry["local_search_embedding_model"]["value"]+ == DEFAULT_LOCAL_SEARCH_MODEL+ )+ assert (+ registry["local_search_chunk_size"]["value"]+ == DEFAULT_LOCAL_SEARCH_CHUNK_SIZE+ )+ assert (+ registry["local_search_chunk_overlap"]["value"]+ == DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP+ )+ assert (+ registry["local_search_splitter_type"]["value"]+ == DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE+ )+ assert (+ registry["local_search_text_separators"]["value"]+ == DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS+ )+ assert (+ json.loads(DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS_JSON)+ == DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS+ )+ assert (+ registry["local_search_distance_metric"]["value"]+ == DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC+ )+ assert (+ registry["local_search_normalize_vectors"]["value"]+ == DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS+ )+ assert (+ registry["local_search_index_type"]["value"]+ == DEFAULT_LOCAL_SEARCH_INDEX_TYPE+ )+++def test_default_local_search_options_are_registered():+ """Selected defaults for select settings must exist in their option lists."""+ path = DEFAULTS_DIR / "settings_local_search.json"+ with open(path, encoding="utf-8-sig") as f:+ registry = json.load(f)++ provider_options = {+ opt["value"]+ for opt in registry["local_search_embedding_provider"]["options"]+ }+ assert DEFAULT_LOCAL_SEARCH_PROVIDER in provider_options++ splitter_options = {+ opt["value"]+ for opt in registry["local_search_splitter_type"]["options"]+ }+ assert DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE in splitter_options++ distance_options = {+ opt["value"]+ for opt in registry["local_search_distance_metric"]["options"]+ }+ assert DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC in distance_options++ index_options = {+ opt["value"] for opt in registry["local_search_index_type"]["options"]+ }+ assert DEFAULT_LOCAL_SEARCH_INDEX_TYPE in index_options+++def test_injected_frontend_local_search_constants_match_defaults():+ """Template rendering (via TemplateResponse in template_config.py) must+ inject local_search_defaults that match the backend constants and the+ registry."""+ from starlette.requests import Request+ from local_deep_research.web.fastapi_app import _setup_template_globals+ from local_deep_research.web.template_config import templates++ _setup_template_globals()+ req = Request(+ {+ "type": "http",+ "method": "GET",+ "path": "/",+ "headers": [],+ "session": {},+ }+ )+ ctx = {"request": req}+ resp = templates.TemplateResponse(+ request=req,+ name="base.html",+ context=ctx,+ )++ assert "local_search_defaults" in ctx+ html = resp.body.decode()+ assert "window.LDR_LOCAL_SEARCH_DEFAULTS" in html+ ls = ctx["local_search_defaults"]+ assert ls["provider"] == DEFAULT_LOCAL_SEARCH_PROVIDER+ assert ls["model"] == DEFAULT_LOCAL_SEARCH_MODEL+ assert ls["chunk_size"] == DEFAULT_LOCAL_SEARCH_CHUNK_SIZE+ assert ls["chunk_overlap"] == DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP+ assert ls["splitter_type"] == DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE+ assert ls["text_separators"] == DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS+ assert ls["distance_metric"] == DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC+ assert ls["normalize_vectors"] == DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS+ assert ls["index_type"] == DEFAULT_LOCAL_SEARCH_INDEX_TYPE+++def test_embedding_settings_template_renders_without_syntax_error():+ """pages/embedding_settings.html must compile and render properly."""+ from starlette.requests import Request+ from local_deep_research.web.fastapi_app import _setup_template_globals+ from local_deep_research.web.template_config import templates++ _setup_template_globals()+ req = Request(+ {+ "type": "http",+ "method": "GET",+ "path": "/library/embedding-settings",+ "headers": [],+ "session": {},+ }+ )+ ctx = {"request": req, "active_page": "embedding-settings"}+ resp = templates.TemplateResponse(+ request=req,+ name="pages/embedding_settings.html",+ context=ctx,+ )++ html = resp.body.decode()+ assert "Default Embedding Settings" in html+ assert 'id="text-separators"' in html+ assert (+ 'placeholder="["\\n\\n", "\\n", ". ", " ", ""]"'+ in html+ or '["\\n\\n"' in html+ )+ assert (+ f'id="chunk-size" class="ldr-form-control" value="{DEFAULT_LOCAL_SEARCH_CHUNK_SIZE}"'+ in html+ )+ assert (+ f'id="chunk-overlap" class="ldr-form-control" value="{DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP}"'+ in html+ )+ assert (+ f'<option value="{DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE}" selected>'+ in html+ )+ assert (+ f'<option value="{DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC}" selected>'+ in html+ )+ assert (+ f'<option value="{DEFAULT_LOCAL_SEARCH_INDEX_TYPE}" selected>' in html+ )+ assert 'id="normalize-vectors" checked' in htmldiff --git a/tests/web_search_engines/engines/test_local_embedding_manager.py b/tests/web_search_engines/engines/test_local_embedding_manager.pyindex 0114e36c7a..09f02e9507 100644--- a/tests/web_search_engines/engines/test_local_embedding_manager.py+++ b/tests/web_search_engines/engines/test_local_embedding_manager.py@@ -8,6 +8,11 @@ Tests cover:from unittest.mock import Mock, patch+from local_deep_research.constants import (+ DEFAULT_LOCAL_SEARCH_MODEL,+ DEFAULT_LOCAL_SEARCH_PROVIDER,+)+class TestLocalEmbeddingManagerInit:"""Tests for LocalEmbeddingManager initialization."""@@ -20,9 +25,9 @@ class TestLocalEmbeddingManagerInit:manager = LocalEmbeddingManager()- assert manager.embedding_model == "all-MiniLM-L6-v2"+ assert manager.embedding_model == DEFAULT_LOCAL_SEARCH_MODELassert manager.embedding_device == "cpu"- assert manager.embedding_model_type == "sentence_transformers"+ assert manager.embedding_model_type == DEFAULT_LOCAL_SEARCH_PROVIDERassert manager._embeddings is None # Lazy initializationdef test_init_with_ollama(self):diff --git a/tests/web_search_engines/engines/test_search_engine_library.py b/tests/web_search_engines/engines/test_search_engine_library.pyindex 820e8240e8..9f9da0b8b8 100644--- a/tests/web_search_engines/engines/test_search_engine_library.py+++ b/tests/web_search_engines/engines/test_search_engine_library.py@@ -10,6 +10,13 @@ Tests cover:from unittest.mock import Mock, patch+from local_deep_research.constants import (+ DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,+ DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,+ DEFAULT_LOCAL_SEARCH_MODEL,+ DEFAULT_LOCAL_SEARCH_PROVIDER,+)+from local_deep_research.vector_stores.facade import SearchResult@@ -48,10 +55,10 @@ class TestLibraryRAGSearchEngineInit:"local_deep_research.web_search_engines.engines.search_engine_library.get_setting_from_snapshot") as mock_get_setting:mock_get_setting.side_effect = lambda key, default=None, **kwargs: {- "local_search_embedding_model": "all-MiniLM-L6-v2",- "local_search_embedding_provider": "sentence_transformers",- "local_search_chunk_size": 1000,- "local_search_chunk_overlap": 200,+ "local_search_embedding_model": DEFAULT_LOCAL_SEARCH_MODEL,+ "local_search_embedding_provider": DEFAULT_LOCAL_SEARCH_PROVIDER,+ "local_search_chunk_size": DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,+ "local_search_chunk_overlap": DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,}.get(key, default)with patch(diff --git a/tests/web_search_engines/test_search_engine_library_settings.py b/tests/web_search_engines/test_search_engine_library_settings.pyindex b50c30d76e..cb3831426c 100644--- a/tests/web_search_engines/test_search_engine_library_settings.py+++ b/tests/web_search_engines/test_search_engine_library_settings.py@@ -8,6 +8,12 @@ was never consulted: outside a thread settings context each settingsilently resolved to the snapshot DICT itself."""+from local_deep_research.constants import (+ DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,+ DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,+ DEFAULT_LOCAL_SEARCH_MODEL,+ DEFAULT_LOCAL_SEARCH_PROVIDER,+)from local_deep_research.web_search_engines.engines.search_engine_library import (LibraryRAGSearchEngine,)@@ -30,10 +36,10 @@ def test_snapshot_values_are_honored():def test_defaults_used_when_keys_missing():eng = LibraryRAGSearchEngine(settings_snapshot={"_username": "tester"})- assert eng.embedding_model == "all-MiniLM-L6-v2"- assert eng.embedding_provider == "sentence_transformers"- assert eng.chunk_size == 1000- assert eng.chunk_overlap == 200+ assert eng.embedding_model == DEFAULT_LOCAL_SEARCH_MODEL+ assert eng.embedding_provider == DEFAULT_LOCAL_SEARCH_PROVIDER+ assert eng.chunk_size == DEFAULT_LOCAL_SEARCH_CHUNK_SIZE+ assert eng.chunk_overlap == DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP# ---------------------------------------------------------------------------