~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
feat: add semantic search to news page (#2995)
LearningCircuit3fdfc3d65264
diff --git a/src/local_deep_research/research_library/search/routes/search_routes.py b/src/local_deep_research/research_library/search/routes/search_routes.pyindex 355e6cba12..3c295944a2 100644--- a/src/local_deep_research/research_library/search/routes/search_routes.py+++ b/src/local_deep_research/research_library/search/routes/search_routes.py@@ -386,7 +386,9 @@ def _enrich_with_research_metadata(results, username, db_password):)result["research_query"] = row.research_queryresult["research_created_at"] = (- row.research_created_at.isoformat()+ row.research_created_at+ if isinstance(row.research_created_at, str)+ else row.research_created_at.isoformat()if row.research_created_atelse None)@@ -426,7 +428,11 @@ def _enrich_with_document_metadata(results, username, db_password):if row:result["file_type"] = row.file_typeresult["created_at"] = (- row.created_at.isoformat() if row.created_at else None+ row.created_at+ if isinstance(row.created_at, str)+ else row.created_at.isoformat()+ if row.created_at+ else None)if row.original_url:try:diff --git a/src/local_deep_research/web/static/css/components/semantic-search.css b/src/local_deep_research/web/static/css/components/semantic-search.cssindex 6d9a8020d7..6ddee4dded 100644--- a/src/local_deep_research/web/static/css/components/semantic-search.css+++ b/src/local_deep_research/web/static/css/components/semantic-search.css@@ -88,8 +88,8 @@/* Semantic result card (used by createSemanticResultCard) */.ldr-semantic-result {- padding: 1rem;- margin-bottom: 0.75rem;+ padding: 1.25rem;+ margin-bottom: 1rem;background: var(--bg-secondary);border-radius: 8px;border-left: 3px solid var(--primary-color);@@ -197,3 +197,39 @@color: var(--primary-color);text-decoration: underline;}++/* Library: semantic snippet injected into document cards during hybrid search */+.ldr-library-snippet {+ margin-top: 0.75rem;+ padding: 0.6rem 0.75rem;+ background: color-mix(in srgb, var(--primary-color) 8%, var(--bg-secondary));+ border-radius: 6px;+ border-left: 2px solid var(--primary-color);+ font-size: 0.85rem;+ color: var(--text-secondary);+ line-height: 1.5;+}+.ldr-library-snippet small {+ display: block;+ margin-bottom: 0.25rem;+ font-size: 0.75rem;+}+.ldr-library-snippet div {+ display: -webkit-box;+ -webkit-line-clamp: 4;+ -webkit-box-orient: vertical;+ overflow: hidden;+}++/* Semantic result cards in library context: show more content */+.ldr-semantic-result .ldr-history-item-snippet {+ -webkit-line-clamp: 4;+}++/* Query term highlighting in snippets */+.ldr-search-highlight {+ background: color-mix(in srgb, var(--primary-color) 25%, transparent);+ color: var(--text-primary);+ border-radius: 2px;+ padding: 0 2px;+}diff --git a/src/local_deep_research/web/static/js/components/history.js b/src/local_deep_research/web/static/js/components/history.jsindex 69a5e27df5..4060eb13d4 100644--- a/src/local_deep_research/web/static/js/components/history.js+++ b/src/local_deep_research/web/static/js/components/history.js@@ -415,7 +415,7 @@<div class="ldr-history-item-ai-match"><span class="ldr-ai-match-badge"><i class="fas fa-brain"></i> ${esc(String(semanticMatch.similarity))}% match</span></div>- ${semanticMatch.snippet ? `<div class="ldr-history-item-snippet">${renderSnippet(semanticMatch.snippet)}</div>` : ''}+ ${semanticMatch.snippet ? `<div class="ldr-history-item-snippet">${renderSnippet(semanticMatch.snippet, searchInput ? searchInput.value.trim() : '')}</div>` : ''}` : '';// bearer:disable javascript_lang_dangerous_insert_html@@ -495,7 +495,7 @@<div class="ldr-history-item-ai-match"><span class="ldr-ai-match-badge"><i class="fas fa-brain"></i> ${esc(String(semanticResult.similarity))}% match</span></div>- ${semanticResult.snippet ? `<div class="ldr-history-item-snippet">${renderSnippet(semanticResult.snippet)}</div>` : ''}+ ${semanticResult.snippet ? `<div class="ldr-history-item-snippet">${renderSnippet(semanticResult.snippet, searchInput ? searchInput.value.trim() : '')}</div>` : ''}<div class="ldr-history-item-meta">${dateStr ? `<div class="ldr-history-item-date">${esc(dateStr)}</div>` : ''}</div>@@ -697,7 +697,7 @@`;return;}- window.HistorySearch.renderSemanticResults(results);+ window.HistorySearch.renderSemanticResults(results, searchTerm);} catch (error) {SafeLogger.error('Semantic search failed:', error);if (historyContainer) {diff --git a/src/local_deep_research/web/static/js/components/history_search.js b/src/local_deep_research/web/static/js/components/history_search.jsindex dfe2b49e00..34e6e2ead6 100644--- a/src/local_deep_research/web/static/js/components/history_search.js+++ b/src/local_deep_research/web/static/js/components/history_search.js@@ -385,7 +385,7 @@ async function semanticSearchHistory(query) {* Render semantic search results into the history-items container.* Uses shared createSemanticResultCard from semantic_search.js.*/-function renderSemanticResults(results) {+function renderSemanticResults(results, query) {const container = document.getElementById('history-items');if (!container) return;@@ -403,7 +403,7 @@ function renderSemanticResults(results) {const fragment = document.createDocumentFragment();for (const result of results) {if (window.SemanticSearch && window.SemanticSearch.createSemanticResultCard) {- fragment.appendChild(window.SemanticSearch.createSemanticResultCard(result));+ fragment.appendChild(window.SemanticSearch.createSemanticResultCard(result, null, query));}}container.innerHTML = '';diff --git a/src/local_deep_research/web/static/js/components/library_search.js b/src/local_deep_research/web/static/js/components/library_search.jsindex 04f680423b..d80e6a3553 100644--- a/src/local_deep_research/web/static/js/components/library_search.js+++ b/src/local_deep_research/web/static/js/components/library_search.js@@ -158,7 +158,7 @@ async function searchAllCollections(collectionIds, query, limit) {* @param {Array} results - search results from API* @param {HTMLElement} container - target container element*/-function renderSemanticResults(results, container) {+function renderSemanticResults(results, container, query) {if (!container) return;if (!results || results.length === 0) {@@ -177,7 +177,7 @@ function renderSemanticResults(results, container) {const fragment = document.createDocumentFragment();for (const result of results) {- fragment.appendChild(createCard(result, LIBRARY_CARD_CONFIG));+ fragment.appendChild(createCard(result, LIBRARY_CARD_CONFIG, query));}container.innerHTML = '';diff --git a/src/local_deep_research/web/static/js/components/library_search_ui.js b/src/local_deep_research/web/static/js/components/library_search_ui.jsindex 4d21b37df3..2bbe7d3fba 100644--- a/src/local_deep_research/web/static/js/components/library_search_ui.js+++ b/src/local_deep_research/web/static/js/components/library_search_ui.js@@ -42,18 +42,14 @@ if (searchModeMenu) {searchMode = mode;searchModeMenu.querySelectorAll('.dropdown-item').forEach(function(i) { i.classList.remove('active'); });item.classList.add('active');- var labels = { hybrid: '<i class="fas fa-brain" aria-hidden="true"></i> Hybrid', text: '<i class="fas fa-font" aria-hidden="true"></i> Text Only', semantic: '<i class="fas fa-brain" aria-hidden="true"></i> AI Only' };- var placeholders = { hybrid: 'Hybrid: titles & authors + AI content search...', text: 'Text: filter by title, authors, DOI...', semantic: 'AI: search inside document content...' };+ var labels = { hybrid: '<i class="fas fa-brain" aria-hidden="true"></i> AI Hybrid', text: '<i class="fas fa-font" aria-hidden="true"></i> Text Only', semantic: '<i class="fas fa-brain" aria-hidden="true"></i> AI Only' };+ var placeholders = { hybrid: 'AI Hybrid: titles & authors + AI content search...', text: 'Text: filter by title, authors, DOI...', semantic: 'AI: search inside document content...' };var btn = document.getElementById('search-mode-btn');if (btn) btn.innerHTML = labels[mode] || labels.hybrid;var input = document.getElementById('search-documents');if (input) input.placeholder = placeholders[mode] || placeholders.hybrid;- // Clean up badges and restore original card order from previous hybrid search- document.querySelectorAll('.card-header [data-similarity]').forEach(function(b) { b.remove(); });- for (var ci = 0; ci < originalCardOrder.length; ci++) {- documentsContainer.appendChild(originalCardOrder[ci]);- }- documentsContainer.querySelectorAll('.ldr-semantic-result').forEach(function(el) { el.remove(); });+ // Clean up badges, snippets, and restore original card order+ clearHybridState();handleSearchInput();});}@@ -127,11 +123,7 @@ function handleSearchInput() {// Empty search: revert to showing all cards in original orderif (!searchTerm) {clearTimeout(semanticDebounceTimer);- document.querySelectorAll('.card-header [data-similarity]').forEach(function(b) { b.remove(); });- for (var ci = 0; ci < originalCardOrder.length; ci++) {- documentsContainer.appendChild(originalCardOrder[ci]);- }- documentsContainer.querySelectorAll('.ldr-semantic-result').forEach(function(el) { el.remove(); });+ clearHybridState();if (documentsContainer) documentsContainer.style.display = 'grid';if (semanticResultsContainer) { semanticResultsContainer.style.display = 'none'; semanticResultsContainer.innerHTML = ''; }if (searchNotice) searchNotice.style.display = 'none';@@ -187,7 +179,7 @@ async function runSemanticSearch(query) {}if (searchMode !== SM.SEMANTIC) return; // mode changedresults = postFilterSemanticResults(results);- window.LibrarySearch.renderSemanticResults(results, semanticResultsContainer);+ window.LibrarySearch.renderSemanticResults(results, semanticResultsContainer, query);} catch (err) {if (typeof SafeLogger !== 'undefined') SafeLogger.error('Semantic search error:', err);if (semanticResultsContainer) {@@ -241,7 +233,7 @@ async function runHybridSearch(query, searchId) {{ textIdKey: 'id', semanticIdKey: 'document_id' });- renderMergedLibraryResults(tiered);+ renderMergedLibraryResults(tiered, query);} catch (err) {removeHybridLoading();@@ -250,10 +242,12 @@ async function runHybridSearch(query, searchId) {}// --- Render merged library results (DOM reorder) ----function renderMergedLibraryResults(tiered) {+function renderMergedLibraryResults(tiered, query) {if (!documentsContainer) return;var fragment = document.createDocumentFragment();- var esc = window.escapeHtml || function(s) { return String(s || ''); };+ var esc = window.escapeHtml || function(s) { return String(s || '').replace(/[&<>"']/g, function(m) { return {'&':'&','<':'<','>':'>','"':'"',"'":"'"}[m]; }); };++ var renderSnippet = window.SemanticSearch && window.SemanticSearch.renderSnippet;for (var i = 0; i < tiered.tier1.length; i++) {var entry = tiered.tier1[i];@@ -268,6 +262,18 @@ function renderMergedLibraryResults(tiered) {badge.innerHTML = '<i class="fas fa-brain" aria-hidden="true"></i> ' + esc(String(entry.semanticMatch.similarity)) + '% match';header.appendChild(badge);}+ // Inject semantic snippet into card body+ if (entry.semanticMatch.snippet && renderSnippet) {+ var existing = card.querySelector('.ldr-library-snippet');+ if (existing) existing.remove();+ var snippetDiv = document.createElement('div');+ snippetDiv.className = 'ldr-library-snippet';+ // bearer:disable javascript_lang_dangerous_insert_html+ snippetDiv.innerHTML = '<small class="text-muted"><i class="fas fa-brain" aria-hidden="true"></i> Matched content:</small>' ++ '<div>' + renderSnippet(entry.semanticMatch.snippet, query) + '</div>';+ var body = card.querySelector('.card-body');+ if (body) body.appendChild(snippetDiv);+ }fragment.appendChild(card);}}@@ -285,7 +291,7 @@ function renderMergedLibraryResults(tiered) {var config = window.LibrarySearch.getLibraryCardConfig();for (var k = 0; k < tiered.tier3.length; k++) {- fragment.appendChild(window.SemanticSearch.createSemanticResultCard(tiered.tier3[k].semanticResult, config));+ fragment.appendChild(window.SemanticSearch.createSemanticResultCard(tiered.tier3[k].semanticResult, config, query));}}@@ -294,6 +300,17 @@ function renderMergedLibraryResults(tiered) {}// --- Helpers ---+function clearHybridState() {+ hybridSearchId++;+ document.querySelectorAll('.card-header [data-similarity]').forEach(function(b) { b.remove(); });+ document.querySelectorAll('.ldr-library-snippet').forEach(function(el) { el.remove(); });+ for (var ci = 0; ci < originalCardOrder.length; ci++) {+ documentsContainer.appendChild(originalCardOrder[ci]);+ }+ documentsContainer.querySelectorAll('.ldr-semantic-result').forEach(function(el) { el.remove(); });+ documentsContainer.querySelectorAll('.ldr-hybrid-divider').forEach(function(el) { el.remove(); });+}+function getActiveSearchCollectionId() {var sel = document.getElementById('filter-collection');return (sel && sel.value) ? sel.value : null;diff --git a/src/local_deep_research/web/static/js/components/semantic_search.js b/src/local_deep_research/web/static/js/components/semantic_search.jsindex 7a3b85efb9..aed01eef47 100644--- a/src/local_deep_research/web/static/js/components/semantic_search.js+++ b/src/local_deep_research/web/static/js/components/semantic_search.js@@ -17,18 +17,50 @@ const esc = window.escapeHtml || (s => String(s || '').replace(/[&<>"']/g, m =>/*** Render a markdown snippet as sanitized inline HTML.* Falls back to escapeHtml when marked/DOMPurify are not loaded.+ * @param {string} md - markdown snippet+ * @param {string} [query] - optional search query for keyword highlighting*/-function renderSnippet(md) {+function renderSnippet(md, query) {if (!md) return '';+ var html;if (window.marked && window.DOMPurify) {- const html = window.marked.parseInline(String(md));- return window.DOMPurify.sanitize(html, {- ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'span', 'a', 'code', 'br', 'p', 'ul', 'ol', 'li'],- ALLOWED_ATTR: ['href', 'title'],+ html = window.marked.parseInline(String(md));+ html = window.DOMPurify.sanitize(html, {+ ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'span', 'a', 'code', 'br', 'p', 'ul', 'ol', 'li', 'mark'],+ ALLOWED_ATTR: ['href', 'title', 'class'],ALLOW_DATA_ATTR: false,});+ } else {+ html = esc(md);}- return esc(md);+ if (query) {+ html = highlightTerms(html, query);+ }+ return html;+}++/**+ * Highlight query terms in an HTML string by wrapping matches in <mark> tags.+ * Only operates on text between HTML tags to avoid breaking markup.+ * @param {string} html - HTML string+ * @param {string} query - search query (split into words, each highlighted)+ * @returns {string} HTML with <mark> wrapped terms+ */+function highlightTerms(html, query) {+ if (!html || !query) return html;+ // Extract meaningful words (3+ chars to avoid noise)+ var words = query.split(/\s+/).filter(function(w) { return w.length >= 3; });+ if (words.length === 0) return html;+ // Escape regex special characters in each word+ var escaped = words.map(function(w) {+ return w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ });+ var pattern = new RegExp('(' + escaped.join('|') + ')', 'gi');+ // Split on HTML tags to only highlight text content, not inside tags+ return html.replace(/(<[^>]*>)|([^<]+)/g, function(match, tag, text) {+ if (tag) return tag; // preserve HTML tags as-is+ return text.replace(pattern, '<mark class="ldr-search-highlight">$1</mark>');+ });}/**@@ -110,7 +142,7 @@ function buildTieredResults(textResults, semanticResults, options) {* - getSubtitle(r): optional subtitle line or null* @returns {HTMLElement}*/-function createSemanticResultCard(result, config) {+function createSemanticResultCard(result, config, query) {const cfg = config || {};const cardId = (cfg.getId || function(r) { return r.research_id || ''; })(result);@@ -167,7 +199,7 @@ function createSemanticResultCard(result, config) {<a href="${esc(cardUrl)}">${esc(displayTitle)}</a></h4>${subtitle ? `<p class="ldr-semantic-result-subtitle">${esc(subtitle)}</p>` : ''}- ${result.snippet ? `<div class="ldr-history-item-snippet">${renderSnippet(result.snippet)}</div>` : ''}+ ${result.snippet ? `<div class="ldr-history-item-snippet">${renderSnippet(result.snippet, query)}</div>` : ''}${result.url && isSafeExternalUrl(result.url) ? `<p class="ldr-semantic-result-source"><a href="${esc(result.url)}" target="_blank" rel="noopener noreferrer">@@ -208,6 +240,7 @@ function isSafeExternalUrl(url) {// Expose shared APIwindow.SemanticSearch = {renderSnippet,+ highlightTerms,buildTieredResults,createSemanticResultCard,isSafeExternalUrl,diff --git a/src/local_deep_research/web/static/js/pages/news.js b/src/local_deep_research/web/static/js/pages/news.jsindex e404e65faa..f659f922b4 100644--- a/src/local_deep_research/web/static/js/pages/news.js+++ b/src/local_deep_research/web/static/js/pages/news.js@@ -79,6 +79,14 @@ let readNewsIds = new Set();let expandedNewsIds = new Set();let savedNewsIds = new Set();+// Semantic search state+const NEWS_SM = { HYBRID: 'hybrid', TEXT: 'text', SEMANTIC: 'semantic' };+let newsSearchMode = NEWS_SM.HYBRID;+let newsCollectionId = null;+let newsSemanticTimer = null;+let newsSearchId = 0;+let newsSemanticMatches = null; // Map: research_id -> { similarity, snippet }+// Optimized news table query templateconst getNewsTableQuery = () => `Find UP TO 10 IMPORTANT breaking news stories from TODAY ${new Date().toLocaleDateString()} ONLY.@@ -155,6 +163,10 @@ async function initializeNewsPage() {// Set up event listeners firstsetupEventListeners();+ setupSearchModeToggle();++ // Initialize semantic search (non-blocking)+ initNewsSemanticSearch();// Load initial data in proper orderawait loadSubscriptions();@@ -206,15 +218,30 @@ function cleanupNewsPage() {clearInterval(autoRefreshInterval);autoRefreshInterval = null;}+ if (newsSemanticTimer) {+ clearTimeout(newsSemanticTimer);+ newsSemanticTimer = null;+ }}function setupEventListeners() {// Search button+ // Search button still works as a manual triggerconst searchBtn = document.getElementById('search-btn');if (searchBtn) {searchBtn.addEventListener('click', handleSearchSubmit);}+ // Debounced auto-search on typing (250ms, matching library/history pages)+ let newsInputDebounceTimer = null;+ const newsSearchInput = document.getElementById('news-search');+ if (newsSearchInput) {+ newsSearchInput.addEventListener('input', () => {+ clearTimeout(newsInputDebounceTimer);+ newsInputDebounceTimer = setTimeout(() => handleSearchSubmit(), 250);+ });+ }+// Create subscription buttonconst createSubBtn = document.getElementById('create-subscription-btn');if (createSubBtn) {@@ -251,11 +278,12 @@ function setupEventListeners() {});}- // Search input - handle Enter key+ // Search input - Enter key triggers immediately (bypasses debounce)const searchInput = document.getElementById('news-search');if (searchInput) {searchInput.addEventListener('keypress', (e) => {if (e.key === 'Enter') {+ clearTimeout(newsInputDebounceTimer);handleSearchSubmit(e);}});@@ -371,9 +399,9 @@ async function handleSearchSubmit(e) {}const query = document.getElementById('news-search').value.trim();- // If empty query, reset the filter and show all news+ // If empty query, reset everythingif (!query) {- // Clear any existing filter+ clearSemanticState();await loadNewsFeed();return;}@@ -381,13 +409,35 @@ async function handleSearchSubmit(e) {// Add to search history only for non-empty queriesaddToSearchHistory(query, 'filter');- // Always filter the current results- await loadNewsFeed(query);+ if (newsSearchMode === NEWS_SM.SEMANTIC) {+ // Pure semantic search+ await runNewsSemanticSearch(query);+ } else if (newsSearchMode === NEWS_SM.TEXT) {+ // Text-only: existing behavior+ clearSemanticState();+ await loadNewsFeed(query);+ } else {+ // Hybrid: text results first, then debounced semantic+ clearSemanticState();+ const feedContent = document.getElementById('news-feed-content');+ if (feedContent) feedContent.style.display = '';+ const semanticContainer = document.getElementById('news-semantic-results');+ if (semanticContainer) semanticContainer.style.display = 'none';++ await loadNewsFeed(query);++ // Debounced semantic search+ clearTimeout(newsSemanticTimer);+ newsSemanticTimer = setTimeout(() => {+ runNewsHybridSearch(query);+ }, 500);+ }}// Clear search and reload feedfunction clearSearch() {document.getElementById('news-search').value = '';+ clearSemanticState();loadNewsFeed();}@@ -723,11 +773,15 @@ async function loadSubscriptions() {function selectSubscription(subId) {activeSubscription = subId;// renderSubscriptions(); // Removed sidebar subscription list+ clearSemanticState();loadNewsFeed();}// Load news feedasync function loadNewsFeed(focus = null) {+ // Clear stale semantic badges — hybrid search will re-set them if needed+ newsSemanticMatches = null;+const container = document.getElementById('news-feed-content');if (!container) {SafeLogger.error('News container not found!');@@ -897,9 +951,21 @@ function renderNewsItems(searchQuery = null) {setTimeout(() => markNewsAsSeen(item.id), 3000);}- // Render findings if available - limit to a reasonable preview+ // Render findings or semantic snippet as previewlet findingsHtml = '';- if (item.findings) {+ const semanticMatch = newsSemanticMatches && newsSemanticMatches.get(String(item.research_id));+ if (semanticMatch && semanticMatch.snippet) {+ // Show semantic snippet — the relevant chunk that matched the query+ const renderSnippet = window.SemanticSearch && window.SemanticSearch.renderSnippet;+ const currentQuery = searchQuery || (document.getElementById('news-search') ? document.getElementById('news-search').value.trim() : '');+ const snippetContent = renderSnippet+ ? renderSnippet(semanticMatch.snippet, currentQuery)+ : escapeHtml(semanticMatch.snippet);+ findingsHtml = `<div class="ldr-news-findings ldr-semantic-snippet">+ <small class="text-muted"><i class="fas fa-brain" aria-hidden="true"></i> Matched content:</small>+ <div>${snippetContent}</div>+ </div>`;+ } else if (item.findings) {// Limit findings to first 800 characters for previewconst findingsPreview = item.findings.substring(0, 800) + (item.findings.length > 800 ? '...' : '');@@ -939,7 +1005,12 @@ function renderNewsItems(searchQuery = null) {<div class="ldr-news-item ldr-priority-${priorityClass} ${newClasses} ${readClasses} ldr-is-expanded" data-news-id="${escapeHtml(item.id)}">${isNew ? '<span class="ldr-new-indicator">New</span>' : ''}<div class="ldr-news-item-header">- <div class="ldr-news-headline">${escapeHtml(item.headline)}</div>+ <div class="ldr-news-headline">+ ${escapeHtml(item.headline)}+ ${newsSemanticMatches && newsSemanticMatches.has(String(item.research_id))+ ? `<span class="ldr-ai-match-badge"><i class="fas fa-brain"></i> ${Math.round(newsSemanticMatches.get(String(item.research_id)).similarity || 0)}% match</span>`+ : ''}+ </div><div class="ldr-news-actions-menu"><button class="btn btn-sm btn-ghost" onclick="toggleReadStatus('${escapeAttr(item.id)}')" title="${isRead ? 'Mark as unread' : 'Mark as read'}"><i class="bi ${isRead ? 'bi-envelope-open' : 'bi-envelope'}"></i>@@ -1692,6 +1763,9 @@ function clearAllFilters() {activeTimeFilter = 'all';activeImpactThreshold = 0;+ // Clear semantic search state+ clearSemanticState();+// Update UIupdateActiveTopicUI();@@ -1986,14 +2060,285 @@ function showAlert(message, type = 'info') {}function getCSRFToken() {- return window.api ? window.api.getCsrfToken() : '';+ return (window.api && window.api.getCsrfToken)+ ? window.api.getCsrfToken()+ : (document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '');+}++// --- Semantic search ---++const NEWS_CARD_CONFIG = {+ getId: (r) => r.research_id || '',+ getTitle: (r) => r.research_title || r.title || 'Untitled',+ getUrl: (r) => (typeof URLBuilder !== 'undefined' && r.research_id)+ ? URLBuilder.resultsPage(r.research_id) : '#',+ getBadges: (r) => [{ icon: 'newspaper', label: 'News' }],+ getDate: (r) => r.research_created_at,+ getSubtitle: (r) => null,+};++async function initNewsSemanticSearch() {+ try {+ const resp = await fetch('/library/api/research-history/collection', {+ headers: { 'X-CSRFToken': getCSRFToken() }+ });+ if (!resp.ok) return;+ const data = await resp.json();+ if (data.success) newsCollectionId = data.collection_id;+ } catch (e) {+ SafeLogger.warn('Semantic search unavailable:', e);+ }+}++function setupSearchModeToggle() {+ const menu = document.getElementById('news-search-mode-menu');+ if (!menu) return;++ menu.addEventListener('click', function(e) {+ const item = e.target.closest('.dropdown-item');+ if (!item) return;+ e.preventDefault();++ const mode = item.dataset.mode;+ if (!mode || mode === newsSearchMode) return;++ newsSearchMode = mode;++ // Update active state+ menu.querySelectorAll('.dropdown-item').forEach(el => el.classList.remove('active'));+ item.classList.add('active');++ // Update button label+ const btn = document.getElementById('news-search-mode-btn');+ if (btn) {+ const labels = { hybrid: 'AI Hybrid', text: 'Text Only', semantic: 'AI Only' };+ const icons = { hybrid: 'fa-brain', text: 'fa-font', semantic: 'fa-brain' };+ btn.innerHTML = `<i class="fas ${icons[mode]}"></i> ${labels[mode]}`;+ }++ // Update placeholder+ const input = document.getElementById('news-search');+ if (input) {+ const placeholders = {+ hybrid: 'AI Hybrid: searches headlines & content with AI...',+ text: 'Text: filters by headline, topic, or keyword...',+ semantic: 'AI: searches inside research content using semantic similarity...'+ };+ input.placeholder = placeholders[mode];+ }++ // Cancel any in-flight debounced search and clear semantic state+ clearTimeout(newsSemanticTimer);+ clearSemanticState();++ // Re-trigger search with current query+ const query = document.getElementById('news-search').value.trim();+ if (query) {+ handleSearchSubmit();+ }+ });+}++function clearSemanticState() {+ newsSemanticMatches = null;+ newsSearchId++;+ clearTimeout(newsSemanticTimer);+ const semanticContainer = document.getElementById('news-semantic-results');+ if (semanticContainer) {+ semanticContainer.style.display = 'none';+ semanticContainer.innerHTML = '';+ }+ const feedContent = document.getElementById('news-feed-content');+ if (feedContent) feedContent.style.display = '';+}++async function runNewsSemanticSearch(query) {+ const currentId = ++newsSearchId;++ if (!newsCollectionId) {+ showAlert('Semantic search not available — research history may not be indexed yet.', 'warning');+ return;+ }++ const feedContent = document.getElementById('news-feed-content');+ const semanticContainer = document.getElementById('news-semantic-results');+ if (!semanticContainer) return;++ // Show loading+ if (feedContent) feedContent.style.display = 'none';+ semanticContainer.style.display = '';+ semanticContainer.innerHTML = '<div class="ldr-loading-placeholder"><div class="ldr-loading-spinner"></div><p>Searching content with AI...</p></div>';++ try {+ const searchUrl = typeof URLBuilder !== 'undefined'+ ? URLBuilder.build(URLS.LIBRARY_API.COLLECTION_SEARCH, newsCollectionId)+ : `/library/api/collections/${encodeURIComponent(newsCollectionId)}/search`;++ const resp = await fetch(searchUrl, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': getCSRFToken()+ },+ body: JSON.stringify({ query: query, limit: 50 })+ });++ // Stale guard+ if (currentId !== newsSearchId || newsSearchMode !== NEWS_SM.SEMANTIC) return;++ if (!resp.ok) {+ semanticContainer.innerHTML = '<div class="ldr-empty-state"><p>Semantic search failed. Try again later.</p></div>';+ return;+ }++ const data = await resp.json();+ if (currentId !== newsSearchId || newsSearchMode !== NEWS_SM.SEMANTIC) return;++ let results = data.results || [];++ // Filter to only news items+ const newsIds = new Set(newsItems.map(i => String(i.research_id)));+ results = results.filter(r => r.research_id && newsIds.has(String(r.research_id)));++ if (results.length === 0) {+ semanticContainer.innerHTML = '<div class="ldr-empty-state"><i class="fas fa-brain fa-2x" style="opacity:0.5"></i><p>No semantic matches found in news items.</p></div>';+ return;+ }++ // Render semantic result cards+ const createCard = window.SemanticSearch && window.SemanticSearch.createSemanticResultCard;+ if (!createCard) {+ semanticContainer.innerHTML = '<div class="ldr-empty-state"><i class="fas fa-exclamation-triangle fa-2x"></i><p>Search module not loaded. Please refresh the page.</p></div>';+ return;+ }++ semanticContainer.innerHTML = '';+ for (const result of results) {+ semanticContainer.appendChild(createCard(result, NEWS_CARD_CONFIG, query));+ }+ } catch (error) {+ SafeLogger.error('Semantic search error:', error);+ semanticContainer.innerHTML = '<div class="ldr-empty-state"><p>Error performing semantic search.</p></div>';+ }+}++async function runNewsHybridSearch(query) {+ const currentId = ++newsSearchId;++ // Show loading indicator+ const feedContent = document.getElementById('news-feed-content');+ const existingIndicator = document.getElementById('news-hybrid-loading');+ if (existingIndicator) existingIndicator.remove();++ if (feedContent) {+ const loadingDiv = document.createElement('div');+ loadingDiv.className = 'ldr-hybrid-loading';+ loadingDiv.id = 'news-hybrid-loading';+ loadingDiv.innerHTML = '<div class="ldr-spinner" style="width: 16px; height: 16px; border-width: 2px;"></div> Searching content...';+ feedContent.appendChild(loadingDiv);+ }++ try {+ if (!newsCollectionId) {+ const indicator = document.getElementById('news-hybrid-loading');+ if (indicator) indicator.remove();+ return;+ }++ const searchUrl = typeof URLBuilder !== 'undefined'+ ? URLBuilder.build(URLS.LIBRARY_API.COLLECTION_SEARCH, newsCollectionId)+ : `/library/api/collections/${encodeURIComponent(newsCollectionId)}/search`;++ const resp = await fetch(searchUrl, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': getCSRFToken()+ },+ body: JSON.stringify({ query: query, limit: 50 })+ });++ // Stale guard+ if (currentId !== newsSearchId || newsSearchMode !== NEWS_SM.HYBRID) return;++ if (!resp.ok) {+ const indicator = document.getElementById('news-hybrid-loading');+ if (indicator) indicator.remove();+ return;+ }++ const data = await resp.json();+ if (currentId !== newsSearchId || newsSearchMode !== NEWS_SM.HYBRID) return;++ // Filter to news items+ const newsIds = new Set(newsItems.map(i => String(i.research_id)));+ const semanticResults = (data.results || []).filter(r => r.research_id && newsIds.has(String(r.research_id)));++ // Build tiered results+ const buildTiered = window.SemanticSearch && window.SemanticSearch.buildTieredResults;+ if (!buildTiered) {+ const indicator = document.getElementById('news-hybrid-loading');+ if (indicator) indicator.remove();+ return;+ }++ const textItems = newsItems.map(item => ({ id: String(item.research_id), item: item }));+ const tiered = buildTiered(textItems, semanticResults, { textIdKey: 'id', semanticIdKey: 'research_id' });++ // Reorder newsItems array+ const reordered = [];+ const similarityMap = new Map();+ for (const entry of tiered.tier1) {+ reordered.push(entry.historyItem.item);+ similarityMap.set(String(entry.historyItem.item.research_id), entry.semanticMatch);+ }+ for (const entry of tiered.tier2) {+ reordered.push(entry.historyItem.item);+ }++ // Store similarity data for badge rendering+ newsSemanticMatches = similarityMap;++ // Replace newsItems and re-render+ newsItems = reordered;+ renderNewsItems(query);++ // Remove loading indicator+ const indicator = document.getElementById('news-hybrid-loading');+ if (indicator) indicator.remove();++ // Tier 3: semantic-only results not in current feed+ if (tiered.tier3.length > 0 && feedContent) {+ const createCard = window.SemanticSearch && window.SemanticSearch.createSemanticResultCard;+ if (createCard) {+ const divider = document.createElement('div');+ divider.className = 'ldr-hybrid-divider';+ divider.textContent = 'Also found in research content';+ feedContent.appendChild(divider);++ for (const entry of tiered.tier3) {+ feedContent.appendChild(createCard(entry.semanticResult, NEWS_CARD_CONFIG, query));+ }+ }+ }+ } catch (error) {+ SafeLogger.error('Hybrid search error:', error);+ const indicator = document.getElementById('news-hybrid-loading');+ if (indicator) indicator.remove();+ }}// Refresh feedfunction refreshFeed() {lastRefreshTime = new Date();updateRefreshIndicator();- loadNewsFeed();+ const query = document.getElementById('news-search').value.trim();+ clearSemanticState();+ if (query) {+ handleSearchSubmit();+ } else {+ loadNewsFeed();+ }showAlert('Feed refreshed', 'info');}@@ -2006,6 +2351,8 @@ function startAutoRefresh() {const refreshInterval = 5 * 60 * 1000; // 5 minutesautoRefreshInterval = setInterval(() => {+ // Skip auto-refresh while any search query is active+ if (document.getElementById('news-search').value.trim()) return;refreshFeed();}, refreshInterval);diff --git a/src/local_deep_research/web/templates/pages/history.html b/src/local_deep_research/web/templates/pages/history.htmlindex f249089b73..24fa698f28 100644--- a/src/local_deep_research/web/templates/pages/history.html+++ b/src/local_deep_research/web/templates/pages/history.html@@ -23,8 +23,8 @@</div><div class="ldr-card-content" id="semantic-panel-content"><p class="ldr-semantic-panel-description">- Index your completed research to enable <strong>Hybrid</strong> and <strong>AI Only</strong> search modes.- Hybrid (default) shows instant title matches, then appends AI content matches.+ Index your completed research to enable <strong>AI Hybrid</strong> and <strong>AI Only</strong> search modes.+ AI Hybrid (default) shows instant title matches, then appends AI content matches.</p><!-- Indexing Status --><div id="indexing-status" class="ldr-indexing-status">@@ -57,11 +57,11 @@<div class="dropdown d-inline-block"><button class="btn btn-sm ldr-btn-outline dropdown-toggle" type="button"id="search-mode-btn" data-bs-toggle="dropdown" aria-expanded="false">- <i class="fas fa-brain"></i> Hybrid+ <i class="fas fa-brain"></i> AI Hybrid</button>- <ul class="dropdown-menu" aria-labelledby="search-mode-btn" id="search-mode-menu">+ <ul class="dropdown-menu" aria-label="Search mode" id="search-mode-menu"><li><a class="dropdown-item active" href="#" data-mode="hybrid">- <i class="fas fa-brain"></i> Hybrid <small class="text-muted">— titles + content</small>+ <i class="fas fa-brain"></i> AI Hybrid <small class="text-muted">— titles + content</small></a></li><li><a class="dropdown-item" href="#" data-mode="text"><i class="fas fa-font"></i> Text Only <small class="text-muted">— titles only</small>diff --git a/src/local_deep_research/web/templates/pages/library.html b/src/local_deep_research/web/templates/pages/library.htmlindex 6cd5d8c871..9c24d44104 100644--- a/src/local_deep_research/web/templates/pages/library.html+++ b/src/local_deep_research/web/templates/pages/library.html@@ -126,15 +126,15 @@<label for="search-documents">Search</label><div class="ldr-search-row"><input type="text" id="search-documents" class="form-control library-search-input"- placeholder="Hybrid: titles & authors + AI content search..." aria-label="Search documents" style="flex: 1;">+ placeholder="AI Hybrid: titles & authors + AI content search..." aria-label="Search documents" style="flex: 1;"><div class="dropdown d-inline-block"><button class="btn btn-sm ldr-btn-outline dropdown-toggle" type="button"id="search-mode-btn" data-bs-toggle="dropdown" aria-expanded="false">- <i class="fas fa-brain" aria-hidden="true"></i> Hybrid+ <i class="fas fa-brain" aria-hidden="true"></i> AI Hybrid</button>- <ul class="dropdown-menu" aria-labelledby="search-mode-btn" id="search-mode-menu">+ <ul class="dropdown-menu" aria-label="Search mode" id="search-mode-menu"><li><a class="dropdown-item active" href="#" data-mode="hybrid">- <i class="fas fa-brain" aria-hidden="true"></i> Hybrid <small class="text-muted">— titles + AI content</small>+ <i class="fas fa-brain" aria-hidden="true"></i> AI Hybrid <small class="text-muted">— titles + AI content</small></a></li><li><a class="dropdown-item" href="#" data-mode="text"><i class="fas fa-font" aria-hidden="true"></i> Text Only <small class="text-muted">— titles, authors, DOI</small>diff --git a/src/local_deep_research/web/templates/pages/news.html b/src/local_deep_research/web/templates/pages/news.htmlindex c170bf9043..7891b805c3 100644--- a/src/local_deep_research/web/templates/pages/news.html+++ b/src/local_deep_research/web/templates/pages/news.html@@ -9,6 +9,7 @@<link rel="stylesheet" href="/static/css/custom_dropdown.css"><link rel="stylesheet" href="/static/css/news.css"><link rel="stylesheet" href="/static/css/news-enhanced.css">+<link rel="stylesheet" href="/static/css/components/semantic-search.css"><style>/* Define the button styles */.ldr-filter-btn {@@ -44,8 +45,22 @@<!-- Search box below header --><div class="ldr-news-search-container"><div class="ldr-news-search-box">+ <div class="dropdown d-inline-block">+ <button class="btn btn-sm ldr-btn-outline dropdown-toggle" type="button"+ id="news-search-mode-btn" data-bs-toggle="dropdown" aria-expanded="false">+ <i class="fas fa-brain" aria-hidden="true"></i> AI Hybrid+ </button>+ <ul class="dropdown-menu" aria-label="Search mode" id="news-search-mode-menu">+ <li><a class="dropdown-item active" href="#" data-mode="hybrid">+ <i class="fas fa-brain" aria-hidden="true"></i> AI Hybrid <small class="text-muted">— titles + content</small></a></li>+ <li><a class="dropdown-item" href="#" data-mode="text">+ <i class="fas fa-font" aria-hidden="true"></i> Text Only <small class="text-muted">— headlines & topics</small></a></li>+ <li><a class="dropdown-item" href="#" data-mode="semantic">+ <i class="fas fa-brain" aria-hidden="true"></i> AI Only <small class="text-muted">— content similarity</small></a></li>+ </ul>+ </div><i class="bi bi-search ldr-search-icon"></i>- <input type="text" id="news-search" class="ldr-form-control" placeholder="Search news topics, headlines, or keywords...">+ <input type="text" id="news-search" class="ldr-form-control" placeholder="AI Hybrid: searches headlines & content with AI..."><button id="search-btn" class="btn btn-primary">Search</button>@@ -107,6 +122,7 @@<div id="news-feed-content"><!-- This is where news items will be displayed --></div>+ <div id="news-semantic-results" style="display:none"></div></div><!-- Load More -->@@ -341,6 +357,9 @@<!-- Add custom dropdown component --><script defer src="/static/js/components/custom_dropdown.js"></script>+<!-- Add semantic search component -->+<script defer src="/static/js/components/semantic_search.js"></script>+<!-- Add news page JavaScript --><script defer src="/static/js/pages/news.js"></script>diff --git a/tests/research_library/search/routes/test_search_routes.py b/tests/research_library/search/routes/test_search_routes.pyindex 75b9aaf222..99fe7480e9 100644--- a/tests/research_library/search/routes/test_search_routes.py+++ b/tests/research_library/search/routes/test_search_routes.py@@ -741,3 +741,264 @@ class TestAddToCollectionRoute:assert data["success"] is Trueassert data["collection_name"] == "My Collection"assert data["documents_added"] == 3+++class TestEnrichDatetimeTypeGuards:+ """Tests for the isinstance(str) type guards on datetime fields in+ _enrich_with_research_metadata and _enrich_with_document_metadata.++ These guards handle cases where the DB driver returns a string+ instead of a datetime object (e.g. SQLite text columns).+ """++ def test_document_created_at_as_string_passthrough(self, auth_client):+ """When created_at is already a string, return it as-is (no .isoformat())."""+ mock_collection = MagicMock()+ mock_collection.collection_type = "user_collection"+ mock_collection.name = "Docs"++ mock_doc_row = MagicMock()+ mock_doc_row.document_id = "doc-str-date"+ mock_doc_row.file_type = "pdf"+ mock_doc_row.original_url = None+ mock_doc_row.created_at = (+ "2025-06-15T10:00:00+00:00" # already a string+ )++ call_count = 0++ @contextmanager+ def mock_session(*_args, **_kwargs):+ nonlocal call_count+ call_count += 1+ db_session = MagicMock()+ if call_count == 1:+ db_session.query.return_value.filter_by.return_value.first.return_value = mock_collection+ else:+ db_session.query.return_value.filter.return_value.all.return_value = [+ mock_doc_row+ ]+ yield db_session++ fake_results = [+ {+ "title": "String Date Doc",+ "snippet": "s",+ "relevance_score": 0.9,+ "metadata": {"document_id": "doc-str-date"},+ }+ ]+ mock_engine = MagicMock()+ mock_engine.search.return_value = fake_results++ with (+ patch(+ "local_deep_research.database.session_context.get_user_db_session",+ mock_session,+ ),+ patch(+ "local_deep_research.web_search_engines.engines.search_engine_collection.CollectionSearchEngine",+ return_value=mock_engine,+ ),+ ):+ response = auth_client.post(+ f"/library/api/collections/{TEST_COLLECTION_ID}/search",+ data=json.dumps({"query": "date test"}),+ content_type="application/json",+ )++ assert response.status_code == 200+ data = response.get_json()+ result = data["results"][0]+ assert result["created_at"] == "2025-06-15T10:00:00+00:00"++ def test_document_created_at_as_datetime(self, auth_client):+ """When created_at is a datetime, call .isoformat()."""+ from datetime import datetime, timezone++ mock_collection = MagicMock()+ mock_collection.collection_type = "user_collection"+ mock_collection.name = "Docs"++ mock_doc_row = MagicMock()+ mock_doc_row.document_id = "doc-dt-date"+ mock_doc_row.file_type = "pdf"+ mock_doc_row.original_url = None+ mock_doc_row.created_at = datetime(+ 2025, 6, 15, 10, 0, 0, tzinfo=timezone.utc+ )++ call_count = 0++ @contextmanager+ def mock_session(*_args, **_kwargs):+ nonlocal call_count+ call_count += 1+ db_session = MagicMock()+ if call_count == 1:+ db_session.query.return_value.filter_by.return_value.first.return_value = mock_collection+ else:+ db_session.query.return_value.filter.return_value.all.return_value = [+ mock_doc_row+ ]+ yield db_session++ fake_results = [+ {+ "title": "Datetime Date Doc",+ "snippet": "s",+ "relevance_score": 0.9,+ "metadata": {"document_id": "doc-dt-date"},+ }+ ]+ mock_engine = MagicMock()+ mock_engine.search.return_value = fake_results++ with (+ patch(+ "local_deep_research.database.session_context.get_user_db_session",+ mock_session,+ ),+ patch(+ "local_deep_research.web_search_engines.engines.search_engine_collection.CollectionSearchEngine",+ return_value=mock_engine,+ ),+ ):+ response = auth_client.post(+ f"/library/api/collections/{TEST_COLLECTION_ID}/search",+ data=json.dumps({"query": "date test"}),+ content_type="application/json",+ )++ assert response.status_code == 200+ data = response.get_json()+ result = data["results"][0]+ assert result["created_at"] == "2025-06-15T10:00:00+00:00"++ def test_document_created_at_none(self, auth_client):+ """When created_at is None, return None."""+ mock_collection = MagicMock()+ mock_collection.collection_type = "user_collection"+ mock_collection.name = "Docs"++ mock_doc_row = MagicMock()+ mock_doc_row.document_id = "doc-no-date"+ mock_doc_row.file_type = "pdf"+ mock_doc_row.original_url = None+ mock_doc_row.created_at = None++ call_count = 0++ @contextmanager+ def mock_session(*_args, **_kwargs):+ nonlocal call_count+ call_count += 1+ db_session = MagicMock()+ if call_count == 1:+ db_session.query.return_value.filter_by.return_value.first.return_value = mock_collection+ else:+ db_session.query.return_value.filter.return_value.all.return_value = [+ mock_doc_row+ ]+ yield db_session++ fake_results = [+ {+ "title": "No Date Doc",+ "snippet": "s",+ "relevance_score": 0.9,+ "metadata": {"document_id": "doc-no-date"},+ }+ ]+ mock_engine = MagicMock()+ mock_engine.search.return_value = fake_results++ with (+ patch(+ "local_deep_research.database.session_context.get_user_db_session",+ mock_session,+ ),+ patch(+ "local_deep_research.web_search_engines.engines.search_engine_collection.CollectionSearchEngine",+ return_value=mock_engine,+ ),+ ):+ response = auth_client.post(+ f"/library/api/collections/{TEST_COLLECTION_ID}/search",+ data=json.dumps({"query": "date test"}),+ content_type="application/json",+ )++ assert response.status_code == 200+ data = response.get_json()+ result = data["results"][0]+ assert result["created_at"] is None++ def test_research_created_at_as_string_passthrough(self, auth_client):+ """When research_created_at is already a string, return as-is."""+ mock_collection = MagicMock()+ mock_collection.collection_type = "research_history"+ mock_collection.name = "Research History"++ mock_research_row = MagicMock()+ mock_research_row.document_id = "rdoc-1"+ mock_research_row.source_type_name = "source"+ mock_research_row.research_id = 42+ mock_research_row.research_title = "Test Research"+ mock_research_row.research_query = "test query"+ mock_research_row.research_created_at = "2025-03-20T12:00:00+00:00"++ call_count = 0++ @contextmanager+ def mock_session(*_args, **_kwargs):+ nonlocal call_count+ call_count += 1+ db_session = MagicMock()+ if call_count == 1:+ # Collection lookup+ db_session.query.return_value.filter_by.return_value.first.return_value = mock_collection+ else:+ # Both _enrich_with_research_metadata (outerjoin chain) and+ # _enrich_with_document_metadata (filter chain) go through here.+ # MagicMock auto-chains, so .outerjoin().outerjoin().filter().all()+ # returns the same mock chain ending in .all()+ q = db_session.query.return_value+ q.outerjoin.return_value = q+ q.filter.return_value = q+ q.all.return_value = (+ [mock_research_row] if call_count == 2 else []+ )+ yield db_session++ fake_results = [+ {+ "title": "Result",+ "snippet": "s",+ "relevance_score": 0.8,+ "metadata": {"document_id": "rdoc-1"},+ }+ ]+ mock_engine = MagicMock()+ mock_engine.search.return_value = fake_results++ with (+ patch(+ "local_deep_research.database.session_context.get_user_db_session",+ mock_session,+ ),+ patch(+ "local_deep_research.web_search_engines.engines.search_engine_collection.CollectionSearchEngine",+ return_value=mock_engine,+ ),+ ):+ response = auth_client.post(+ f"/library/api/collections/{TEST_COLLECTION_ID}/search",+ data=json.dumps({"query": "research date"}),+ content_type="application/json",+ )++ assert response.status_code == 200+ data = response.get_json()+ result = data["results"][0]+ assert result["research_created_at"] == "2025-03-20T12:00:00+00:00"