~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: Fix news subscription system issues
LearningCircuit3c7143a03556
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex ec23fdf885..63c6994331 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -564,7 +564,9 @@ class DatabaseManager:def create_thread_connection():"""Create a SQLCipher connection for this thread."""try:- conn = sqlcipher3.connect(str(db_path))+ conn = sqlcipher3.connect(+ str(db_path), check_same_thread=False+ )cursor = conn.cursor()# Use centralized SQLCipher setupdiff --git a/src/local_deep_research/news/api.py b/src/local_deep_research/news/api.pyindex 14cd0f4601..94f4d8937a 100644--- a/src/local_deep_research/news/api.py+++ b/src/local_deep_research/news/api.py@@ -10,7 +10,7 @@ import reimport jsonfrom .recommender.topic_based import TopicBasedRecommender-from .recommender.simple_feed import generate_welcome_feed+# Removed welcome feed import - no placeholders# get_db_setting not available in merged codebase@@ -100,18 +100,24 @@ def get_news_feed(results = [{"id": r.id,- "uuid_id": r.uuid_id,+ "uuid_id": r.id, # In ResearchHistory, id is the UUID"query": r.query,- "title": r.title, # Include title field- "created_at": r.created_at.isoformat()- if r.created_at- else None,- "completed_at": r.completed_at.isoformat()+ "title": r.title+ if hasattr(r, "title")+ else None, # Include title field if exists+ "created_at": r.created_at if r.created_at else None,+ "completed_at": r.completed_atif r.completed_atelse None,- "duration_seconds": r.duration_seconds,- "report_path": r.report_path,- "report_content": r.report_content, # Include database content+ "duration_seconds": r.duration_seconds+ if hasattr(r, "duration_seconds")+ else None,+ "report_path": r.report_path+ if hasattr(r, "report_path")+ else None,+ "report_content": r.report_content+ if hasattr(r, "report_content")+ else None, # Include database content"research_meta": r.research_meta,"status": r.status,}@@ -121,7 +127,11 @@ def get_news_feed(logger.info(f"Database returned {len(results)} research items")if results and len(results) > 0:logger.info(f"First row keys: {list(results[0].keys())}")- logger.info(f"First row data: {results[0]}")+ # Log first few items' metadata+ for i, row in enumerate(results[:3]):+ logger.info(+ f"Item {i}: query='{row['query'][:50]}...', has meta={bool(row.get('research_meta'))}"+ )# Process results to find news itemsprocessed_count = 0@@ -133,11 +143,13 @@ def get_news_feed(metadata = {}if row.get("research_meta"):try:- metadata = json.loads(row["research_meta"])- except json.JSONDecodeError as e:- logger.exception(- f"Error parsing metadata JSON: {e}"- )+ # Handle both dict and string formats+ if isinstance(row["research_meta"], dict):+ metadata = row["research_meta"]+ else:+ metadata = json.loads(row["research_meta"])+ except (json.JSONDecodeError, TypeError) as e:+ logger.exception(f"Error parsing metadata: {e}")metadata = {}# Check if this has news metadata (generated_headline or generated_topics)@@ -164,6 +176,13 @@ def get_news_feed(or "latest news" in query_lower)+ # Log the decision for first few items+ if processed_count < 3 or error_count < 3:+ logger.info(+ f"Item check: query='{row['query'][:30]}...', is_news_search={metadata.get('is_news_search')}, "+ f"has_news_metadata={has_news_metadata}, is_news_query={is_news_query}"+ )+# Only show items that have news metadata or are news queriesif is_news_query:processed_count += 1@@ -358,17 +377,27 @@ def get_news_feed(continuelogger.info(- f"Processing summary: processed={processed_count}, errors={error_count}, added={len(news_items)}"+ f"Processing summary: total_results={len(results)}, processed={processed_count}, "+ f"errors={error_count}, added={len(news_items)}")+ # Log subscription-specific items if we were filtering+ if subscription_id and subscription_id != "all":+ sub_items = [+ item for item in news_items if item.get("is_news", False)+ ]+ logger.info(+ f"Subscription {subscription_id}: found {len(sub_items)} items"+ )+except Exception as db_error:logger.exception(f"Database error in research history: {db_error}")# Continue with what we have from news_items table- # If no news items found from either source, show welcome feed+ # If no news items found, return empty listif not news_items:- logger.info("No news items found, showing welcome feed")- news_items = generate_welcome_feed()+ logger.info("No news items found, returning empty list")+ news_items = []logger.info(f"Returning {len(news_items)} news items to client")diff --git a/src/local_deep_research/news/flask_api.py b/src/local_deep_research/news/flask_api.pyindex 97e86869cc..422e798278 100644--- a/src/local_deep_research/news/flask_api.py+++ b/src/local_deep_research/news/flask_api.py@@ -51,6 +51,7 @@ def get_news_feed() -> Dict[str, Any]:try:# Get current user (login_required ensures we have one)user_id = get_user_id()+ logger.info(f"News feed requested by user: {user_id}")# Get query parameterslimit = int(request.args.get("limit", DEFAULT_FEED_LIMIT))@@ -59,6 +60,10 @@ def get_news_feed() -> Dict[str, Any]:focus = request.args.get("focus")subscription_id = request.args.get("subscription_id")+ logger.info(+ f"News feed params: limit={limit}, subscription_id={subscription_id}, focus={focus}"+ )+# Call the direct API function (now synchronous)result = api.get_news_feed(user_id=user_id,diff --git a/src/local_deep_research/news/folder_manager.py b/src/local_deep_research/news/folder_manager.pyindex 16969da434..275a735916 100644--- a/src/local_deep_research/news/folder_manager.py+++ b/src/local_deep_research/news/folder_manager.py@@ -19,10 +19,10 @@ class FolderManager:self.session = sessiondef get_user_folders(self, user_id: str) -> List[SubscriptionFolder]:- """Get all folders for a user."""+ """Get all folders for a user (user_id parameter kept for API compatibility)."""+ # In per-user databases, all folders belong to the current userreturn (self.session.query(SubscriptionFolder)- .filter_by(user_id=user_id).order_by(SubscriptionFolder.name).all())@@ -30,12 +30,11 @@ class FolderManager:def create_folder(self, user_id: str, name: str, description: Optional[str] = None) -> SubscriptionFolder:- """Create a new folder."""+ """Create a new folder (user_id parameter kept for API compatibility)."""import uuidfolder = SubscriptionFolder(id=str(uuid.uuid4()),- user_id=user_id,name=name,description=description,)@@ -54,7 +53,6 @@ class FolderManager:for key, value in kwargs.items():if hasattr(folder, key) and key not in ["id",- "user_id","created_at",]:setattr(folder, key, value)@@ -96,7 +94,7 @@ class FolderManager:for folder in folders:subs = (self.session.query(BaseSubscription)- .filter_by(user_id=user_id, folder=folder.name, status="active")+ .filter_by(folder=folder.name, status="active").all())@@ -110,7 +108,7 @@ class FolderManager:# Get uncategorized subscriptionsuncategorized = (self.session.query(BaseSubscription)- .filter_by(user_id=user_id, folder=None, status="active")+ .filter_by(folder=None, status="active").all())@@ -131,7 +129,7 @@ class FolderManager:return Nonefor key, value in kwargs.items():- if hasattr(sub, key) and key not in ["id", "user_id", "created_at"]:+ if hasattr(sub, key) and key not in ["id", "created_at"]:setattr(sub, key, value)# Recalculate next_refresh if refresh_interval_hours changed@@ -179,16 +177,13 @@ class FolderManager:return Truedef get_subscription_stats(self, user_id: str) -> Dict[str, Any]:- """Get subscription statistics for a user."""- total = (- self.session.query(BaseSubscription)- .filter_by(user_id=user_id)- .count()- )+ """Get subscription statistics for a user (user_id kept for API compatibility)."""+ # In per-user databases, all data belongs to the current user+ total = self.session.query(BaseSubscription).count()active = (self.session.query(BaseSubscription)- .filter_by(user_id=user_id, status="active")+ .filter_by(status="active").count())@@ -196,9 +191,7 @@ class FolderManager:for sub_type in ["search", "topic"]:count = (self.session.query(BaseSubscription)- .filter_by(- user_id=user_id, subscription_type=sub_type, status="active"- )+ .filter_by(subscription_type=sub_type, status="active").count())by_type[sub_type] = countdiff --git a/src/local_deep_research/news/subscription_manager/scheduler.py b/src/local_deep_research/news/subscription_manager/scheduler.pyindex f557ac935b..404055437b 100644--- a/src/local_deep_research/news/subscription_manager/scheduler.py+++ b/src/local_deep_research/news/subscription_manager/scheduler.py@@ -726,16 +726,106 @@ class NewsScheduler:settings_manager = SettingsManager(db)settings_snapshot = settings_manager.get_settings_snapshot()- # Generate a descriptive title+ # Get the report content - check both 'report' and 'summary' fields+ report_content = serializable_result.get(+ "report"+ ) or serializable_result.get("summary")++ # Extract sources/links from the result+ sources = serializable_result.get("sources", [])++ # First add the sources/references section if we have sources+ if report_content and sources:+ # Import utilities for formatting links+ from ...utilities.search_utilities import (+ format_links_to_markdown,+ )++ # Format the links/citations+ formatted_links = format_links_to_markdown(sources)++ # Add references section to the report+ if formatted_links:+ report_content = f"{report_content}\n\n## Sources\n\n{formatted_links}"++ # Then format citations in the report content+ if report_content:+ # Import citation formatter+ from ...text_optimization.citation_formatter import (+ CitationFormatter,+ CitationMode,+ )+ from ...config.search_config import (+ get_setting_from_snapshot,+ )++ # Get citation format from settings+ citation_format = get_setting_from_snapshot(+ "report.citation_format", "domain_id_hyperlinks"+ )+ mode_map = {+ "number_hyperlinks": CitationMode.NUMBER_HYPERLINKS,+ "domain_hyperlinks": CitationMode.DOMAIN_HYPERLINKS,+ "domain_id_hyperlinks": CitationMode.DOMAIN_ID_HYPERLINKS,+ "domain_id_always_hyperlinks": CitationMode.DOMAIN_ID_ALWAYS_HYPERLINKS,+ "no_hyperlinks": CitationMode.NO_HYPERLINKS,+ }+ mode = mode_map.get(+ citation_format, CitationMode.DOMAIN_ID_HYPERLINKS+ )+ formatter = CitationFormatter(mode=mode)++ # Format citations within the content+ report_content = formatter.format_document(report_content)++ if not report_content:+ # If neither field exists, use the full result as JSON+ report_content = json.dumps(serializable_result)++ # Generate headline and topics for news searches+ from ...news.utils.headline_generator import generate_headline+ from ...news.utils.topic_generator import generate_topics++ query_text = result.get(+ "query", subscription.get("query", "News Update")+ )++ # Generate headline from the actual research findings+ logger.info(+ f"Generating headline for subscription {subscription_id}"+ )+ generated_headline = generate_headline(+ query=query_text,+ findings=report_content,+ max_length=200, # Allow longer headlines for news+ )++ # Generate topics from the findings+ logger.info(+ f"Generating topics for subscription {subscription_id}"+ )+ generated_topics = generate_topics(+ query=query_text,+ findings=report_content,+ category=subscription.get("name", "News"),+ max_topics=6,+ )++ logger.info(+ f"Generated headline: {generated_headline}, topics: {generated_topics}"+ )++ # Get subscription name for metadatasubscription_name = subscription.get("name", "")- if subscription_name:- title = f"{subscription_name} - {datetime.now().strftime('%Y-%m-%d %H:%M')}"++ # Use generated headline as title, or fallback+ if generated_headline:+ title = generated_headlineelse:- # Use query as title, truncated- query_text = result.get(- "query", subscription.get("query", "News Update")- )- title = f"{query_text[:60]}... - {datetime.now().strftime('%Y-%m-%d %H:%M')}"+ if subscription_name:+ title = f"{subscription_name} - {datetime.now().strftime('%Y-%m-%d %H:%M')}"+ else:+ title = f"{query_text[:60]}... - {datetime.now().strftime('%Y-%m-%d %H:%M')}"# Create research history entryhistory_entry = ResearchHistory(@@ -753,6 +843,8 @@ class NewsScheduler:"username": username,"subscription_name": subscription_name, # Store subscription name for display"settings_snapshot": settings_snapshot, # Store settings snapshot for later retrieval+ "generated_headline": generated_headline, # Store generated headline for news display+ "generated_topics": generated_topics, # Store topics for categorization},)db.add(history_entry)@@ -761,15 +853,7 @@ class NewsScheduler:# Store the report content using storage abstractionfrom ...storage import get_report_storage- # Get the report content - check both 'report' and 'summary' fields- report_content = serializable_result.get(- "report"- ) or serializable_result.get("summary")- if not report_content:- # If neither field exists, use the full result as JSON- report_content = json.dumps(serializable_result)-- # Use storage to save the report+ # Use storage to save the report (report_content already retrieved above)storage = get_report_storage(session=db)storage.save_report(research_id=research_id,diff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.pyindex 71f5afb5b8..b4cd691fd6 100644--- a/src/local_deep_research/web/queue/processor_v2.py+++ b/src/local_deep_research/web/queue/processor_v2.py@@ -10,7 +10,6 @@ from typing import Setfrom loguru import loggerfrom ...database.encrypted_db import db_manager-from ...settings import SettingsManagerfrom ...database.models import (QueuedResearch,ResearchHistory,@@ -43,38 +42,22 @@ class QueueProcessorV2:self.running = Falseself.thread = None- # Get settings using a temporary session- # This is initialization code, so we need to get system-wide settings- try:- # Use the system database to get default settings- from ...database.session_context import get_system_db_session-- with get_system_db_session() as session:- settings_manager = SettingsManager(session)- self.max_concurrent_per_user = int(- settings_manager.get_setting(- "app.max_concurrent_researches", 3- )- )- # Get queue mode from settings- queue_mode = settings_manager.get_setting(- "app.queue_mode", "direct"- )- self.direct_mode = queue_mode.lower() == "direct"- except Exception as e:- logger.warning(f"Could not get settings, using defaults: {e}")- self.max_concurrent_per_user = 3- self.direct_mode = True+ # In the new per-user encrypted database architecture,+ # there's no system database for global settings.+ # Use defaults for queue processor configuration.+ self.max_concurrent_per_user = 3+ self.direct_mode = True++ # Log configuration+ logger.info(+ "Queue processor using default configuration "+ "(per-user encrypted databases don't have system-wide settings)"+ )# Track which users we should checkself._users_to_check: Set[str] = set()self._users_lock = threading.Lock()- logger.info(- f"Queue processor initialized in {'DIRECT' if self.direct_mode else 'QUEUE'} mode, "- f"max concurrent: {self.max_concurrent_per_user}"- )-def start(self):"""Start the queue processor thread."""if self.running: