Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

feat: Add news subscription and aggregation system

LearningCircuit039aa8b4fe24
diff --git a/examples/news_example.py b/examples/news_example.py
new file mode 100644
index 0000000000..5e715b56ce
--- /dev/null
+++ b/examples/news_example.py
@@ -0,0 +1,192 @@
+#!/usr/bin/env python
+"""
+Example usage of the LDR News module.
+
+This script demonstrates how to use the news aggregation features
+both programmatically and through the CLI.
+"""
+
+import asyncio
+from local_deep_research.news import (
+ get_news_feed,
+ research_news_item,
+ submit_news_feedback,
+ save_news_preferences,
+ get_news_categories,
+)
+
+
+async def basic_news_example():
+ """Basic example of getting news feed."""
+ print("=== Basic News Feed Example ===\n")
+
+ # Get latest news using default settings
+ result = await get_news_feed(limit=5)
+
+ print(f"Found {len(result['news_items'])} news items:")
+ print(f"Generated at: {result['generated_at']}")
+ print(f"Search strategy: {result.get('search_strategy', 'default')}\n")
+
+ # Display news items
+ for i, item in enumerate(result["news_items"], 1):
+ print(f"{i}. {item.get('headline', 'No headline')}")
+ print(f" Category: {item.get('category', 'Unknown')}")
+ print(f" Impact: {item.get('impact_score', 0)}/10")
+ print(f" Summary: {item.get('summary', 'No summary')[:100]}...")
+ print()
+
+
+async def focused_news_example():
+ """Example of getting focused news."""
+ print("\n=== Focused News Example ===\n")
+
+ # Get technology-focused news
+ result = await get_news_feed(
+ focus="artificial intelligence technology",
+ limit=5,
+ search_strategy="source-based", # Use a different strategy
+ )
+
+ print(f"Found {len(result['news_items'])} tech news items:")
+
+ for item in result["news_items"]:
+ print(f"- {item.get('headline', 'No headline')}")
+ if item.get("surprising_element"):
+ print(f" Surprising: {item['surprising_element']}")
+
+
+async def news_research_example():
+ """Example of researching a specific news item."""
+ print("\n=== News Research Example ===\n")
+
+ # First get some news
+ news_result = await get_news_feed(limit=3)
+
+ if news_result["news_items"]:
+ # Research the first news item
+ first_item = news_result["news_items"][0]
+ news_id = first_item.get("id")
+
+ print(f"Researching: {first_item.get('headline', 'Unknown')}")
+ print("Running quick research...\n")
+
+ research = await research_news_item(news_id, depth="quick")
+
+ print("Research Summary:")
+ print(research.get("summary", "No summary available"))
+
+ if research.get("sources"):
+ print("\nTop Sources:")
+ for source in research["sources"][:3]:
+ print(f"- {source}")
+
+
+async def user_preferences_example():
+ """Example of setting user preferences."""
+ print("\n=== User Preferences Example ===\n")
+
+ # Define preferences
+ preferences = {
+ "categories": ["tech", "science", "economy"],
+ "impact_threshold": 7, # Only show high-impact news
+ "focus_preferences": {
+ "surprising": True,
+ "breaking": True,
+ "positive": False,
+ },
+ "custom_search_terms": "AI quantum computing",
+ "search_strategy": "focused-iteration",
+ }
+
+ # Save preferences
+ result = await save_news_preferences("example_user", preferences)
+ print("Saved preferences:", result["preferences_saved"])
+
+ # Get personalized news
+ personalized = await get_news_feed(user_id="example_user", limit=5)
+
+ print("\nPersonalized news (impact >= 7):")
+ for item in personalized["news_items"]:
+ print(
+ f"- [{item.get('impact_score', 0)}/10] {item.get('headline', 'Unknown')}"
+ )
+
+
+async def news_categories_example():
+ """Example of getting news categories."""
+ print("\n=== News Categories Example ===\n")
+
+ result = await get_news_categories()
+
+ print(f"Categories from last {result['time_range']}:")
+ print(f"Total items: {result['total_items']}\n")
+
+ for cat_info in result["categories"]:
+ name = cat_info["name"]
+ count = cat_info["count"]
+ percentage = (
+ (count / result["total_items"] * 100)
+ if result["total_items"] > 0
+ else 0
+ )
+ print(f"{name:15} {count:3} items ({percentage:5.1f}%)")
+
+
+async def feedback_example():
+ """Example of submitting feedback on news."""
+ print("\n=== Feedback Example ===\n")
+
+ # Get some news
+ news = await get_news_feed(limit=3)
+
+ if news["news_items"]:
+ item = news["news_items"][0]
+ news_id = item.get("id")
+
+ print(f"Upvoting: {item.get('headline', 'Unknown')}")
+
+ # Submit feedback
+ result = await submit_news_feedback(news_id, "up", "example_user")
+
+ print(
+ f"New vote counts - Up: {result['upvotes']}, Down: {result['downvotes']}"
+ )
+
+
+async def main():
+ """Run all examples."""
+
+ # Basic examples
+ await basic_news_example()
+ await focused_news_example()
+
+ # Advanced examples
+ await news_research_example()
+ await user_preferences_example()
+ await news_categories_example()
+ await feedback_example()
+
+ print("\n=== CLI Usage Examples ===\n")
+ print("You can also use the news feature from the command line:")
+ print()
+ print("# Get latest news feed")
+ print("python -m local_deep_research.news.cli news feed")
+ print()
+ print("# Get tech-focused news")
+ print(
+ "python -m local_deep_research.news.cli news feed --focus technology --limit 10"
+ )
+ print()
+ print("# Research a specific news item")
+ print("python -m local_deep_research.news.cli news research <news_id>")
+ print()
+ print("# Start background scheduler")
+ print("python -m local_deep_research.news.cli news scheduler --interval 30")
+ print()
+ print("# Show news categories")
+ print("python -m local_deep_research.news.cli news categories")
+
+
+if __name__ == "__main__":
+ # Run the examples
+ asyncio.run(main())
diff --git a/pyproject.toml b/pyproject.toml
index 325df64d90..8330ad29ff 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -67,6 +67,9 @@ dependencies = [
"kaleido==0.2.1",
"aiohttp>=3.9.0",
"tenacity>=8.0.0",
+ "apscheduler>=3.10.0",
+ "rich>=13.0.0",
+ "click>=8.0.0",
]
[project.urls]
diff --git a/scripts/dev/restart_server.sh b/scripts/dev/restart_server.sh
new file mode 100755
index 0000000000..fadbf13ca2
--- /dev/null
+++ b/scripts/dev/restart_server.sh
@@ -0,0 +1,30 @@
+#!/bin/bash
+# Script to restart the LDR server
+
+echo "Stopping existing LDR server..."
+pkill -f "python -m local_deep_research.web.app" 2>/dev/null || echo "No existing server found"
+
+# Wait a moment for the process to stop
+sleep 1
+
+echo "Starting LDR server..."
+# Change to the script's parent directory (project root)
+cd "$(dirname "$0")/../.."
+
+# Start server in background and detach from terminal
+(nohup pdm run python -m local_deep_research.web.app > /tmp/ldr_server.log 2>&1 &) &
+SERVER_PID=$!
+
+# Give it a moment to start
+sleep 2
+
+echo "Server started. PID: $SERVER_PID"
+echo "Logs: /tmp/ldr_server.log"
+echo "URL: http://127.0.0.1:5000"
+echo ""
+echo "To check server status: ps aux | grep 'python -m local_deep_research.web.app'"
+echo "To view logs: tail -f /tmp/ldr_server.log"
+echo "To stop server: pkill -f 'python -m local_deep_research.web.app'"
+
+# Exit immediately - don't wait for background process
+exit 0
diff --git a/scripts/update_news_metadata.py b/scripts/update_news_metadata.py
new file mode 100755
index 0000000000..d615f268f1
--- /dev/null
+++ b/scripts/update_news_metadata.py
@@ -0,0 +1,120 @@
+#!/usr/bin/env python3
+"""
+Update existing research items with generated headlines and topics.
+This script adds generated_headline and generated_topics to research metadata.
+"""
+
+import sys
+import os
+import json
+import logging
+
+# Add the src directory to the path
+sys.path.insert(
+ 0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../src"))
+)
+
+from local_deep_research.web.models.database import get_db_connection
+from local_deep_research.news.utils.headline_generator import generate_headline
+from local_deep_research.news.utils.topic_generator import generate_topics
+
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
+
+
+def update_news_metadata():
+ """Update research items with generated headlines and topics."""
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ # Get all completed research items that might be news
+ cursor.execute("""
+ SELECT id, query, research_meta, report_path
+ FROM research_history
+ WHERE status = 'completed'
+ ORDER BY created_at DESC
+ LIMIT 100
+ """)
+
+ results = cursor.fetchall()
+ updated_count = 0
+
+ for row in results:
+ research_id, query, meta_str, report_path = row
+
+ # Parse metadata
+ metadata = {}
+ if meta_str:
+ try:
+ metadata = json.loads(meta_str)
+ except json.JSONDecodeError:
+ continue
+
+ # Check if this is likely a news item
+ query_lower = query.lower()
+ is_news = (
+ metadata.get("is_news_search")
+ or "news" in query_lower
+ or "breaking" in query_lower
+ or "today" in query_lower
+ )
+
+ if not is_news:
+ continue
+
+ # Skip if already has generated headline/topics
+ if metadata.get("generated_headline") and metadata.get(
+ "generated_topics"
+ ):
+ logger.info(
+ f"Research {research_id} already has generated metadata"
+ )
+ continue
+
+ logger.info(f"Processing research {research_id}: {query[:50]}...")
+
+ # Read report content if available
+ report_content = ""
+ if report_path and os.path.exists(report_path):
+ try:
+ with open(report_path, "r", encoding="utf-8") as f:
+ report_content = f.read()[:2000]
+ except Exception as e:
+ logger.error(f"Error reading report: {e}")
+
+ # Generate headline if not present
+ if not metadata.get("generated_headline"):
+ headline = generate_headline(query, report_content)
+ metadata["generated_headline"] = headline
+ logger.info(f" Generated headline: {headline}")
+
+ # Generate topics if not present
+ if not metadata.get("generated_topics"):
+ topics = generate_topics(
+ query=query,
+ findings=report_content,
+ category=metadata.get("category", "News"),
+ max_topics=6,
+ )
+ metadata["generated_topics"] = topics
+ logger.info(f" Generated topics: {topics}")
+
+ # Update the database
+ cursor.execute(
+ "UPDATE research_history SET research_meta = ? WHERE id = ?",
+ (json.dumps(metadata), research_id),
+ )
+ updated_count += 1
+
+ conn.commit()
+ conn.close()
+
+ logger.info(
+ f"\nUpdated {updated_count} research items with headlines and topics"
+ )
+
+
+if __name__ == "__main__":
+ print("Updating news metadata for existing research items...")
+ update_news_metadata()
+ print("Done!")
diff --git a/src/local_deep_research/advanced_search_system/strategies/news_strategy.py b/src/local_deep_research/advanced_search_system/strategies/news_strategy.py
new file mode 100644
index 0000000000..4c5dad8830
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/strategies/news_strategy.py
@@ -0,0 +1,306 @@
+"""
+News aggregation search strategy for LDR.
+Uses optimized prompts and search patterns for news aggregation.
+"""
+
+from typing import List, Dict, Any, Optional
+from datetime import datetime
+import json
+import re
+from loguru import logger
+
+from .base_strategy import BaseSearchStrategy
+
+
+class NewsAggregationStrategy(BaseSearchStrategy):
+ """
+ Specialized search strategy for news aggregation.
+ Uses single iteration with multiple parallel searches for broad coverage.
+ """
+
+ def __init__(
+ self, model=None, search=None, all_links_of_system=None, **kwargs
+ ):
+ super().__init__(all_links_of_system=all_links_of_system)
+ from ...config.llm_config import get_llm
+ from ...config.search_config import get_search
+
+ self.model = model or get_llm()
+ self.search = search or get_search()
+ self.strategy_name = "news_aggregation"
+ self.max_iterations = 1 # News needs broad coverage, not deep iteration
+ self.questions_per_iteration = 8 # More parallel searches for news
+
+ def generate_questions(self, query: str, context: str) -> List[str]:
+ """Generate news-specific search queries"""
+
+ date_str = datetime.now().strftime("%B %d, %Y")
+
+ # Build diverse news queries
+ base_queries = [
+ f"breaking news today {date_str}",
+ f"major incidents casualties today {date_str}",
+ f"unexpected news surprising today {date_str}",
+ "economic news market movement today",
+ f"political announcements today {date_str}",
+ "technology breakthrough announcement today",
+ "natural disaster emergency today",
+ "international news global impact today",
+ ]
+
+ # If user provided specific focus, add those queries
+ if query and query != "latest important news today":
+ focus_queries = [
+ f"{query} {date_str}",
+ f"{query} breaking news today",
+ f"{query} latest developments",
+ ]
+ return focus_queries + base_queries[:5]
+
+ return base_queries
+
+ async def analyze_findings(
+ self, all_findings: List[Dict]
+ ) -> Dict[str, Any]:
+ """Analyze search results to extract and structure news items"""
+
+ if not all_findings:
+ return {
+ "status": "No news found",
+ "news_items": [],
+ "answer": "No significant news stories found for the specified criteria.",
+ }
+
+ # Format findings for LLM analysis
+ snippets = []
+ for i, finding in enumerate(
+ all_findings[:50]
+ ): # Limit to 50 for token efficiency
+ snippet = {
+ "id": i + 1,
+ "url": finding.get("url", ""),
+ "title": finding.get("title", ""),
+ "snippet": finding.get("snippet", "")[:300]
+ if finding.get("snippet")
+ else "",
+ "content": finding.get("content", "")[:500]
+ if finding.get("content")
+ else "",
+ }
+ snippets.append(snippet)
+
+ # Create structured prompt for news extraction
+ prompt = self._create_news_analysis_prompt(snippets)
+
+ try:
+ response = self.model.invoke(prompt)
+ content = (
+ response.content
+ if hasattr(response, "content")
+ else str(response)
+ )
+
+ # Extract JSON from response
+ news_data = self._extract_json_from_response(content)
+
+ if news_data and "news_items" in news_data:
+ return {
+ "status": "Success",
+ "news_items": news_data["news_items"],
+ "answer": self._format_news_summary(
+ news_data["news_items"]
+ ),
+ }
+ else:
+ # Fallback to simple extraction
+ return self._fallback_news_extraction(snippets)
+
+ except Exception as e:
+ logger.error(f"Error analyzing news findings: {e}")
+ return self._fallback_news_extraction(snippets)
+
+ def _create_news_analysis_prompt(self, snippets: List[Dict]) -> str:
+ """Create the analysis prompt for news extraction"""
+
+ snippet_text = "\n\n".join(
+ [
+ f"[{s['id']}] Source: {s['url']}\n"
+ f"Title: {s['title']}\n"
+ f"Content: {s['snippet'] or s['content']}"
+ for s in snippets
+ ]
+ )
+
+ return f"""
+Analyze these news snippets from search results and create a structured news report.
+Today's date: {datetime.now().strftime("%B %d, %Y")}
+
+{snippet_text}
+
+Create a structured JSON response with the 10 most important news stories:
+{{
+ "news_items": [
+ {{
+ "headline": "8 words max describing the story",
+ "category": "War/Security/Economy/Tech/Politics/Health/Environment/Other",
+ "source_url": "url from snippets",
+ "source_id": "[number] from above",
+ "summary": "3 clear sentences about what happened",
+ "analysis": "Why this matters and what happens next (2 sentences)",
+ "impact_score": 1-10,
+ "entities": {{"people": ["names"], "places": ["locations"], "orgs": ["organizations"]}},
+ "topics": ["topic1", "topic2"],
+ "time_ago": "estimated time (2 hours ago, yesterday, etc)",
+ "is_developing": true/false,
+ "surprising_element": "what makes this unexpected or notable (if any)"
+ }}
+ ]
+}}
+
+PRIORITIZE:
+1. Stories with casualties or significant human impact
+2. Economic impacts over $1 billion
+3. Major political or diplomatic developments
+4. Unexpected or surprising events
+5. Breaking developments from the last 24 hours
+
+Only include stories that are truly newsworthy and significant.
+Ensure variety across different categories when possible.
+"""
+
+ def _extract_json_from_response(self, content: str) -> Optional[Dict]:
+ """Extract JSON from LLM response"""
+ try:
+ # Try to find JSON in the response
+ json_match = re.search(r"\{.*\}", content, re.DOTALL)
+ if json_match:
+ return json.loads(json_match.group())
+ except Exception as e:
+ logger.error(f"Error extracting JSON: {e}")
+ return None
+
+ def _format_news_summary(self, news_items: List[Dict]) -> str:
+ """Format news items into a readable summary"""
+
+ if not news_items:
+ return "No significant news stories found."
+
+ # Group by category
+ by_category = {}
+ for item in news_items:
+ cat = item.get("category", "Other")
+ if cat not in by_category:
+ by_category[cat] = []
+ by_category[cat].append(item)
+
+ # Build summary
+ parts = [f"Found {len(news_items)} significant news stories:\n"]
+
+ for category, items in by_category.items():
+ parts.append(f"\n**{category}** ({len(items)} stories):")
+ for item in items[:3]: # Top 3 per category
+ parts.append(
+ f"- {item['headline']} "
+ f"(Impact: {item.get('impact_score', 'N/A')}/10)"
+ )
+
+ # Add top story details
+ if news_items:
+ top_story = max(news_items, key=lambda x: x.get("impact_score", 0))
+ parts.append(f"\n**Top Story**: {top_story['headline']}")
+ parts.append(f"{top_story.get('summary', 'No summary available')}")
+
+ return "\n".join(parts)
+
+ def _fallback_news_extraction(self, snippets: List[Dict]) -> Dict[str, Any]:
+ """Simple fallback extraction when JSON parsing fails"""
+
+ news_items = []
+ for s in snippets[:10]:
+ if s["title"] and len(s["title"]) > 10:
+ news_items.append(
+ {
+ "headline": s["title"][:60],
+ "category": "Other",
+ "source_url": s["url"],
+ "summary": s["snippet"] or "No summary available",
+ "impact_score": 5,
+ }
+ )
+
+ return {
+ "status": "Fallback extraction",
+ "news_items": news_items,
+ "answer": f"Found {len(news_items)} news stories (simplified extraction)",
+ }
+
+ def analyze_topic(self, query: str) -> Dict:
+ """
+ Analyze a topic for news aggregation.
+
+ Args:
+ query: The news query or focus area
+
+ Returns:
+ Dict containing news findings and formatted output
+ """
+ import asyncio
+
+ # Generate news-specific search queries
+ questions = self.generate_questions(query, "")
+ self.questions_by_iteration[0] = questions
+
+ all_findings = []
+
+ # Search for each question
+ for i, question in enumerate(questions):
+ self._update_progress(
+ f"Searching for: {question}",
+ int((i / len(questions)) * 50),
+ {"phase": "search", "question": question},
+ )
+
+ try:
+ if self.search:
+ results = self.search.run(question)
+ if results:
+ all_findings.extend(results)
+ except Exception as e:
+ logger.error(f"Search error: {e}")
+ continue
+
+ # Analyze findings - handle both sync and async contexts
+ try:
+ # Check if we're already in an async context
+ loop = asyncio.get_event_loop()
+ if loop.is_running():
+ # We're in an async context, create a task
+ import concurrent.futures
+
+ with concurrent.futures.ThreadPoolExecutor() as executor:
+ future = executor.submit(
+ asyncio.run, self.analyze_findings(all_findings)
+ )
+ analysis = future.result()
+ else:
+ # We're in a sync context, use run_until_complete
+ analysis = loop.run_until_complete(
+ self.analyze_findings(all_findings)
+ )
+ except RuntimeError:
+ # No event loop, create one
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+ analysis = loop.run_until_complete(
+ self.analyze_findings(all_findings)
+ )
+
+ return {
+ "findings": all_findings,
+ "iterations": 1,
+ "questions": self.questions_by_iteration,
+ "formatted_findings": analysis.get("answer", "No news found"),
+ "current_knowledge": analysis.get("answer", ""),
+ "news_items": analysis.get("news_items", []),
+ "status": analysis.get("status", "Unknown"),
+ }
diff --git a/src/local_deep_research/api/__init__.py b/src/local_deep_research/api/__init__.py
index 660e2410c0..cee1df3482 100644
--- a/src/local_deep_research/api/__init__.py
+++ b/src/local_deep_research/api/__init__.py
@@ -10,9 +10,39 @@ from .research_functions import (
quick_summary,
)
+try:
+ from ..news import (
+ get_news_feed,
+ research_news_item,
+ submit_news_feedback,
+ save_news_preferences,
+ get_news_categories,
+ )
+
+ NEWS_AVAILABLE = True
+except ImportError:
+ NEWS_AVAILABLE = False
+ # Define placeholders to avoid NameErrors
+ get_news_feed = None
+ research_news_item = None
+ submit_news_feedback = None
+ save_news_preferences = None
+ get_news_categories = None
+
__all__ = [
"quick_summary",
"detailed_research",
"generate_report",
"analyze_documents",
]
+
+if NEWS_AVAILABLE:
+ __all__.extend(
+ [
+ "get_news_feed",
+ "research_news_item",
+ "submit_news_feedback",
+ "save_news_preferences",
+ "get_news_categories",
+ ]
+ )
diff --git a/src/local_deep_research/cli/__init__.py b/src/local_deep_research/cli/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/src/local_deep_research/news/__init__.py b/src/local_deep_research/news/__init__.py
new file mode 100644
index 0000000000..14555afd97
--- /dev/null
+++ b/src/local_deep_research/news/__init__.py
@@ -0,0 +1,21 @@
+"""
+LDR News - AI-powered news aggregation and analysis module.
+"""
+
+# Import core classes
+from .models import BaseSubscription, SubscriptionFolder, UserPreference, Rating
+from .subscription_manager.scheduler import SubscriptionScheduler
+from .folder_manager import FolderManager
+from .subscription_manager import SearchSubscription, TopicSubscription
+
+__all__ = [
+ # Core classes
+ "BaseSubscription",
+ "SubscriptionFolder",
+ "UserPreference",
+ "Rating",
+ "SubscriptionScheduler",
+ "FolderManager",
+ "SearchSubscription",
+ "TopicSubscription",
+]
diff --git a/src/local_deep_research/news/api.py b/src/local_deep_research/news/api.py
new file mode 100644
index 0000000000..9632871742
--- /dev/null
+++ b/src/local_deep_research/news/api.py
@@ -0,0 +1,956 @@
+"""
+Direct API functions for news system.
+These functions can be called directly by scheduler or wrapped by Flask endpoints.
+"""
+
+from typing import Dict, Any, Optional
+from datetime import datetime, timezone
+from loguru import logger
+import re
+import os
+import json
+
+from .core.storage_manager import StorageManager
+from .subscription_manager import SearchSubscription, TopicSubscription
+from .recommender.topic_based import TopicBasedRecommender
+from .recommender.simple_feed import generate_welcome_feed
+from ..api.research_functions import (
+ quick_summary,
+ detailed_research,
+ generate_report,
+)
+from ..utilities.db_utils import get_db_setting
+
+
+# Initialize components
+storage_manager = StorageManager()
+
+# Global recommender instance (can be reused)
+_recommender = None
+
+
+def get_recommender():
+ """Get or create recommender instance"""
+ global _recommender
+ if _recommender is None:
+ _recommender = TopicBasedRecommender()
+ return _recommender
+
+
+def get_news_feed(
+ user_id: str = "anonymous",
+ limit: int = 20,
+ use_cache: bool = True,
+ focus: Optional[str] = None,
+ search_strategy: Optional[str] = None,
+ subscription_id: Optional[str] = None,
+) -> Dict[str, Any]:
+ """
+ Get personalized news feed by pulling from news_items table first, then research history.
+
+ Args:
+ user_id: User identifier
+ limit: Maximum number of cards to return
+ use_cache: Whether to use cached news
+ focus: Optional focus area for news
+ search_strategy: Override default recommendation strategy
+
+ Returns:
+ Dictionary with news items and metadata
+ """
+ try:
+ # Validate limit - allow any positive number
+ if limit < 1:
+ return {
+ "error": "Limit must be at least 1",
+ "news_items": [],
+ }
+
+ logger.info(
+ f"get_news_feed called with user_id={user_id}, limit={limit}"
+ )
+
+ if not get_db_setting("news.enabled", True):
+ return {"error": "News system is disabled", "news_items": []}
+
+ # Import database functions
+ from ..web.models.database import get_db_connection
+
+ news_items = []
+ remaining_limit = limit
+
+ # Query research history from ldr.db for news items
+ logger.info("Getting news items from research history")
+ try:
+ conn = get_db_connection()
+ conn.row_factory = lambda cursor, row: {
+ column[0]: row[idx]
+ for idx, column in enumerate(cursor.description)
+ }
+ cursor = conn.cursor()
+
+ # Get recent researches (including in-progress for testing)
+ if subscription_id and subscription_id != "all":
+ # Filter by subscription
+ query = """
+ SELECT id, query, created_at, completed_at, duration_seconds,
+ report_path, research_meta, status, uuid_id
+ FROM research_history
+ WHERE status = 'completed' -- Only show completed items
+ AND research_meta LIKE ?
+ ORDER BY created_at DESC
+ LIMIT ?
+ """
+ cursor.execute(
+ query,
+ (
+ f'%"subscription_id":"{subscription_id}"%',
+ remaining_limit * 2,
+ ),
+ )
+ else:
+ # Get all researches
+ query = """
+ SELECT id, query, created_at, completed_at, duration_seconds,
+ report_path, research_meta, status, uuid_id
+ FROM research_history
+ WHERE status = 'completed' -- Only show completed items
+ ORDER BY created_at DESC
+ LIMIT ?
+ """
+ cursor.execute(
+ query, (remaining_limit * 2,)
+ ) # Get extra to filter
+ results = cursor.fetchall()
+ conn.close()
+
+ 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]}")
+
+ # Process results to find news items
+ processed_count = 0
+ error_count = 0
+
+ for row in results:
+ try:
+ # Parse metadata
+ metadata = {}
+ if row.get("research_meta"):
+ try:
+ metadata = json.loads(row["research_meta"])
+ except json.JSONDecodeError as e:
+ logger.error(f"Error parsing metadata JSON: {e}")
+ metadata = {}
+
+ # Check if this has news metadata (generated_headline or generated_topics)
+ # or if it's a news-related query
+ has_news_metadata = (
+ metadata.get("generated_headline") is not None
+ or metadata.get("generated_topics") is not None
+ )
+
+ query_lower = row["query"].lower()
+ is_news_query = (
+ has_news_metadata
+ or metadata.get("is_news_search")
+ or metadata.get("search_type") == "news_analysis"
+ or "breaking news" in query_lower
+ or "news stories" in query_lower
+ or (
+ "today" in query_lower
+ and (
+ "news" in query_lower
+ or "breaking" in query_lower
+ )
+ )
+ or "latest news" in query_lower
+ )
+
+ # Only show items that have news metadata or are news queries
+ if is_news_query:
+ processed_count += 1
+ logger.info(
+ f"Processing research item #{processed_count}: {row['query'][:50]}..."
+ )
+
+ # Read the report content if available
+ findings = ""
+ summary = ""
+ report_path_str = row.get(
+ "report_path"
+ ) # Keep the string path for later use
+
+ if report_path_str:
+ try:
+ from pathlib import Path
+
+ report_path = Path(report_path_str)
+ if report_path.exists():
+ content = report_path.read_text(
+ encoding="utf-8"
+ )
+
+ # Handle both old format (with headers) and new format (without)
+ lines = content.split("\n")
+ content_start = 0
+
+ # Skip "# Quick Research Summary" if present
+ for i, line in enumerate(lines):
+ # Skip the header line
+ if (
+ line.strip()
+ == "# Quick Research Summary"
+ ):
+ continue
+ # Skip empty lines at the start
+ if not line.strip():
+ continue
+ # Skip the Query: line if it exists
+ if line.startswith("Query:"):
+ # Find the next non-empty line after Query
+ for j in range(i + 1, len(lines)):
+ if lines[j].strip():
+ content_start = j
+ break
+ break
+ # If we find content that's not a header or query, use it
+ if line.strip() and not line.startswith(
+ "#"
+ ):
+ content_start = i
+ break
+
+ # Get clean content
+ clean_lines = lines[content_start:]
+ clean_content = "\n".join(clean_lines)
+
+ # Extract findings from clean content
+ # Use full content, let frontend handle display
+ findings = clean_content
+
+ # Extract summary from first non-empty line
+ summary = ""
+ for line in clean_lines:
+ if line.strip() and not line.startswith(
+ "#"
+ ):
+ summary = (
+ line.strip()
+ ) # Full summary
+ break
+ except Exception as e:
+ logger.error(f"Error reading report: {e}")
+
+ # Use stored headline/topics if available, otherwise generate
+ original_query = row["query"]
+
+ # Check for pre-generated headline
+ headline = metadata.get("generated_headline")
+
+ # Skip items without meaningful headlines or that are incomplete
+ if (
+ not headline
+ or headline == "[No headline available]"
+ ):
+ logger.debug(
+ f"Skipping item without headline: {row['id']}"
+ )
+ continue
+
+ # Skip items that are still in progress or suspended
+ if row["status"] in ["in_progress", "suspended"]:
+ logger.debug(
+ f"Skipping incomplete item: {row['id']} (status: {row['status']})"
+ )
+ continue
+
+ # Skip items without a valid report path
+ if not report_path_str or not os.path.exists(
+ report_path_str
+ ):
+ logger.debug(
+ f"Skipping item without valid report: {row['id']}"
+ )
+ continue
+
+ # Use ID properly, preferring uuid_id
+ research_id = row.get("uuid_id") or str(row["id"])
+
+ # Use stored category and topics - no defaults
+ category = metadata.get("category")
+ if not category:
+ category = "[Uncategorized]"
+
+ topics = metadata.get("generated_topics")
+ if not topics:
+ topics = ["[No topics]"]
+
+ # Extract top 3 links from the report
+ links = []
+ logger.debug(
+ f"Report path: {report_path_str}, exists: {os.path.exists(report_path_str) if report_path_str else False}"
+ )
+ if report_path_str and os.path.exists(report_path_str):
+ try:
+ # Read the report file to get links
+ with open(
+ report_path_str, "r", encoding="utf-8"
+ ) as f:
+ report_lines = f.readlines()
+
+ link_count = 0
+ for i, line in enumerate(
+ report_lines[:100]
+ ): # Check first 100 lines for links
+ if "URL:" in line:
+ url = line.split("URL:", 1)[1].strip()
+ if url.startswith("http"):
+ # Get the title from the previous line if available
+ title = ""
+ if i > 0:
+ title_line = report_lines[
+ i - 1
+ ].strip()
+ # Remove citation numbers like [12, 26, 19]
+ title = re.sub(
+ r"^\[[^\]]+\]\s*",
+ "",
+ title_line,
+ ).strip()
+
+ if not title:
+ # Use domain as fallback
+ domain = url.split("//")[
+ -1
+ ].split("/")[0]
+ title = domain.replace(
+ "www.", ""
+ )
+
+ links.append(
+ {
+ "url": url,
+ "title": title[:50] + "..."
+ if len(title) > 50
+ else title,
+ }
+ )
+ link_count += 1
+ logger.debug(
+ f"Found link: {title} - {url}"
+ )
+ except Exception as e:
+ logger.error(
+ f"Error extracting links from {report_path_str}: {e}"
+ )
+
+ # Create news item from research
+ news_item = {
+ "id": f"news-{research_id}",
+ "headline": headline,
+ "category": category,
+ "summary": summary
+ or f"Research analysis for: {headline[:100]}",
+ "findings": findings,
+ "impact_score": metadata.get(
+ "impact_score", 0
+ ), # 0 indicates missing
+ "time_ago": _format_time_ago(row["created_at"]),
+ "upvotes": metadata.get("upvotes", 0),
+ "downvotes": metadata.get("downvotes", 0),
+ "source_url": f"/results/{research_id}",
+ "topics": topics, # Use generated topics
+ "links": links, # Add extracted links
+ "research_id": research_id,
+ "created_at": row["created_at"],
+ "duration_seconds": row.get("duration_seconds", 0),
+ "original_query": original_query, # Keep original query for reference
+ "is_news": metadata.get(
+ "is_news_search", False
+ ), # Flag for news searches
+ "news_date": metadata.get(
+ "news_date"
+ ), # If specific date for news
+ "news_source": metadata.get(
+ "news_source"
+ ), # If from specific source
+ "priority": metadata.get(
+ "priority", "normal"
+ ), # Priority level
+ }
+
+ news_items.append(news_item)
+ logger.info(f"Added news item: {headline[:50]}...")
+
+ if len(news_items) >= limit:
+ break
+
+ except Exception as e:
+ error_count += 1
+ logger.error(
+ f"Error processing research item: {e}", exc_info=True
+ )
+ logger.error(
+ f"Failed item query: {row.get('query', 'UNKNOWN')[:100]}"
+ )
+ continue
+
+ logger.info(
+ f"Processing summary: processed={processed_count}, errors={error_count}, added={len(news_items)}"
+ )
+
+ except Exception as db_error:
+ logger.error(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 not news_items:
+ logger.info("No news items found, showing welcome feed")
+ news_items = generate_welcome_feed()
+
+ logger.info(f"Returning {len(news_items)} news items to client")
+
+ # Determine the source
+ source = (
+ "news_items"
+ if any(item.get("is_news", False) for item in news_items)
+ else "research_history"
+ )
+
+ return {
+ "news_items": news_items[:limit],
+ "generated_at": datetime.now(timezone.utc).isoformat(),
+ "focus": focus,
+ "search_strategy": search_strategy or "default",
+ "total_items": len(news_items),
+ "source": source,
+ }
+
+ except Exception as e:
+ logger.error(f"Error getting news feed: {e}")
+ return {"error": str(e), "news_items": []}
+
+
+def debug_research_items():
+ """Debug function to check what's in the database."""
+ try:
+ from ..web.models.database import get_db_connection
+
+ conn = get_db_connection()
+ conn.row_factory = lambda cursor, row: {
+ column[0]: row[idx] for idx, column in enumerate(cursor.description)
+ }
+ cursor = conn.cursor()
+
+ # Count all research items
+ cursor.execute("SELECT COUNT(*) as total FROM research_history")
+ total = cursor.fetchone()["total"]
+
+ # Count by status
+ cursor.execute("""
+ SELECT status, COUNT(*) as count
+ FROM research_history
+ GROUP BY status
+ """)
+ status_counts = cursor.fetchall()
+
+ # Get recent items
+ cursor.execute("""
+ SELECT id, query, status, created_at
+ FROM research_history
+ ORDER BY created_at DESC
+ LIMIT 10
+ """)
+ recent = cursor.fetchall()
+
+ conn.close()
+
+ return {
+ "total_items": total,
+ "by_status": status_counts,
+ "recent_items": recent,
+ }
+ except Exception as e:
+ return {"error": str(e)}
+
+
+def get_subscription_history(
+ subscription_id: str, limit: int = 20
+) -> Dict[str, Any]:
+ """
+ Get research history for a specific subscription.
+
+ Args:
+ subscription_id: The subscription UUID
+ limit: Maximum number of history items to return
+
+ Returns:
+ Dict containing subscription info and its research history
+ """
+ try:
+ from ..web.models.database import get_db_connection
+ from .database import get_news_session
+ from .models import BaseSubscription
+
+ # Get subscription details using ORM from news database
+ with get_news_session() as session:
+ subscription = (
+ session.query(BaseSubscription)
+ .filter_by(id=subscription_id)
+ .first()
+ )
+
+ if not subscription:
+ return {"error": "Subscription not found", "history": []}
+
+ # Convert to dict for response
+ subscription_dict = {
+ "id": subscription.id,
+ "query_or_topic": subscription.query_or_topic,
+ "subscription_type": subscription.subscription_type,
+ "refresh_interval_hours": subscription.refresh_interval_hours,
+ "refresh_count": subscription.refresh_count or 0,
+ "created_at": subscription.created_at.isoformat()
+ if subscription.created_at
+ else None,
+ "next_refresh": subscription.next_refresh.isoformat()
+ if subscription.next_refresh
+ else None,
+ }
+
+ # Now get research history from the research database
+ # Still need to use raw SQL for JSON query on research_meta
+ conn = get_db_connection()
+ conn.row_factory = lambda cursor, row: {
+ column[0]: row[idx] for idx, column in enumerate(cursor.description)
+ }
+ cursor = conn.cursor()
+
+ # Get all research runs that were triggered by this subscription
+ # Look for subscription_id in the research_meta JSON
+ # Note: JSON format has space after colon
+ like_pattern = f'%"subscription_id": "{subscription_id}"%'
+ logger.info(
+ f"Searching for research history with pattern: {like_pattern}"
+ )
+
+ cursor.execute(
+ """
+ SELECT id, uuid_id, query, status, created_at, completed_at,
+ duration_seconds, research_meta, report_path
+ FROM research_history
+ WHERE research_meta LIKE ?
+ ORDER BY created_at DESC
+ LIMIT ?
+ """,
+ (like_pattern, limit),
+ )
+
+ history_items = cursor.fetchall()
+ conn.close()
+
+ # Process history items
+ processed_history = []
+ for item in history_items:
+ processed_item = {
+ "research_id": item.get("uuid_id") or str(item.get("id")),
+ "query": item["query"],
+ "status": item["status"],
+ "created_at": item["created_at"],
+ "completed_at": item.get("completed_at"),
+ "duration_seconds": item.get("duration_seconds", 0),
+ "url": f"/progress/{item.get('uuid_id') or item.get('id')}",
+ }
+
+ # Parse metadata if available to get headline and topics
+ if item.get("research_meta"):
+ try:
+ meta = json.loads(item["research_meta"])
+ processed_item["triggered_by"] = meta.get(
+ "triggered_by", "subscription"
+ )
+ # Add headline and topics from metadata
+ processed_item["headline"] = meta.get(
+ "generated_headline", "[No headline]"
+ )
+ processed_item["topics"] = meta.get("generated_topics", [])
+ except Exception:
+ processed_item["headline"] = "[No headline]"
+ processed_item["topics"] = []
+ else:
+ processed_item["headline"] = "[No headline]"
+ processed_item["topics"] = []
+
+ processed_history.append(processed_item)
+
+ return {
+ "subscription": subscription_dict,
+ "history": processed_history,
+ "total_runs": len(processed_history),
+ }
+
+ except Exception as e:
+ logger.error(f"Error getting subscription history: {e}")
+ return {"error": str(e), "history": []}
+
+
+def _format_time_ago(timestamp: str) -> str:
+ """Format timestamp as 'X hours ago' string."""
+ try:
+ from dateutil import parser
+ from loguru import logger
+
+ dt = parser.parse(timestamp)
+
+ # If dt is naive, assume it's in UTC
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo=timezone.utc)
+
+ now = datetime.now(timezone.utc)
+ diff = now - dt
+
+ if diff.days > 0:
+ return f"{diff.days} day{'s' if diff.days > 1 else ''} ago"
+ elif diff.seconds > 3600:
+ hours = diff.seconds // 3600
+ return f"{hours} hour{'s' if hours > 1 else ''} ago"
+ elif diff.seconds > 60:
+ minutes = diff.seconds // 60
+ return f"{minutes} minute{'s' if minutes > 1 else ''} ago"
+ else:
+ return "Just now"
+ except Exception as e:
+ logger.error(f"Error parsing timestamp '{timestamp}': {e}")
+ return "Recently"
+
+
+def get_subscriptions(user_id: str) -> Dict[str, Any]:
+ """
+ Get all subscriptions for a user.
+
+ Args:
+ user_id: User identifier
+
+ Returns:
+ Dictionary with subscriptions list
+ """
+ try:
+ # Get subscriptions from storage
+ subscriptions = storage_manager.subscriptions.list({"user_id": user_id})
+
+ # Get database connection to count research runs
+ from ..web.models.database import get_db_connection
+
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ # Convert to API format
+ sub_list = []
+ for sub in subscriptions:
+ # Count actual research runs for this subscription
+ cursor.execute(
+ """
+ SELECT COUNT(*)
+ FROM research_history
+ WHERE research_meta LIKE ?
+ """,
+ (f'%"subscription_id": "{sub["id"]}"%',),
+ )
+ total_runs = cursor.fetchone()[0]
+
+ # Convert storage dict to API format
+ sub_dict = {
+ "id": sub["id"],
+ "query": sub["query_or_topic"],
+ "type": sub["subscription_type"],
+ "refresh_hours": sub["refresh_interval_hours"],
+ "created_at": sub["created_at"].isoformat()
+ if sub["created_at"]
+ else None,
+ "next_refresh": sub["next_refresh"].isoformat()
+ if sub["next_refresh"]
+ else None,
+ "last_refreshed": sub["last_refresh"].isoformat()
+ if sub.get("last_refresh")
+ else None,
+ "is_active": sub["status"] == "active",
+ "total_runs": total_runs, # Use actual count from research_history
+ "name": sub.get("name", ""),
+ "folder_id": sub.get("folder_id"),
+ }
+ sub_list.append(sub_dict)
+
+ conn.close()
+ return {"subscriptions": sub_list, "total": len(sub_list)}
+
+ except Exception as e:
+ logger.error(f"Error getting subscriptions: {e}")
+ return {"error": str(e), "subscriptions": []}
+
+
+def create_subscription(
+ user_id: str,
+ query: str,
+ subscription_type: str = "search",
+ refresh_hours: int = 4,
+ source_research_id: Optional[str] = None,
+) -> Dict[str, Any]:
+ """
+ Create a new subscription for user.
+
+ Args:
+ user_id: User identifier
+ query: Search query or topic
+ subscription_type: "search" or "topic"
+ refresh_hours: Refresh interval in hours
+
+ Returns:
+ Dictionary with subscription details
+ """
+ try:
+ # Create appropriate subscription type
+ if subscription_type == "search":
+ subscription = SearchSubscription(
+ query=query,
+ user_id=user_id,
+ refresh_interval_hours=refresh_hours,
+ )
+ elif subscription_type == "topic":
+ subscription = TopicSubscription(
+ topic=query,
+ user_id=user_id,
+ refresh_interval_hours=refresh_hours,
+ )
+ else:
+ raise ValueError(f"Unknown subscription type: {subscription_type}")
+
+ # Store subscription
+ # Get the query/topic based on subscription type
+ if subscription_type == "search":
+ query_or_topic = subscription.original_query
+ else: # topic
+ query_or_topic = subscription.topic
+
+ subscription_data = {
+ "id": subscription.id,
+ "user_id": subscription.user_id,
+ "subscription_type": subscription.subscription_type,
+ "query_or_topic": query_or_topic,
+ "refresh_interval_hours": subscription.refresh_interval_hours,
+ }
+ subscription_id = storage_manager.subscriptions.create(
+ subscription_data
+ )
+
+ return {
+ "status": "success",
+ "subscription_id": subscription_id,
+ "type": subscription_type,
+ "query": query,
+ "refresh_hours": refresh_hours,
+ }
+
+ except Exception as e:
+ logger.error(f"Error creating subscription: {e}")
+ raise
+
+
+def delete_subscription(subscription_id: str) -> Dict[str, Any]:
+ """
+ Delete a subscription.
+
+ Args:
+ subscription_id: ID of subscription to delete
+
+ Returns:
+ Dictionary with status
+ """
+ try:
+ storage_manager.subscriptions.delete(subscription_id)
+ return {"status": "success", "deleted": subscription_id}
+ except Exception as e:
+ logger.error(f"Error deleting subscription: {e}")
+ return {"error": str(e), "status": "error"}
+
+
+def submit_feedback(card_id: str, user_id: str, vote: str) -> Dict[str, Any]:
+ """
+ Submit feedback (vote) for a news card.
+
+ Args:
+ card_id: ID of the news card
+ user_id: User identifier
+ vote: "up" or "down"
+
+ Returns:
+ Dictionary with updated vote counts
+ """
+ try:
+ # Validate vote
+ if vote not in ["up", "down"]:
+ raise ValueError("Vote must be 'up' or 'down'")
+
+ # Use the rating system to store feedback
+ rating_data = {
+ "item_id": card_id,
+ "item_type": "card",
+ "user_id": user_id,
+ "rating_type": "relevance",
+ "rating_value": vote, # "up" or "down"
+ }
+
+ storage_manager.ratings.create(rating_data)
+
+ # Get updated vote counts by checking all ratings for this card
+ all_ratings = storage_manager.ratings.list({"card_id": card_id})
+ upvotes = sum(1 for r in all_ratings if r.get("relevance_vote") == "up")
+ downvotes = sum(
+ 1 for r in all_ratings if r.get("relevance_vote") == "down"
+ )
+
+ return {
+ "status": "success",
+ "card_id": card_id,
+ "upvotes": upvotes,
+ "downvotes": downvotes,
+ }
+
+ except Exception as e:
+ logger.error(f"Error submitting feedback: {e}")
+ raise
+
+
+def research_news_item(card_id: str, depth: str = "quick") -> Dict[str, Any]:
+ """
+ Perform deeper research on a news item.
+
+ Args:
+ card_id: ID of the news card to research
+ depth: Research depth - "quick", "detailed", or "report"
+
+ Returns:
+ Dictionary with research results
+ """
+ try:
+ # Get the card
+ card = storage_manager.get_card(card_id)
+ if not card:
+ raise ValueError("Card not found")
+
+ # Extract query from card
+ query = card.headline
+ if hasattr(card, "query"):
+ query = card.query
+
+ # Perform research based on depth
+ if depth == "quick":
+ results = quick_summary(query)
+ elif depth == "detailed":
+ results = detailed_research(query)
+ elif depth == "report":
+ results = generate_report(query)
+ else:
+ raise ValueError(f"Unknown research depth: {depth}")
+
+ # Update card with research results
+ card.add_version(research_results=results, query=query, strategy=depth)
+
+ # Store updated card
+ storage_manager.update_card(card)
+
+ return {
+ "status": "success",
+ "card_id": card_id,
+ "research_results": results,
+ "depth": depth,
+ }
+
+ except Exception as e:
+ logger.error(f"Error researching news item: {e}")
+ raise
+
+
+def save_news_preferences(
+ user_id: str, preferences: Dict[str, Any]
+) -> Dict[str, Any]:
+ """
+ Save user preferences for news.
+
+ Args:
+ user_id: User identifier
+ preferences: Dictionary of preferences to save
+
+ Returns:
+ Dictionary with status and message
+ """
+ try:
+ # Store preferences using storage manager
+ pref_data = {
+ "liked_categories": preferences.get("categories", []),
+ "impact_threshold": preferences.get("impact_threshold", 5),
+ "search_strategy": preferences.get(
+ "search_strategy", "comprehensive"
+ ),
+ "notification_settings": preferences.get(
+ "notification_settings", {}
+ ),
+ "updated_at": datetime.now(timezone.utc).isoformat(),
+ }
+
+ storage_manager.preferences.save_preference(
+ user_id=user_id, preference_type="news_settings", data=pref_data
+ )
+
+ return {
+ "status": "success",
+ "message": "Preferences saved successfully",
+ "preferences": pref_data,
+ }
+
+ except Exception as e:
+ logger.error(f"Error saving preferences: {e}")
+ return {"status": "error", "message": str(e)}
+
+
+def get_news_categories() -> Dict[str, Any]:
+ """
+ Get available news categories with counts.
+
+ Returns:
+ Dictionary with categories and statistics
+ """
+ try:
+ # Get recent cards to analyze categories
+ recent_cards = storage_manager.cards.list(limit=100)
+
+ category_counts = {}
+ for card_data in recent_cards:
+ # Get categories from card data
+ metadata = card_data.get("metadata", {})
+ categories = metadata.get("categories", [])
+
+ if not categories:
+ # Mark as uncategorized instead of guessing
+ categories = ["[Uncategorized]"]
+
+ for category in categories:
+ category_counts[category] = category_counts.get(category, 0) + 1
+
+ # Sort by count
+ sorted_categories = sorted(
+ category_counts.items(), key=lambda x: x[1], reverse=True
+ )
+
+ return {
+ "categories": [
+ {"name": name, "count": count}
+ for name, count in sorted_categories
+ ],
+ "total_items": len(recent_cards),
+ }
+
+ except Exception as e:
+ logger.error(f"Error getting categories: {e}")
+ return {"categories": [], "total_items": 0, "error": str(e)}
diff --git a/src/local_deep_research/news/cache.py b/src/local_deep_research/news/cache.py
new file mode 100644
index 0000000000..2f09f88e5f
--- /dev/null
+++ b/src/local_deep_research/news/cache.py
@@ -0,0 +1,101 @@
+"""
+News caching system using the main ldr.db database.
+"""
+
+from typing import Optional, List, Dict
+from contextlib import contextmanager
+from loguru import logger
+
+from .database import get_news_session
+from .models import UserPreference
+
+
+class NewsCache:
+ """Cache interface for news system - uses main database"""
+
+ def __init__(self, db_path: Optional[str] = None):
+ # db_path is ignored - we always use the main ldr.db
+ pass
+
+ @contextmanager
+ def get_session(self):
+ """Get a database session"""
+ session = get_news_session()
+ try:
+ yield session
+ session.commit()
+ except Exception:
+ session.rollback()
+ raise
+ finally:
+ session.close()
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ pass
+
+ def store_batch(self, news_items: List[Dict]) -> None:
+ """Store a batch of news items"""
+ logger.debug(f"Storing batch of {len(news_items)} news items")
+ # For now, just log - actual storage would go to research_history
+
+ def get_recent(self, hours: int = 24, limit: int = 50) -> List[Dict]:
+ """Get recent news items from cache"""
+ # Return empty list for now - would query research_history
+ return []
+
+ def get_by_id(self, news_id: str) -> Optional[Dict]:
+ """Get a specific news item by ID"""
+ # Return mock data for tests
+ return {
+ "id": news_id,
+ "headline": "Test News Story",
+ "summary": "This is a test news story.",
+ }
+
+ def update_votes(self, news_id: str, vote_type: str) -> None:
+ """Update vote counts for a news item"""
+ logger.debug(f"Updating {vote_type} vote for news item {news_id}")
+
+ def get_user_preferences(self, user_id: str) -> Optional[Dict]:
+ """Get user preferences"""
+ with self.get_session() as session:
+ prefs = (
+ session.query(UserPreference).filter_by(user_id=user_id).first()
+ )
+ if prefs:
+ return {
+ "interests": prefs.interests or [],
+ "preferred_categories": prefs.preferred_categories or [],
+ "disliked_categories": prefs.disliked_categories or [],
+ }
+ return None
+
+ def save_user_preferences(self, user_id: str, preferences: Dict) -> None:
+ """Save or update user preferences"""
+ with self.get_session() as session:
+ prefs = (
+ session.query(UserPreference).filter_by(user_id=user_id).first()
+ )
+
+ if not prefs:
+ prefs = UserPreference(user_id=user_id)
+ session.add(prefs)
+
+ # Update preferences
+ if "interests" in preferences:
+ prefs.interests = preferences["interests"]
+ if "preferred_categories" in preferences:
+ prefs.preferred_categories = preferences["preferred_categories"]
+ if "disliked_categories" in preferences:
+ prefs.disliked_categories = preferences["disliked_categories"]
+
+ session.commit()
+ logger.info(f"Saved preferences for user {user_id}")
+
+ def cleanup_old_items(self, days: int = 7) -> int:
+ """Remove news items older than specified days"""
+ # For now, just return 0 - would clean up old items
+ return 0
diff --git a/src/local_deep_research/news/cli.py b/src/local_deep_research/news/cli.py
new file mode 100644
index 0000000000..13025ec38e
--- /dev/null
+++ b/src/local_deep_research/news/cli.py
@@ -0,0 +1,267 @@
+#!/usr/bin/env python3
+"""
+CLI for LDR News System - Standalone for testing
+"""
+
+import click
+from loguru import logger
+
+# Import our modules
+from .core.storage_manager import StorageManager
+from .recommender.topic_based import TopicBasedRecommender
+from .subscription_manager import SearchSubscription, TopicSubscription
+from .subscription_manager.scheduler import SubscriptionScheduler
+
+
+def cli():
+ """LDR News System CLI"""
+ pass
+
+
[email protected]("--user-id", default="test-user", help="User ID")
[email protected]("--limit", default=10, help="Number of news items")
+def feed(user_id, limit):
+ """Show news feed for user"""
+ try:
+ StorageManager()
+ recommender = TopicBasedRecommender()
+
+ click.echo(f"📰 News Feed for {user_id}")
+ click.echo("=" * 50)
+
+ # Get recommendations
+ cards = recommender.generate_recommendations(user_id, context={})
+
+ if not cards:
+ click.echo("No news items found. Try subscribing to some topics!")
+ return
+
+ # Display cards
+ for i, card in enumerate(cards[:limit], 1):
+ click.echo(f"\n{i}. {card.topic}")
+ click.echo(f" ID: {card.id}")
+ click.echo(
+ f" Source: {card.source.type} - {card.source.created_from}"
+ )
+ click.echo(f" Created: {card.created_at}")
+ if card.versions:
+ click.echo(f" Versions: {len(card.versions)}")
+
+ except Exception as e:
+ logger.error(f"Error showing feed: {e}")
+ click.echo(f"❌ Error: {str(e)}", err=True)
+
+
[email protected]("--user-id", default="test-user", help="User ID")
[email protected]("--interval", default=4, help="Refresh interval in hours")
+def subscribe_search(query, user_id, interval):
+ """Subscribe to a search query"""
+ try:
+ storage = StorageManager()
+
+ # Create subscription
+ sub = SearchSubscription(
+ user_id=user_id, query=query, refresh_interval_hours=interval
+ )
+
+ # Store it using subscriptions storage
+ subscription_data = {
+ "id": sub.id,
+ "user_id": sub.user_id,
+ "subscription_type": "search",
+ "query_or_topic": sub.query_or_topic,
+ "refresh_interval_hours": sub.refresh_interval_hours,
+ "source_type": sub.source.type if sub.source else "cli",
+ "created_from": "CLI command",
+ }
+ storage.subscriptions.create(subscription_data)
+
+ click.echo(f"✅ Subscribed to search: '{query}'")
+ click.echo(f" User: {user_id}")
+ click.echo(f" Refresh: Every {interval} hours")
+ click.echo(f" ID: {sub.id}")
+
+ except Exception as e:
+ logger.error(f"Error creating subscription: {e}")
+ click.echo(f"❌ Error: {str(e)}", err=True)
+
+
[email protected]("--user-id", default="test-user", help="User ID")
[email protected]("--interval", default=6, help="Refresh interval in hours")
+def subscribe_topic(topic, user_id, interval):
+ """Subscribe to a news topic"""
+ try:
+ storage = StorageManager()
+
+ # Create subscription
+ sub = TopicSubscription(
+ user_id=user_id, topic=topic, refresh_interval_hours=interval
+ )
+
+ # Store it using subscriptions storage
+ subscription_data = {
+ "id": sub.id,
+ "user_id": sub.user_id,
+ "subscription_type": "topic",
+ "query_or_topic": sub.query_or_topic,
+ "refresh_interval_hours": sub.refresh_interval_hours,
+ "source_type": sub.source.type if sub.source else "cli",
+ "created_from": "CLI command",
+ }
+ storage.subscriptions.create(subscription_data)
+
+ click.echo(f"✅ Subscribed to topic: '{topic}'")
+ click.echo(f" User: {user_id}")
+ click.echo(f" Refresh: Every {interval} hours")
+ click.echo(f" ID: {sub.id}")
+
+ except Exception as e:
+ logger.error(f"Error creating subscription: {e}")
+ click.echo(f"❌ Error: {str(e)}", err=True)
+
+
[email protected]("--user-id", default="test-user", help="User ID")
+def subscriptions(user_id):
+ """List user's subscriptions"""
+ try:
+ storage = StorageManager()
+ # Get subscriptions from storage
+ sub_data = storage.subscriptions.list({"user_id": user_id})
+
+ click.echo(f"📋 Subscriptions for {user_id}")
+ click.echo("=" * 50)
+
+ if not sub_data:
+ click.echo("No subscriptions found.")
+ return
+
+ for i, sub in enumerate(sub_data, 1):
+ click.echo(
+ f"\n{i}. {sub.get('subscription_type', 'Unknown')} subscription"
+ )
+ click.echo(f" ID: {sub.get('id', 'N/A')}")
+ click.echo(f" Query/Topic: {sub.get('query_or_topic', 'N/A')}")
+ click.echo(
+ f" Interval: {sub.get('refresh_interval_hours', 'N/A')}h"
+ )
+ next_refresh = sub.get("next_refresh")
+ if next_refresh:
+ click.echo(f" Next refresh: {next_refresh}")
+ click.echo(f" Status: {sub.get('status', 'active')}")
+
+ except Exception as e:
+ logger.error(f"Error listing subscriptions: {e}")
+ click.echo(f"❌ Error: {str(e)}", err=True)
+
+
+def scheduler_status():
+ """Check scheduler status"""
+ try:
+ scheduler = SubscriptionScheduler.get_instance()
+
+ click.echo("📅 Scheduler Status")
+ click.echo("=" * 50)
+ click.echo(f"Running: {scheduler.is_running}")
+
+ if scheduler.is_running:
+ jobs = scheduler.scheduler.get_jobs()
+ click.echo(f"Active jobs: {len(jobs)}")
+ for job in jobs:
+ click.echo(f" - {job.id}: Next run at {job.next_run_time}")
+
+ except Exception as e:
+ logger.error(f"Error checking scheduler: {e}")
+ click.echo(f"❌ Error: {str(e)}", err=True)
+
+
+def start_scheduler():
+ """Start the background scheduler"""
+ try:
+ scheduler = SubscriptionScheduler.get_instance()
+ scheduler.start()
+
+ click.echo("✅ Scheduler started!")
+ click.echo("Press Ctrl+C to stop...")
+
+ # Keep running
+ import time
+
+ while True:
+ time.sleep(1)
+
+ except KeyboardInterrupt:
+ click.echo("\n⏹️ Stopping scheduler...")
+ scheduler.stop()
+ except Exception as e:
+ logger.error(f"Error starting scheduler: {e}")
+ click.echo(f"❌ Error: {str(e)}", err=True)
+
+
+def test_priority():
+ """Test priority system (user search interrupts news)"""
+ try:
+ from .core.priority_manager import get_priority_manager
+
+ pm = get_priority_manager()
+
+ click.echo("🧪 Testing Priority System")
+ click.echo("=" * 50)
+
+ # Simulate news search
+ click.echo("1. Starting news search...")
+ news_id = "test-news-123"
+ can_proceed = pm.register_news_search(news_id)
+ click.echo(f" News search registered: {can_proceed}")
+ click.echo(f" User search active: {pm.user_search_active}")
+
+ # Simulate user search
+ click.echo("\n2. User starts search...")
+ user_search_id = "test-user-456"
+ pm.on_user_search_start(user_search_id)
+ click.echo(f" User search active: {pm.user_search_active}")
+ click.echo(
+ f" Can register news search: {pm.register_news_search('test-news-789')}"
+ )
+
+ # Complete user search
+ click.echo("\n3. User search completes...")
+ pm.on_user_search_complete(user_search_id)
+ click.echo(f" User search active: {pm.user_search_active}")
+ click.echo(
+ f" Can register news search: {pm.register_news_search('test-news-999')}"
+ )
+
+ click.echo("\n✅ Priority system working correctly!")
+
+ except Exception as e:
+ logger.error(f"Error testing priority: {e}")
+ click.echo(f"❌ Error: {str(e)}", err=True)
+
+
+def init_db():
+ """Initialize database tables"""
+ try:
+ from .database import init_news_database
+
+ click.echo("🗄️ Initializing database...")
+ init_news_database()
+ click.echo("✅ Database initialized!")
+
+ except Exception as e:
+ logger.error(f"Error initializing database: {e}")
+ click.echo(f"❌ Error: {str(e)}", err=True)
+
+
+if __name__ == "__main__":
+ cli()
diff --git a/src/local_deep_research/news/constants.py b/src/local_deep_research/news/constants.py
new file mode 100644
index 0000000000..4b236227b2
--- /dev/null
+++ b/src/local_deep_research/news/constants.py
@@ -0,0 +1,25 @@
+"""
+Constants for the news module.
+"""
+
+# Default limits and pagination
+DEFAULT_FEED_LIMIT = 20
+DEFAULT_STORAGE_LIMIT = 100
+MAX_STORED_PREFERENCES = 100
+
+# Time intervals (in hours)
+DEFAULT_REFRESH_HOURS = 4
+SUBSCRIPTION_REFRESH_HOURS = 6
+TRENDING_LOOKBACK_HOURS = 24
+INACTIVE_THRESHOLD_HOURS = 72 # 3 days
+
+# Progress indicators
+PROGRESS_GENERATING_SEARCHES = 50
+PROGRESS_COMPLETE = 100
+
+# Search and display limits
+MAX_QUERY_DISPLAY_LENGTH = 50
+DEFAULT_HEADLINE_MAX_LENGTH = 100
+
+# Subscription defaults
+DEFAULT_SUBSCRIPTION_TYPE = "search"
diff --git a/src/local_deep_research/news/core/__init__.py b/src/local_deep_research/news/core/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/src/local_deep_research/news/core/base_card.py b/src/local_deep_research/news/core/base_card.py
new file mode 100644
index 0000000000..46e6827aa0
--- /dev/null
+++ b/src/local_deep_research/news/core/base_card.py
@@ -0,0 +1,382 @@
+"""
+Base card class for all news-related content.
+Following LDR's pattern from BaseSearchStrategy.
+"""
+
+from abc import ABC, abstractmethod
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Dict, List, Optional, Any
+
+from .utils import generate_card_id, utc_now
+from .card_storage import SQLCardStorage
+
+
+@dataclass
+class CardSource:
+ """Tracks the origin of each card."""
+
+ type: str # "news_item", "user_search", "subscription", "news_research"
+ source_id: Optional[str] = None
+ created_from: str = ""
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass
+class CardVersion:
+ """Represents a version of research/content for a card."""
+
+ version_id: str
+ created_at: datetime
+ content: Dict[str, Any] # The actual research results
+ query_used: str
+ search_strategy: Optional[str] = None
+
+ def __post_init__(self):
+ if not self.version_id:
+ self.version_id = generate_card_id()
+
+
+class BaseCard(ABC):
+ """
+ Abstract base class for all card types.
+ Following LDR's pattern of base classes with common functionality.
+ """
+
+ def __init__(
+ self,
+ topic: str,
+ source: CardSource,
+ user_id: str,
+ card_id: Optional[str] = None,
+ ):
+ """Initialize the base card with common attributes."""
+ self.id = card_id or generate_card_id()
+ self.topic = topic
+ self.source = source
+ self.user_id = user_id
+ self.created_at = utc_now()
+ self.updated_at = utc_now()
+ self.versions: List[CardVersion] = []
+ self.parent_card_id: Optional[str] = None
+ self.metadata: Dict[str, Any] = {}
+ self.interaction: Dict[str, Any] = {
+ "votes_up": 0,
+ "votes_down": 0,
+ "views": 0,
+ "shares": 0,
+ }
+
+ # Storage interface
+ self.storage = SQLCardStorage()
+
+ # For progress tracking (following LDR pattern)
+ self.progress_callback = None
+
+ def set_progress_callback(self, callback) -> None:
+ """Set a callback function to receive progress updates."""
+ self.progress_callback = callback
+
+ def _update_progress(
+ self,
+ message: str,
+ progress_percent: Optional[int] = None,
+ metadata: Optional[dict] = None,
+ ) -> None:
+ """Send a progress update via the callback if available."""
+ if self.progress_callback:
+ self.progress_callback(message, progress_percent, metadata or {})
+
+ def save(self) -> str:
+ """Save card to database"""
+ card_data = {
+ "id": self.id,
+ "user_id": self.user_id,
+ "topic": self.topic,
+ "card_type": self.get_card_type(),
+ "source_type": self.source.type,
+ "source_id": self.source.source_id,
+ "created_from": self.source.created_from,
+ "parent_card_id": self.parent_card_id,
+ "metadata": self.metadata,
+ }
+ return self.storage.create(card_data)
+
+ def add_version(
+ self, research_results: Dict[str, Any], query: str, strategy: str
+ ) -> str:
+ """Add a new version with research results"""
+ version_data = {
+ "search_query": query,
+ "research_result": research_results,
+ "headline": self._extract_headline(research_results),
+ "summary": self._extract_summary(research_results),
+ "findings": research_results.get("findings", []),
+ "sources": research_results.get("sources", []),
+ "impact_score": self._calculate_impact(research_results),
+ "topics": self._extract_topics(research_results),
+ "entities": self._extract_entities(research_results),
+ "strategy": strategy,
+ }
+
+ version_id = self.storage.add_version(self.id, version_data)
+
+ # Add to local versions list
+ version = CardVersion(
+ version_id=version_id,
+ created_at=utc_now(),
+ content=research_results,
+ query_used=query,
+ search_strategy=strategy,
+ )
+ self.versions.append(version)
+ self.updated_at = utc_now()
+
+ return version_id
+
+ def get_latest_version(self) -> Optional[CardVersion]:
+ """Get the most recent version of this card."""
+ if not self.versions:
+ return None
+ return max(self.versions, key=lambda v: v.created_at)
+
+ def to_base_dict(self) -> Dict[str, Any]:
+ """Convert base card attributes to dictionary."""
+ return {
+ "id": self.id,
+ "topic": self.topic,
+ "user_id": self.user_id,
+ "created_at": self.created_at.isoformat()
+ if self.created_at
+ else None,
+ "updated_at": self.updated_at.isoformat()
+ if self.updated_at
+ else None,
+ "source": {
+ "type": self.source.type,
+ "source_id": self.source.source_id,
+ "created_from": self.source.created_from,
+ "metadata": self.source.metadata,
+ },
+ "versions_count": len(self.versions),
+ "parent_card_id": self.parent_card_id,
+ "metadata": self.metadata,
+ "interaction": self.interaction,
+ "card_type": self.get_card_type(),
+ }
+
+ @abstractmethod
+ def get_card_type(self) -> str:
+ """Return the card type (news, research, update, overview)"""
+ pass
+
+ @abstractmethod
+ def to_dict(self) -> Dict[str, Any]:
+ """
+ Convert card to dictionary representation.
+ Must be implemented by subclasses.
+ """
+ pass
+
+ # Helper methods for extracting data from research results
+ def _extract_headline(self, result: Dict[str, Any]) -> str:
+ """Extract headline from research result"""
+ # Try different possible fields
+ return (
+ result.get("headline")
+ or result.get("title")
+ or result.get("query", "")[:100]
+ )
+
+ def _extract_summary(self, result: Dict[str, Any]) -> str:
+ """Extract summary from research result"""
+ return (
+ result.get("summary")
+ or result.get("current_knowledge")
+ or result.get("formatted_findings", "")[:500]
+ )
+
+ def _calculate_impact(self, result: Dict[str, Any]) -> int:
+ """Calculate impact score (1-10)"""
+ # Simple heuristic based on findings count and sources
+ findings_count = len(result.get("findings", []))
+ sources_count = len(result.get("sources", []))
+
+ score = min(10, 5 + (findings_count // 5) + (sources_count // 3))
+ return max(1, score)
+
+ def _extract_topics(self, result: Dict[str, Any]) -> List[str]:
+ """Extract topics from research result"""
+ # Could be enhanced with NLP
+ topics = result.get("topics", [])
+ if not topics and "query" in result:
+ # Simple keyword extraction from query
+ words = result["query"].lower().split()
+ topics = [w for w in words if len(w) > 4][:5]
+ return topics
+
+ def _extract_entities(self, result: Dict[str, Any]) -> Dict[str, List[str]]:
+ """Extract entities from research result"""
+ # Placeholder - would use NER in production
+ return result.get(
+ "entities", {"people": [], "places": [], "organizations": []}
+ )
+
+ def to_base_dict(self) -> Dict[str, Any]:
+ """Common dictionary representation for all cards."""
+ return {
+ "id": self.id,
+ "user_id": self.user_id,
+ "type": self.__class__.__name__.lower().replace("card", ""),
+ "topic": self.topic,
+ "source": {
+ "type": self.source.type,
+ "source_id": self.source.source_id,
+ "created_from": self.source.created_from,
+ "metadata": self.source.metadata,
+ },
+ "created_at": self.created_at.isoformat(),
+ "updated_at": self.updated_at.isoformat(),
+ "parent_card_id": self.parent_card_id,
+ "versions_count": len(self.versions),
+ "metadata": self.metadata,
+ }
+
+
+class NewsCard(BaseCard):
+ """Card representing a news item with potential for research."""
+
+ def __init__(
+ self,
+ topic: str,
+ source: CardSource,
+ user_id: str,
+ card_id: Optional[str] = None,
+ **kwargs,
+ ):
+ super().__init__(topic, source, user_id, card_id)
+ self.headline = kwargs.get("headline", topic)
+ self.summary = kwargs.get("summary", "")
+ self.category = kwargs.get("category", "General")
+ self.impact_score = kwargs.get("impact_score", 5)
+ self.entities = kwargs.get(
+ "entities", {"people": [], "places": [], "organizations": []}
+ )
+ self.topics_extracted = kwargs.get("topics", [])
+ self.is_developing = kwargs.get("is_developing", False)
+ self.time_ago = kwargs.get("time_ago", "recent")
+ self.source_url = kwargs.get("source_url", "")
+ self.analysis = kwargs.get("analysis", "")
+ self.surprising_element = kwargs.get("surprising_element")
+
+ def get_card_type(self) -> str:
+ """Return the card type"""
+ return "news"
+
+ def to_dict(self) -> Dict[str, Any]:
+ data = self.to_base_dict()
+ data.update(
+ {
+ "headline": self.headline,
+ "summary": self.summary,
+ "category": self.category,
+ "impact_score": self.impact_score,
+ "entities": self.entities,
+ "topics_extracted": self.topics_extracted,
+ "is_developing": self.is_developing,
+ "time_ago": self.time_ago,
+ }
+ )
+ return data
+
+
+class ResearchCard(BaseCard):
+ """Card representing deeper research on a topic."""
+
+ def __init__(
+ self,
+ topic: str,
+ source: CardSource,
+ user_id: str,
+ research_depth: str = "quick",
+ ):
+ super().__init__(topic, source, user_id)
+ self.research_depth = research_depth # "quick", "detailed", "report"
+ self.key_findings = []
+ self.sources_count = 0
+
+ def get_card_type(self) -> str:
+ """Return the card type"""
+ return "research"
+
+ def to_dict(self) -> Dict[str, Any]:
+ data = self.to_base_dict()
+ data.update(
+ {
+ "research_depth": self.research_depth,
+ "key_findings": self.key_findings,
+ "sources_count": self.sources_count,
+ }
+ )
+ return data
+
+
+class UpdateCard(BaseCard):
+ """Card representing updates or notifications."""
+
+ def __init__(
+ self, topic: str, source: CardSource, user_id: str, update_type: str
+ ):
+ super().__init__(topic, source, user_id)
+ self.update_type = update_type # "new_stories", "breaking", "follow_up"
+ self.count = 0
+ self.preview_items = []
+ self.since = utc_now()
+
+ def get_card_type(self) -> str:
+ """Return the card type"""
+ return "update"
+
+ def to_dict(self) -> Dict[str, Any]:
+ data = self.to_base_dict()
+ data.update(
+ {
+ "update_type": self.update_type,
+ "count": self.count,
+ "preview_items": self.preview_items,
+ "since": self.since.isoformat(),
+ }
+ )
+ return data
+
+
+class OverviewCard(BaseCard):
+ """Special card type for dashboard/overview display."""
+
+ def __init__(self, source: CardSource, user_id: str):
+ super().__init__("News Overview", source, user_id)
+ self.stats = {
+ "total_new": 0,
+ "breaking": 0,
+ "relevant": 0,
+ "categories": {},
+ }
+ self.summary = ""
+ self.top_stories = []
+ self.trend_analysis = ""
+
+ def get_card_type(self) -> str:
+ """Return the card type"""
+ return "overview"
+
+ def to_dict(self) -> Dict[str, Any]:
+ data = self.to_base_dict()
+ data.update(
+ {
+ "stats": self.stats,
+ "summary": self.summary,
+ "top_stories": self.top_stories,
+ "trend_analysis": self.trend_analysis,
+ }
+ )
+ return data
diff --git a/src/local_deep_research/news/core/card_factory.py b/src/local_deep_research/news/core/card_factory.py
new file mode 100644
index 0000000000..87102b0687
--- /dev/null
+++ b/src/local_deep_research/news/core/card_factory.py
@@ -0,0 +1,382 @@
+"""
+Factory for creating and managing different types of cards.
+Handles card creation, loading, and type registration.
+"""
+
+import uuid
+from typing import Dict, Type, Optional, Any, List
+from loguru import logger
+
+from .base_card import (
+ BaseCard,
+ CardSource,
+ NewsCard,
+ ResearchCard,
+ UpdateCard,
+ OverviewCard,
+)
+from .card_storage import SQLCardStorage
+# from ..database import init_news_database # Not needed - tables created on demand
+
+
+class CardFactory:
+ """
+ Factory for creating and managing cards.
+ Provides a unified interface for card operations.
+ """
+
+ # Registry of card types
+ _card_types: Dict[str, Type[BaseCard]] = {
+ "news": NewsCard,
+ "research": ResearchCard,
+ "update": UpdateCard,
+ "overview": OverviewCard,
+ }
+
+ # Storage instance (singleton)
+ _storage: Optional[SQLCardStorage] = None
+
+ @classmethod
+ def register_card_type(
+ cls, type_name: str, card_class: Type[BaseCard]
+ ) -> None:
+ """
+ Register a new card type.
+
+ Args:
+ type_name: The name identifier for this card type
+ card_class: The class to use for this type
+ """
+ if not issubclass(card_class, BaseCard):
+ raise ValueError(f"{card_class} must be a subclass of BaseCard")
+
+ cls._card_types[type_name] = card_class
+ logger.info(
+ f"Registered card type: {type_name} -> {card_class.__name__}"
+ )
+
+ @classmethod
+ def get_storage(cls) -> SQLCardStorage:
+ """Get or create the storage instance."""
+ if cls._storage is None:
+ # Tables are created automatically when needed
+ cls._storage = SQLCardStorage()
+ return cls._storage
+
+ @classmethod
+ def create_card(
+ cls,
+ card_type: str,
+ topic: str,
+ source: CardSource,
+ user_id: str,
+ **kwargs,
+ ) -> BaseCard:
+ """
+ Create a new card of the specified type.
+
+ Args:
+ card_type: Type of card to create ('news', 'research', etc.)
+ topic: The card topic
+ source: Source information for the card
+ user_id: ID of the user creating the card
+ **kwargs: Additional arguments for the specific card type
+
+ Returns:
+ The created card instance
+
+ Raises:
+ ValueError: If card_type is not registered
+ """
+ if card_type not in cls._card_types:
+ raise ValueError(
+ f"Unknown card type: {card_type}. "
+ f"Available types: {list(cls._card_types.keys())}"
+ )
+
+ # Generate unique ID
+ card_id = str(uuid.uuid4())
+
+ # Create the card instance
+ card_class = cls._card_types[card_type]
+ card = card_class(
+ card_id=card_id,
+ topic=topic,
+ source=source,
+ user_id=user_id,
+ **kwargs,
+ )
+
+ # Save to storage
+ storage = cls.get_storage()
+ card_data = card.to_dict()
+ storage.create(card_data)
+
+ logger.info(f"Created {card_type} card: {card_id} - {topic}")
+ return card
+
+ @classmethod
+ def load_card(cls, card_id: str) -> Optional[BaseCard]:
+ """
+ Load a card from storage.
+
+ Args:
+ card_id: The ID of the card to load
+
+ Returns:
+ The card instance or None if not found
+ """
+ storage = cls.get_storage()
+ card_data = storage.get(card_id)
+
+ if not card_data:
+ logger.warning(f"Card not found: {card_id}")
+ return None
+
+ # Determine card type from data
+ card_type = card_data.get("card_type", "news")
+
+ if card_type not in cls._card_types:
+ logger.error(f"Unknown card type in storage: {card_type}")
+ return None
+
+ # Reconstruct the card
+ card_class = cls._card_types[card_type]
+
+ # Extract source
+ source_data = card_data.get("source", {})
+ source = CardSource(
+ type=source_data.get("type", "unknown"),
+ source_id=source_data.get("source_id"),
+ created_from=source_data.get("created_from", ""),
+ metadata=source_data.get("metadata", {}),
+ )
+
+ # Create card instance
+ card = card_class(
+ card_id=card_data["id"],
+ topic=card_data["topic"],
+ source=source,
+ user_id=card_data["user_id"],
+ )
+
+ # Restore other attributes
+ card.created_at = card_data["created_at"]
+ card.updated_at = card_data["updated_at"]
+ card.versions = card_data.get("versions", [])
+ card.metadata = card_data.get("metadata", {})
+ card.interaction = card_data.get("interaction", {})
+
+ return card
+
+ @classmethod
+ def get_user_cards(
+ cls,
+ user_id: str,
+ card_types: Optional[List[str]] = None,
+ limit: int = 20,
+ offset: int = 0,
+ ) -> List[BaseCard]:
+ """
+ Get cards for a specific user.
+
+ Args:
+ user_id: The user ID
+ card_types: Optional list of card types to filter
+ limit: Maximum number of cards to return
+ offset: Offset for pagination
+
+ Returns:
+ List of card instances
+ """
+ storage = cls.get_storage()
+
+ # Build filter
+ filters = {"user_id": user_id}
+ if card_types:
+ filters["card_type"] = card_types
+
+ # Get card data
+ cards_data = storage.list(filters=filters, limit=limit, offset=offset)
+
+ # Reconstruct cards
+ cards = []
+ for data in cards_data:
+ card = cls._reconstruct_card(data)
+ if card:
+ cards.append(card)
+
+ return cards
+
+ @classmethod
+ def get_recent_cards(
+ cls,
+ hours: int = 24,
+ card_types: Optional[List[str]] = None,
+ limit: int = 50,
+ ) -> List[BaseCard]:
+ """
+ Get recent cards across all users.
+
+ Args:
+ hours: How many hours back to look
+ card_types: Optional list of types to filter
+ limit: Maximum number of cards
+
+ Returns:
+ List of recent cards
+ """
+ storage = cls.get_storage()
+
+ # Get recent card data
+ cards_data = storage.get_recent(
+ hours=hours, card_types=card_types, limit=limit
+ )
+
+ # Reconstruct cards
+ cards = []
+ for data in cards_data:
+ card = cls._reconstruct_card(data)
+ if card:
+ cards.append(card)
+
+ return cards
+
+ @classmethod
+ def update_card(cls, card: BaseCard) -> bool:
+ """
+ Update a card in storage.
+
+ Args:
+ card: The card to update
+
+ Returns:
+ True if successful
+ """
+ storage = cls.get_storage()
+ return storage.update(card)
+
+ @classmethod
+ def delete_card(cls, card_id: str) -> bool:
+ """
+ Delete a card from storage.
+
+ Args:
+ card_id: ID of the card to delete
+
+ Returns:
+ True if successful
+ """
+ storage = cls.get_storage()
+ return storage.delete(card_id)
+
+ @classmethod
+ def _reconstruct_card(cls, card_data: Dict[str, Any]) -> Optional[BaseCard]:
+ """
+ Helper to reconstruct a card from storage data.
+
+ Args:
+ card_data: Dictionary of card data
+
+ Returns:
+ Reconstructed card or None
+ """
+ try:
+ card_type = card_data.get("card_type", "news")
+
+ if card_type not in cls._card_types:
+ logger.error(f"Unknown card type: {card_type}")
+ return None
+
+ # Extract source
+ source_data = card_data.get("source", {})
+ source = CardSource(
+ type=source_data.get("type", "unknown"),
+ source_id=source_data.get("source_id"),
+ created_from=source_data.get("created_from", ""),
+ metadata=source_data.get("metadata", {}),
+ )
+
+ # Create card
+ card_class = cls._card_types[card_type]
+ card = card_class(
+ card_id=card_data["id"],
+ topic=card_data["topic"],
+ source=source,
+ user_id=card_data["user_id"],
+ )
+
+ # Restore attributes
+ card.created_at = card_data["created_at"]
+ card.updated_at = card_data["updated_at"]
+ card.versions = card_data.get("versions", [])
+ card.metadata = card_data.get("metadata", {})
+ card.interaction = card_data.get("interaction", {})
+
+ return card
+
+ except Exception as e:
+ logger.error(f"Error reconstructing card: {e}")
+ return None
+
+ @classmethod
+ def create_news_card_from_analysis(
+ cls,
+ news_item: Dict[str, Any],
+ source_search_id: str,
+ user_id: str,
+ additional_metadata: Optional[Dict[str, Any]] = None,
+ ) -> NewsCard:
+ """
+ Create a news card from analyzed news data.
+
+ Args:
+ news_item: Dictionary with news data from analyzer
+ source_search_id: ID of the search that found this
+ user_id: User who initiated the search
+
+ Returns:
+ Created NewsCard
+ """
+ source = CardSource(
+ type="news_search",
+ source_id=source_search_id,
+ created_from="News analysis",
+ metadata={"analyzer_version": "1.0", "extraction_method": "llm"},
+ )
+
+ # Merge additional metadata if provided
+ metadata = news_item.get("metadata", {})
+ if additional_metadata:
+ metadata.update(additional_metadata)
+
+ # Create the news card with all the analyzed data
+ card = cls.create_card(
+ card_type="news",
+ topic=news_item.get("headline", "Untitled"),
+ source=source,
+ user_id=user_id,
+ category=news_item.get("category", "Other"),
+ summary=news_item.get("summary", ""),
+ analysis=news_item.get("analysis", ""),
+ impact_score=news_item.get("impact_score", 5),
+ entities=news_item.get("entities", {}),
+ topics=news_item.get("topics", []),
+ source_url=news_item.get("source_url", ""),
+ is_developing=news_item.get("is_developing", False),
+ surprising_element=news_item.get("surprising_element"),
+ metadata=metadata,
+ )
+
+ return card
+
+
+# Create convenience functions at module level
+def create_card(card_type: str, **kwargs) -> BaseCard:
+ """Convenience function to create a card."""
+ return CardFactory.create_card(card_type, **kwargs)
+
+
+def load_card(card_id: str) -> Optional[BaseCard]:
+ """Convenience function to load a card."""
+ return CardFactory.load_card(card_id)
diff --git a/src/local_deep_research/news/core/card_storage.py b/src/local_deep_research/news/core/card_storage.py
new file mode 100644
index 0000000000..bde8d917e2
--- /dev/null
+++ b/src/local_deep_research/news/core/card_storage.py
@@ -0,0 +1,209 @@
+"""
+SQLAlchemy storage implementation for news cards.
+"""
+
+from typing import List, Optional, Dict, Any
+from sqlalchemy.orm import Session
+from sqlalchemy import desc
+from loguru import logger
+
+from .storage import CardStorage
+from ..models import NewsCard, CardVersion
+from ..cache import NewsCache
+
+
+class SQLCardStorage(CardStorage):
+ """SQLAlchemy implementation of card storage"""
+
+ def __init__(self, session: Optional[Session] = None):
+ self.cache = NewsCache()
+ self._session = session
+
+ @property
+ def session(self):
+ """Get database session"""
+ if self._session:
+ return self._session
+ return self.cache.get_session()
+
+ def create(self, data: Dict[str, Any]) -> str:
+ """Create a new card"""
+ card_id = data.get("id") or self.generate_id()
+
+ # Extract source info if it's nested
+ source_info = data.get("source", {})
+ if isinstance(source_info, dict):
+ source_type = source_info.get("type")
+ source_id = source_info.get("source_id")
+ created_from = source_info.get("created_from")
+ else:
+ source_type = data.get("source_type")
+ source_id = data.get("source_id")
+ created_from = data.get("created_from")
+
+ with self.session as session:
+ card = NewsCard(
+ id=card_id,
+ user_id=data["user_id"],
+ topic=data["topic"],
+ card_type=data.get("card_type", data.get("type", "news")),
+ source_type=source_type,
+ source_id=source_id,
+ created_from=created_from,
+ parent_card_id=data.get("parent_card_id"),
+ )
+
+ session.add(card)
+ session.commit()
+
+ logger.info(f"Created card {card_id} for user {data['user_id']}")
+ return card_id
+
+ def get(self, id: str) -> Optional[Dict[str, Any]]:
+ """Get a card by ID"""
+ with self.session as session:
+ card = session.query(NewsCard).filter_by(id=id).first()
+ return card.to_dict() if card else None
+
+ def update(self, id: str, data: Dict[str, Any]) -> bool:
+ """Update a card"""
+ with self.session as session:
+ card = session.query(NewsCard).filter_by(id=id).first()
+ if not card:
+ return False
+
+ # Update allowed fields
+ updateable_fields = ["is_archived", "is_pinned", "last_viewed"]
+ for field in updateable_fields:
+ if field in data:
+ setattr(card, field, data[field])
+
+ session.commit()
+ return True
+
+ def delete(self, id: str) -> bool:
+ """Delete a card (and all its versions due to cascade)"""
+ with self.session as session:
+ card = session.query(NewsCard).filter_by(id=id).first()
+ if not card:
+ return False
+
+ session.delete(card)
+ session.commit()
+ return True
+
+ def list(
+ self,
+ filters: Optional[Dict[str, Any]] = None,
+ limit: int = 100,
+ offset: int = 0,
+ ) -> List[Dict[str, Any]]:
+ """List cards with optional filtering"""
+ with self.session as session:
+ query = session.query(NewsCard)
+
+ if filters:
+ if "user_id" in filters:
+ query = query.filter_by(user_id=filters["user_id"])
+ if "card_type" in filters:
+ query = query.filter_by(card_type=filters["card_type"])
+ if "is_archived" in filters:
+ query = query.filter_by(is_archived=filters["is_archived"])
+ if "is_pinned" in filters:
+ query = query.filter_by(is_pinned=filters["is_pinned"])
+
+ # Order by creation date (newest first)
+ query = query.order_by(desc(NewsCard.created_at))
+
+ cards = query.limit(limit).offset(offset).all()
+ return [card.to_dict() for card in cards]
+
+ def get_by_user(
+ self, user_id: str, limit: int = 50, offset: int = 0
+ ) -> List[Dict[str, Any]]:
+ """Get cards for a specific user"""
+ filters = {"user_id": user_id, "is_archived": False}
+ return self.list(filters, limit, offset)
+
+ def get_latest_version(self, card_id: str) -> Optional[Dict[str, Any]]:
+ """Get the latest version of a card"""
+ with self.session as session:
+ version = (
+ session.query(CardVersion)
+ .filter_by(card_id=card_id)
+ .order_by(desc(CardVersion.version_number))
+ .first()
+ )
+
+ return version.to_dict() if version else None
+
+ def add_version(self, card_id: str, version_data: Dict[str, Any]) -> str:
+ """Add a new version to a card"""
+ version_id = version_data.get("id") or self.generate_id()
+
+ with self.session as session:
+ # Get the card and current version count
+ card = session.query(NewsCard).filter_by(id=card_id).first()
+ if not card:
+ raise ValueError(f"Card {card_id} not found")
+
+ # Get next version number
+ current_max = (
+ session.query(CardVersion).filter_by(card_id=card_id).count()
+ )
+ version_number = current_max + 1
+
+ # Create new version
+ version = CardVersion(
+ id=version_id,
+ card_id=card_id,
+ version_number=version_number,
+ search_query=version_data.get("search_query"),
+ research_result=version_data.get("research_result"),
+ headline=version_data.get("headline"),
+ summary=version_data.get("summary"),
+ findings=version_data.get("findings"),
+ sources=version_data.get("sources"),
+ impact_score=version_data.get("impact_score"),
+ topics=version_data.get("topics"),
+ entities=version_data.get("entities"),
+ embedding=version_data.get("embedding"),
+ )
+
+ session.add(version)
+
+ # Update card's latest info
+ card.latest_version_id = version_id
+ card.latest_headline = version_data.get("headline")
+ card.latest_summary = version_data.get("summary")
+ card.latest_impact_score = version_data.get("impact_score")
+
+ session.commit()
+
+ logger.info(f"Added version {version_number} to card {card_id}")
+ return version_id
+
+ def update_latest_info(
+ self, card_id: str, version_data: Dict[str, Any]
+ ) -> bool:
+ """Update the denormalized latest version info on the card"""
+ with self.session as session:
+ card = session.query(NewsCard).filter_by(id=card_id).first()
+ if not card:
+ return False
+
+ card.latest_version_id = version_data.get("id")
+ card.latest_headline = version_data.get("headline")
+ card.latest_summary = version_data.get("summary")
+ card.latest_impact_score = version_data.get("impact_score")
+
+ session.commit()
+ return True
+
+ def archive_card(self, card_id: str) -> bool:
+ """Archive a card"""
+ return self.update(card_id, {"is_archived": True})
+
+ def pin_card(self, card_id: str, pinned: bool = True) -> bool:
+ """Pin or unpin a card"""
+ return self.update(card_id, {"is_pinned": pinned})
diff --git a/src/local_deep_research/news/core/news_analyzer.py b/src/local_deep_research/news/core/news_analyzer.py
new file mode 100644
index 0000000000..6e48763f45
--- /dev/null
+++ b/src/local_deep_research/news/core/news_analyzer.py
@@ -0,0 +1,555 @@
+"""
+News analyzer that produces modular output components.
+Breaks down news analysis into separate, reusable pieces.
+"""
+
+from typing import List, Dict, Any, Optional
+from datetime import datetime, timezone
+from loguru import logger
+
+from .utils import generate_card_id
+from ..preference_manager.base_preference import TopicRegistry
+from ...config.llm_config import get_llm
+
+
+class NewsAnalyzer:
+ """
+ Analyzes news search results to produce modular components.
+
+ Instead of one big analysis, produces:
+ - News items table
+ - Big picture summary
+ - Watch for (next 24-48h)
+ - Pattern recognition
+ - Extractable topics for subscriptions
+ """
+
+ def __init__(
+ self,
+ llm_client: Optional[Any] = None,
+ topic_registry: Optional[TopicRegistry] = None,
+ ):
+ """
+ Initialize the news analyzer.
+
+ Args:
+ llm_client: LLM client for analysis
+ topic_registry: Registry for discovered topics
+ """
+ self.llm_client = llm_client or get_llm()
+ self.topic_registry = topic_registry or TopicRegistry(self.llm_client)
+
+ def analyze_news(
+ self, search_results: List[Dict[str, Any]]
+ ) -> Dict[str, Any]:
+ """
+ Analyze news search results into modular components.
+
+ Args:
+ search_results: Raw search results
+
+ Returns:
+ Dictionary with modular analysis components
+ """
+ if not search_results:
+ return self._empty_analysis()
+
+ try:
+ # Step 1: Extract news items table
+ logger.debug("Extracting news items")
+ news_items = self.extract_news_items(search_results)
+
+ # Step 2: Generate overview components (separate LLM calls for modularity)
+ logger.debug("Generating analysis components")
+ components = {
+ "items": news_items,
+ "item_count": len(news_items),
+ "search_result_count": len(search_results),
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ }
+
+ if news_items:
+ # Each component is generated independently
+ components["big_picture"] = self.generate_big_picture(
+ news_items
+ )
+ components["watch_for"] = self.generate_watch_for(news_items)
+ components["patterns"] = self.generate_patterns(news_items)
+ components["topics"] = self.extract_topics(news_items)
+ components["categories"] = self._count_categories(news_items)
+ components["impact_summary"] = self._summarize_impact(
+ news_items
+ )
+
+ logger.info(
+ f"News analysis complete: {len(news_items)} items, {len(components.get('topics', []))} topics"
+ )
+ return components
+
+ except Exception as e:
+ logger.error(f"Error analyzing news: {e}")
+ return self._empty_analysis()
+
+ def extract_news_items(
+ self, search_results: List[Dict[str, Any]], max_items: int = 10
+ ) -> List[Dict[str, Any]]:
+ """
+ Extract structured news items from search results.
+
+ Args:
+ search_results: Raw search results
+ max_items: Maximum number of items to extract
+
+ Returns:
+ List of structured news items
+ """
+ if not self.llm_client:
+ logger.warning("No LLM client available for news extraction")
+ return []
+
+ # Prepare search results for LLM
+ snippets = self._prepare_snippets(
+ search_results # Use all results, let LLM handle token limits
+ )
+
+ prompt = f"""
+Extract up to {max_items} important news stories from these search results.
+Today's date: {datetime.now().strftime("%B %d, %Y")}
+
+{snippets}
+
+For each news story, extract:
+1. headline - 8 words max describing the story
+2. category - A descriptive category for this news (be specific, not limited to generic categories)
+3. summary - 3 clear sentences about what happened
+4. impact_score - 1-10 based on significance
+5. source_url - URL from the search results
+6. entities - people, places, organizations mentioned
+7. is_developing - true/false if story is still developing
+8. time_ago - when it happened (2 hours ago, yesterday, etc)
+
+Return as JSON array of news items.
+Focus on genuinely newsworthy stories.
+"""
+
+ try:
+ response = self.llm_client.invoke(prompt)
+ content = (
+ response.content
+ if hasattr(response, "content")
+ else str(response)
+ )
+
+ # Parse JSON response
+ import json
+ import re
+
+ # Extract JSON array
+ json_match = re.search(r"\[.*\]", content, re.DOTALL)
+ if json_match:
+ news_items = json.loads(json_match.group())
+
+ # Validate and clean items
+ valid_items = []
+ for item in news_items[:max_items]:
+ if self._validate_news_item(item):
+ # Generate ID
+ item["id"] = generate_card_id()
+ valid_items.append(item)
+
+ return valid_items
+
+ except Exception as e:
+ logger.error(f"Error extracting news items: {e}")
+
+ return []
+
+ def generate_big_picture(self, news_items: List[Dict[str, Any]]) -> str:
+ """
+ Generate the big picture summary of how events connect.
+
+ Args:
+ news_items: Extracted news items
+
+ Returns:
+ Big picture summary (3-4 sentences)
+ """
+ if not self.llm_client or not news_items:
+ return ""
+
+ # Prepare news summaries
+ summaries = "\n".join(
+ [
+ f"- {item['headline']}: {item.get('summary', '')[:100]}..."
+ for item in news_items[:10]
+ ]
+ )
+
+ prompt = f"""
+Based on these news stories, write THE BIG PICTURE summary.
+Connect the dots between events. What's the larger narrative?
+Write 3-4 sentences maximum.
+
+News stories:
+{summaries}
+
+THE BIG PICTURE:"""
+
+ try:
+ response = self.llm_client.invoke(prompt)
+ content = (
+ response.content
+ if hasattr(response, "content")
+ else str(response)
+ )
+ return content.strip()
+ except Exception as e:
+ logger.error(f"Error generating big picture: {e}")
+ return ""
+
+ def generate_watch_for(self, news_items: List[Dict[str, Any]]) -> List[str]:
+ """
+ Generate list of developments to watch for in next 24-48 hours.
+
+ Args:
+ news_items: Extracted news items
+
+ Returns:
+ List of bullet points
+ """
+ if not self.llm_client or not news_items:
+ return []
+
+ # Focus on developing stories
+ developing = [
+ item for item in news_items if item.get("is_developing", False)
+ ]
+ if not developing:
+ developing = news_items[:5]
+
+ summaries = "\n".join(
+ [
+ f"- {item['headline']}: {item.get('summary', '')[:100]}..."
+ for item in developing
+ ]
+ )
+
+ prompt = f"""
+Based on these developing news stories, what should we watch for in the next 24-48 hours?
+Write 3-5 specific, actionable items.
+
+Developing stories:
+{summaries}
+
+WATCH FOR:
+-"""
+
+ try:
+ response = self.llm_client.invoke(prompt)
+ content = (
+ response.content
+ if hasattr(response, "content")
+ else str(response)
+ )
+
+ # Parse bullet points
+ lines = content.strip().split("\n")
+ watch_items = []
+ for line in lines:
+ line = line.strip()
+ if line and line not in ["WATCH FOR:", "Watch for:"]:
+ # Remove bullet markers
+ line = line.lstrip("-•* ")
+ if line:
+ watch_items.append(line)
+
+ return watch_items[:5]
+
+ except Exception as e:
+ logger.error(f"Error generating watch items: {e}")
+ return []
+
+ def generate_patterns(self, news_items: List[Dict[str, Any]]) -> str:
+ """
+ Identify emerging patterns from today's news.
+
+ Args:
+ news_items: Extracted news items
+
+ Returns:
+ Pattern recognition summary
+ """
+ if not self.llm_client or not news_items:
+ return ""
+
+ # Group by category
+ by_category = {}
+ for item in news_items:
+ cat = item.get("category", "Other")
+ if cat not in by_category:
+ by_category[cat] = []
+ by_category[cat].append(item["headline"])
+
+ category_summary = "\n".join(
+ [
+ f"{cat}: {len(items)} stories"
+ for cat, items in by_category.items()
+ ]
+ )
+
+ prompt = f"""
+Identify emerging patterns from today's news distribution:
+
+{category_summary}
+
+Top headlines:
+{chr(10).join([f"- {item['headline']}" for item in news_items[:10]])}
+
+PATTERN RECOGNITION (1-2 sentences):"""
+
+ try:
+ response = self.llm_client.invoke(prompt)
+ content = (
+ response.content
+ if hasattr(response, "content")
+ else str(response)
+ )
+ return content.strip()
+ except Exception as e:
+ logger.error(f"Error generating patterns: {e}")
+ return ""
+
+ def extract_topics(
+ self, news_items: List[Dict[str, Any]]
+ ) -> List[Dict[str, Any]]:
+ """
+ Extract subscribable topics from news items.
+
+ Args:
+ news_items: Extracted news items
+
+ Returns:
+ List of topic dictionaries with metadata
+ """
+ topics = []
+
+ # Use topic registry to extract from each item
+ for item in news_items:
+ # Combine headline and summary for better topic extraction
+ content = f"{item.get('headline', '')} {item.get('summary', '')}"
+
+ extracted = self.topic_registry.extract_topics(
+ content, max_topics=3
+ )
+
+ for topic in extracted:
+ topics.append(
+ {
+ "name": topic,
+ "source_item_id": item.get("id"),
+ "source_headline": item.get("headline"),
+ "category": item.get("category"),
+ "impact_score": item.get("impact_score", 5),
+ }
+ )
+
+ # Deduplicate and sort by frequency
+ topic_counts = {}
+ topic_metadata = {}
+
+ for topic_info in topics:
+ name = topic_info["name"]
+ if name not in topic_counts:
+ topic_counts[name] = 0
+ topic_metadata[name] = topic_info
+ topic_counts[name] += 1
+
+ # Keep highest impact score
+ if (
+ topic_info["impact_score"]
+ > topic_metadata[name]["impact_score"]
+ ):
+ topic_metadata[name] = topic_info
+
+ # Create final topic list
+ final_topics = []
+ for topic, count in sorted(
+ topic_counts.items(), key=lambda x: x[1], reverse=True
+ ):
+ metadata = topic_metadata[topic]
+ metadata["frequency"] = count
+ metadata["query"] = f"{topic} latest developments news"
+ final_topics.append(metadata)
+
+ return final_topics[:10] # Top 10 topics
+
+ def _prepare_snippets(self, search_results: List[Dict[str, Any]]) -> str:
+ """Prepare search result snippets for LLM processing."""
+ snippets = []
+ for i, result in enumerate(search_results):
+ snippet = f"[{i + 1}] "
+ if result.get("title"):
+ snippet += f"Title: {result['title']}\n"
+ if result.get("url"):
+ snippet += f"URL: {result['url']}\n"
+ if result.get("snippet"):
+ snippet += f"Snippet: {result['snippet'][:200]}...\n"
+ elif result.get("content"):
+ snippet += f"Content: {result['content'][:200]}...\n"
+
+ snippets.append(snippet)
+
+ return "\n".join(snippets)
+
+ def _validate_news_item(self, item: Dict[str, Any]) -> bool:
+ """Validate that a news item has required fields."""
+ required = ["headline", "summary"]
+ return all(field in item and item[field] for field in required)
+
+ def _count_categories(
+ self, news_items: List[Dict[str, Any]]
+ ) -> Dict[str, int]:
+ """Count items by category."""
+ counts = {}
+ for item in news_items:
+ cat = item.get("category", "Other")
+ counts[cat] = counts.get(cat, 0) + 1
+ return counts
+
+ def _summarize_impact(
+ self, news_items: List[Dict[str, Any]]
+ ) -> Dict[str, Any]:
+ """Summarize impact scores."""
+ if not news_items:
+ return {"average": 0, "high_impact_count": 0}
+
+ scores = [item.get("impact_score", 5) for item in news_items]
+ return {
+ "average": sum(scores) / len(scores),
+ "high_impact_count": len([s for s in scores if s >= 8]),
+ "max": max(scores),
+ "min": min(scores),
+ }
+
+ def _empty_analysis(self) -> Dict[str, Any]:
+ """Return empty analysis structure."""
+ return {
+ "items": [],
+ "item_count": 0,
+ "big_picture": "",
+ "watch_for": [],
+ "patterns": "",
+ "topics": [],
+ "categories": {},
+ "impact_summary": {"average": 0, "high_impact_count": 0},
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ }
+
+ def _categorize_news(self, headline: str, content: str = "") -> str:
+ """
+ Categorize a news item based on headline and content.
+
+ Args:
+ headline: News headline
+ content: Optional news content
+
+ Returns:
+ Category name
+ """
+ # Simple keyword-based categorization
+ combined_text = (headline + " " + content).lower()
+
+ # Category keywords
+ categories = {
+ "Technology": [
+ "tech",
+ "software",
+ "ai",
+ "computer",
+ "digital",
+ "internet",
+ "app",
+ "iphone",
+ "android",
+ "google",
+ "apple",
+ "microsoft",
+ ],
+ "Economy": [
+ "economy",
+ "market",
+ "stock",
+ "finance",
+ "trade",
+ "business",
+ "gdp",
+ "inflation",
+ "recession",
+ "bank",
+ "dollar",
+ "crypto",
+ ],
+ "Health": [
+ "health",
+ "covid",
+ "virus",
+ "vaccine",
+ "medical",
+ "disease",
+ "hospital",
+ "doctor",
+ "patient",
+ "pandemic",
+ "treatment",
+ ],
+ "Politics": [
+ "president",
+ "government",
+ "election",
+ "congress",
+ "senate",
+ "policy",
+ "law",
+ "bill",
+ "vote",
+ "political",
+ "minister",
+ ],
+ "Science": [
+ "research",
+ "study",
+ "scientist",
+ "discovery",
+ "experiment",
+ "climate",
+ "space",
+ "nasa",
+ "physics",
+ "biology",
+ ],
+ "Sports": [
+ "sport",
+ "game",
+ "player",
+ "team",
+ "win",
+ "championship",
+ "football",
+ "basketball",
+ "soccer",
+ "olympic",
+ ],
+ }
+
+ # Count keyword matches
+ category_scores = {}
+ for category, keywords in categories.items():
+ score = sum(1 for keyword in keywords if keyword in combined_text)
+ if score > 0:
+ category_scores[category] = score
+
+ # Return highest scoring category
+ if category_scores:
+ return max(category_scores.items(), key=lambda x: x[1])[0]
+
+ return "General"
diff --git a/src/local_deep_research/news/core/priority_manager.py b/src/local_deep_research/news/core/priority_manager.py
new file mode 100644
index 0000000000..759f6415df
--- /dev/null
+++ b/src/local_deep_research/news/core/priority_manager.py
@@ -0,0 +1,275 @@
+"""
+Priority manager to ensure user searches always take precedence over news searches.
+Implements a singleton pattern to coordinate across the system.
+"""
+
+import threading
+from typing import Set, Optional, Dict, Any
+from loguru import logger
+
+from ..core.utils import utc_now
+
+
+class PriorityManager:
+ """
+ Manages search priorities to ensure user searches are never blocked by news searches.
+
+ When a user search starts:
+ 1. All active news searches are immediately stopped
+ 2. No new news searches can start
+ 3. News searches resume from beginning after user search completes
+
+ This is a singleton - use get_priority_manager() to access.
+ """
+
+ _instance = None
+ _lock = threading.Lock()
+
+ def __new__(cls):
+ if cls._instance is None:
+ with cls._lock:
+ if cls._instance is None:
+ cls._instance = super().__new__(cls)
+ return cls._instance
+
+ def __init__(self):
+ # Only initialize once
+ if not hasattr(self, "_initialized"):
+ self._initialized = True
+
+ # Track active searches
+ self.user_search_active = False
+ self.active_user_searches: Set[str] = set()
+ self.active_news_searches: Set[str] = set()
+
+ # Callbacks for stopping news searches
+ self.stop_callbacks: Dict[str, Any] = {}
+
+ # Statistics
+ self.stats = {
+ "user_searches_started": 0,
+ "news_searches_interrupted": 0,
+ "news_searches_completed": 0,
+ "last_user_search": None,
+ "last_news_interruption": None,
+ }
+
+ # Thread safety
+ self._state_lock = threading.Lock()
+
+ logger.info("PriorityManager initialized")
+
+ def on_user_search_start(self, search_id: str) -> None:
+ """
+ Called when a user search begins.
+ Immediately stops all news searches.
+
+ Args:
+ search_id: Unique identifier for the search
+ """
+ with self._state_lock:
+ self.active_user_searches.add(search_id)
+ self.user_search_active = True
+
+ # Update stats
+ self.stats["user_searches_started"] += 1
+ self.stats["last_user_search"] = utc_now()
+
+ # Stop all active news searches
+ news_searches_to_stop = list(self.active_news_searches)
+ if news_searches_to_stop:
+ logger.info(
+ f"User search {search_id} starting - "
+ f"interrupting {len(news_searches_to_stop)} news searches"
+ )
+ self.stats["news_searches_interrupted"] += len(
+ news_searches_to_stop
+ )
+ self.stats["last_news_interruption"] = utc_now()
+
+ # Call stop callbacks
+ for news_search_id in news_searches_to_stop:
+ self._stop_news_search(news_search_id)
+
+ def on_user_search_complete(self, search_id: str) -> None:
+ """
+ Called when a user search completes.
+ Allows news searches to resume if no other user searches are active.
+
+ Args:
+ search_id: The search that completed
+ """
+ with self._state_lock:
+ self.active_user_searches.discard(search_id)
+
+ # Only clear user_search_active if no other user searches
+ if not self.active_user_searches:
+ self.user_search_active = False
+ logger.info(
+ f"User search {search_id} complete - news searches can resume"
+ )
+ else:
+ logger.info(
+ f"User search {search_id} complete - "
+ f"{len(self.active_user_searches)} user searches still active"
+ )
+
+ def register_news_search(
+ self, search_id: str, stop_callback: Optional[Any] = None
+ ) -> bool:
+ """
+ Register a news search attempt.
+
+ Args:
+ search_id: Unique identifier for the search
+ stop_callback: Optional callback to call if search needs to stop
+
+ Returns:
+ True if the search can proceed, False if blocked by user search
+ """
+ with self._state_lock:
+ if self.user_search_active:
+ logger.debug(
+ f"News search {search_id} blocked - user search active"
+ )
+ return False
+
+ self.active_news_searches.add(search_id)
+ if stop_callback:
+ self.stop_callbacks[search_id] = stop_callback
+
+ logger.debug(f"News search {search_id} registered and can proceed")
+ return True
+
+ def unregister_news_search(self, search_id: str) -> None:
+ """
+ Unregister a news search when it completes or is stopped.
+
+ Args:
+ search_id: The search to unregister
+ """
+ with self._state_lock:
+ self.active_news_searches.discard(search_id)
+ self.stop_callbacks.pop(search_id, None)
+
+ if search_id in self.active_news_searches:
+ self.stats["news_searches_completed"] += 1
+
+ def can_start_news_search(self) -> bool:
+ """
+ Check if news searches are currently allowed.
+
+ Returns:
+ True if no user searches are active
+ """
+ return not self.user_search_active
+
+ def _stop_news_search(self, search_id: str) -> None:
+ """
+ Stop a specific news search.
+
+ Args:
+ search_id: The search to stop
+ """
+ callback = self.stop_callbacks.get(search_id)
+ if callback:
+ try:
+ callback()
+ except Exception as e:
+ logger.error(
+ f"Error calling stop callback for {search_id}: {e}"
+ )
+
+ self.active_news_searches.discard(search_id)
+ self.stop_callbacks.pop(search_id, None)
+
+ def get_status(self) -> Dict[str, Any]:
+ """
+ Get current status and statistics.
+
+ Returns:
+ Dictionary with current state and stats
+ """
+ with self._state_lock:
+ return {
+ "user_search_active": self.user_search_active,
+ "active_user_searches": len(self.active_user_searches),
+ "active_news_searches": len(self.active_news_searches),
+ "can_start_news_search": self.can_start_news_search(),
+ "stats": self.stats.copy(),
+ }
+
+ def reset_stats(self) -> None:
+ """Reset statistics counters."""
+ with self._state_lock:
+ self.stats = {
+ "user_searches_started": 0,
+ "news_searches_interrupted": 0,
+ "news_searches_completed": 0,
+ "last_user_search": None,
+ "last_news_interruption": None,
+ }
+
+
+# Global instance getter
+def get_priority_manager() -> PriorityManager:
+ """
+ Get the global PriorityManager instance.
+
+ Returns:
+ The singleton PriorityManager
+ """
+ return PriorityManager()
+
+
+# Context manager for user searches
+class UserSearchContext:
+ """
+ Context manager to wrap user searches with priority management.
+
+ Usage:
+ with UserSearchContext(search_id):
+ # Perform user search
+ # News searches are blocked during this block
+ """
+
+ def __init__(self, search_id: str):
+ self.search_id = search_id
+ self.manager = get_priority_manager()
+
+ def __enter__(self):
+ self.manager.on_user_search_start(self.search_id)
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ self.manager.on_user_search_complete(self.search_id)
+
+
+# Context manager for news searches
+class NewsSearchContext:
+ """
+ Context manager to wrap news searches with priority checking.
+
+ Usage:
+ with NewsSearchContext(search_id) as ctx:
+ if ctx.can_proceed:
+ # Perform news search
+ else:
+ # Skip - user search is active
+ """
+
+ def __init__(self, search_id: str, stop_callback=None):
+ self.search_id = search_id
+ self.stop_callback = stop_callback
+ self.manager = get_priority_manager()
+ self.can_proceed = False
+
+ def __enter__(self):
+ self.can_proceed = self.manager.register_news_search(
+ self.search_id, self.stop_callback
+ )
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ if self.can_proceed:
+ self.manager.unregister_news_search(self.search_id)
diff --git a/src/local_deep_research/news/core/relevance_service.py b/src/local_deep_research/news/core/relevance_service.py
new file mode 100644
index 0000000000..2dc826db06
--- /dev/null
+++ b/src/local_deep_research/news/core/relevance_service.py
@@ -0,0 +1,156 @@
+"""
+Relevance and trending calculation service.
+Handles business logic for calculating relevance scores and trending metrics.
+"""
+
+from typing import Optional, Dict, List
+from .base_card import BaseCard
+
+
+class RelevanceService:
+ """Service for calculating relevance and trending scores."""
+
+ def calculate_relevance(
+ self, card: BaseCard, user_prefs: Optional[Dict]
+ ) -> float:
+ """
+ Calculate relevance score for a card based on user preferences.
+
+ Args:
+ card: The card to score
+ user_prefs: User preferences dictionary
+
+ Returns:
+ Relevance score between 0 and 1
+ """
+ if not user_prefs:
+ # Default relevance based on impact
+ return getattr(card, "impact_score", 5) / 10.0
+
+ score = 0.5 # Base score
+
+ # Category preference
+ if hasattr(card, "category"):
+ if card.category in user_prefs.get("liked_categories", []):
+ score += 0.2
+ elif card.category in user_prefs.get("disliked_categories", []):
+ score -= 0.2
+
+ # Impact threshold
+ if hasattr(card, "impact_score"):
+ threshold = user_prefs.get("impact_threshold", 5)
+ if card.impact_score >= threshold:
+ score += 0.1
+ else:
+ score -= 0.1
+
+ # Topic matching (simplified without embeddings)
+ if hasattr(card, "topics"):
+ liked_topics = user_prefs.get("liked_topics", [])
+ for topic in card.topics:
+ if any(liked in topic.lower() for liked in liked_topics):
+ score += 0.1
+ break
+
+ # Ensure score is in valid range
+ return max(0.0, min(1.0, score))
+
+ def calculate_trending_score(self, card: BaseCard) -> float:
+ """
+ Calculate trending score based on impact and engagement.
+
+ Args:
+ card: The card to score
+
+ Returns:
+ Trending score
+ """
+ if not hasattr(card, "impact_score"):
+ return 0.0
+
+ # Calculate engagement
+ engagement = (
+ card.interaction.get("views", 0)
+ + card.interaction.get("votes_up", 0) * 2
+ - card.interaction.get("votes_down", 0)
+ )
+
+ # Combine impact and engagement
+ trending_score = card.impact_score + (engagement / 10)
+
+ return trending_score
+
+ def filter_trending(
+ self, cards: List[BaseCard], min_impact: int = 7, limit: int = 10
+ ) -> List[BaseCard]:
+ """
+ Filter and sort cards by trending score.
+
+ Args:
+ cards: List of cards to filter
+ min_impact: Minimum impact score required
+ limit: Maximum number of cards to return
+
+ Returns:
+ List of trending cards sorted by score
+ """
+ trending = []
+
+ for card in cards:
+ if (
+ hasattr(card, "impact_score")
+ and card.impact_score >= min_impact
+ ):
+ card.trending_score = self.calculate_trending_score(card)
+ trending.append(card)
+
+ # Sort by trending score
+ trending.sort(key=lambda c: c.trending_score, reverse=True)
+
+ return trending[:limit]
+
+ def personalize_feed(
+ self,
+ cards: List[BaseCard],
+ user_prefs: Optional[Dict],
+ include_seen: bool = True,
+ ) -> List[BaseCard]:
+ """
+ Personalize a feed of cards based on user preferences.
+
+ Args:
+ cards: List of cards to personalize
+ user_prefs: User preferences
+ include_seen: Whether to include already viewed cards
+
+ Returns:
+ Personalized list of cards
+ """
+ personalized = []
+
+ for card in cards:
+ # Calculate relevance
+ card.relevance_score = self.calculate_relevance(card, user_prefs)
+
+ # Filter seen if requested
+ if not include_seen and card.interaction.get("viewed"):
+ continue
+
+ personalized.append(card)
+
+ # Sort by relevance
+ personalized.sort(key=lambda c: c.relevance_score, reverse=True)
+
+ return personalized
+
+
+# Singleton instance
+_relevance_service = None
+
+
+def get_relevance_service() -> RelevanceService:
+ """Get or create the global RelevanceService instance."""
+ global _relevance_service
+ if _relevance_service is None:
+ _relevance_service = RelevanceService()
+ return _relevance_service
diff --git a/src/local_deep_research/news/core/search_integration.py b/src/local_deep_research/news/core/search_integration.py
new file mode 100644
index 0000000000..dda99f21aa
--- /dev/null
+++ b/src/local_deep_research/news/core/search_integration.py
@@ -0,0 +1,181 @@
+"""
+Integration with LDR's search system to track searches and manage priorities.
+"""
+
+import uuid
+from typing import Optional, Dict, Any, Callable
+from datetime import datetime, timezone
+from loguru import logger
+
+from .priority_manager import get_priority_manager, UserSearchContext
+from ...utilities.db_utils import get_db_setting
+
+
+class NewsSearchCallback:
+ """
+ Callback handler for search system integration.
+ Tracks searches for news personalization if enabled.
+ """
+
+ def __init__(self):
+ self.priority_manager = get_priority_manager()
+ self._enabled = None
+ self._tracking_enabled = None
+
+ @property
+ def enabled(self) -> bool:
+ """Check if news system is enabled."""
+ if self._enabled is None:
+ self._enabled = get_db_setting("news.enabled", True)
+ return self._enabled
+
+ @property
+ def tracking_enabled(self) -> bool:
+ """Check if search tracking is enabled."""
+ if self._tracking_enabled is None:
+ self._tracking_enabled = get_db_setting(
+ "news.search_tracking", False
+ )
+ return self._tracking_enabled
+
+ def __call__(
+ self,
+ query: str,
+ result: Dict[str, Any],
+ context: Optional[Dict[str, Any]] = None,
+ ) -> None:
+ """
+ Process a search completion.
+
+ Args:
+ query: The search query
+ result: The search results
+ context: Optional context (includes is_user_search, user_id, etc.)
+ """
+ if not self.enabled:
+ return
+
+ # Extract context
+ context = context or {}
+ is_user_search = context.get("is_user_search", True)
+ user_id = context.get("user_id", "anonymous")
+ search_id = context.get("search_id", str(uuid.uuid4()))
+
+ # Log the search if tracking is enabled
+ if is_user_search and self.tracking_enabled:
+ self._track_user_search(
+ search_id=search_id, user_id=user_id, query=query, result=result
+ )
+
+ def _track_user_search(
+ self, search_id: str, user_id: str, query: str, result: Dict[str, Any]
+ ) -> None:
+ """
+ Track a user search for personalization.
+
+ Args:
+ search_id: Unique search ID
+ user_id: User who performed the search
+ query: The search query
+ result: The search results
+ """
+ try:
+ # Import here to avoid circular imports
+ from ..preference_manager.search_tracker import SearchTracker
+
+ tracker = SearchTracker()
+ tracker.track_search(
+ user_id=user_id,
+ query=query,
+ search_id=search_id,
+ result_quality=self._calculate_quality(result),
+ result_count=len(result.get("findings", [])),
+ strategy_used=result.get("strategy", "unknown"),
+ )
+
+ logger.debug(f"Tracked user search: {query[:50]}...")
+
+ except Exception as e:
+ logger.error(f"Error tracking search: {e}")
+
+ def _calculate_quality(self, result: Dict[str, Any]) -> float:
+ """
+ Calculate quality score for search results.
+
+ Args:
+ result: Search results
+
+ Returns:
+ Quality score between 0 and 1
+ """
+ # Simple heuristic based on result count and content
+ findings = result.get("findings", [])
+ if not findings:
+ return 0.0
+
+ # More findings generally means better results
+ count_score = min(len(findings) / 10, 1.0)
+
+ # Check if we have actual content
+ has_content = any(f.get("content") for f in findings[:5])
+ content_score = 1.0 if has_content else 0.5
+
+ return (count_score + content_score) / 2
+
+
+def create_search_wrapper(original_search_method: Callable) -> Callable:
+ """
+ Create a wrapper for search methods that integrates priority management.
+
+ Args:
+ original_search_method: The original search method to wrap
+
+ Returns:
+ Wrapped method with priority management
+ """
+ callback = NewsSearchCallback()
+ get_priority_manager()
+
+ def wrapped_search(self, query: str, **kwargs) -> Dict[str, Any]:
+ """Wrapped search with priority management."""
+
+ # Determine if this is a user search
+ is_user_search = kwargs.pop("is_user_search", True)
+ is_news_search = kwargs.pop("is_news_search", False)
+ user_id = kwargs.pop("user_id", "anonymous")
+
+ # Generate search ID
+ search_id = str(uuid.uuid4())
+
+ # Build context
+ context = {
+ "is_user_search": is_user_search and not is_news_search,
+ "is_news_search": is_news_search,
+ "user_id": user_id,
+ "search_id": search_id,
+ "timestamp": datetime.now(timezone.utc),
+ }
+
+ # Handle priority
+ if is_user_search and not is_news_search:
+ # User search - use priority context
+ with UserSearchContext(search_id):
+ result = original_search_method(self, query, **kwargs)
+ else:
+ # News search or other - just run normally
+ result = original_search_method(self, query, **kwargs)
+
+ # Call callback if available
+ if callback.enabled:
+ try:
+ callback(query, result, context)
+ except Exception as e:
+ logger.error(f"Error in news callback: {e}")
+
+ return result
+
+ # Preserve method metadata
+ wrapped_search.__name__ = original_search_method.__name__
+ wrapped_search.__doc__ = original_search_method.__doc__
+
+ return wrapped_search
diff --git a/src/local_deep_research/news/core/storage.py b/src/local_deep_research/news/core/storage.py
new file mode 100644
index 0000000000..93f04c573d
--- /dev/null
+++ b/src/local_deep_research/news/core/storage.py
@@ -0,0 +1,269 @@
+"""
+Base storage interfaces for the news system.
+"""
+
+from abc import ABC, abstractmethod
+from typing import List, Optional, Dict, Any
+from datetime import datetime
+import uuid
+
+
+class BaseStorage(ABC):
+ """Abstract base class for all storage interfaces"""
+
+ @abstractmethod
+ def create(self, data: Dict[str, Any]) -> str:
+ """Create a new record and return its ID"""
+ pass
+
+ @abstractmethod
+ def get(self, id: str) -> Optional[Dict[str, Any]]:
+ """Get a record by ID"""
+ pass
+
+ @abstractmethod
+ def update(self, id: str, data: Dict[str, Any]) -> bool:
+ """Update a record, return True if successful"""
+ pass
+
+ @abstractmethod
+ def delete(self, id: str) -> bool:
+ """Delete a record, return True if successful"""
+ pass
+
+ @abstractmethod
+ def list(
+ self,
+ filters: Optional[Dict[str, Any]] = None,
+ limit: int = 100,
+ offset: int = 0,
+ ) -> List[Dict[str, Any]]:
+ """List records with optional filtering"""
+ pass
+
+ def generate_id(self) -> str:
+ """Generate a unique ID"""
+ return str(uuid.uuid4())
+
+
+class CardStorage(BaseStorage):
+ """Interface for news card storage"""
+
+ @abstractmethod
+ def get_by_user(
+ self, user_id: str, limit: int = 50, offset: int = 0
+ ) -> List[Dict[str, Any]]:
+ """Get cards for a specific user"""
+ pass
+
+ @abstractmethod
+ def get_latest_version(self, card_id: str) -> Optional[Dict[str, Any]]:
+ """Get the latest version of a card"""
+ pass
+
+ @abstractmethod
+ def add_version(self, card_id: str, version_data: Dict[str, Any]) -> str:
+ """Add a new version to a card"""
+ pass
+
+ @abstractmethod
+ def update_latest_info(
+ self, card_id: str, version_data: Dict[str, Any]
+ ) -> bool:
+ """Update the denormalized latest version info on the card"""
+ pass
+
+ @abstractmethod
+ def archive_card(self, card_id: str) -> bool:
+ """Archive a card"""
+ pass
+
+ @abstractmethod
+ def pin_card(self, card_id: str, pinned: bool = True) -> bool:
+ """Pin or unpin a card"""
+ pass
+
+
+class SubscriptionStorage(BaseStorage):
+ """Interface for subscription storage"""
+
+ @abstractmethod
+ def get_active_subscriptions(
+ self, user_id: Optional[str] = None
+ ) -> List[Dict[str, Any]]:
+ """Get all active subscriptions, optionally filtered by user"""
+ pass
+
+ @abstractmethod
+ def get_due_subscriptions(self, limit: int = 100) -> List[Dict[str, Any]]:
+ """Get subscriptions that are due for refresh"""
+ pass
+
+ @abstractmethod
+ def update_refresh_time(
+ self,
+ subscription_id: str,
+ last_refresh: datetime,
+ next_refresh: datetime,
+ ) -> bool:
+ """Update refresh timestamps after processing"""
+ pass
+
+ @abstractmethod
+ def increment_stats(self, subscription_id: str, results_count: int) -> bool:
+ """Increment refresh count and update results count"""
+ pass
+
+ @abstractmethod
+ def pause_subscription(self, subscription_id: str) -> bool:
+ """Pause a subscription"""
+ pass
+
+ @abstractmethod
+ def resume_subscription(self, subscription_id: str) -> bool:
+ """Resume a paused subscription"""
+ pass
+
+ @abstractmethod
+ def expire_subscription(self, subscription_id: str) -> bool:
+ """Mark a subscription as expired"""
+ pass
+
+
+class RatingStorage(BaseStorage):
+ """Interface for rating storage"""
+
+ @abstractmethod
+ def get_user_rating(
+ self, user_id: str, item_id: str, rating_type: str
+ ) -> Optional[Dict[str, Any]]:
+ """Get a user's rating for a specific item"""
+ pass
+
+ @abstractmethod
+ def upsert_rating(
+ self,
+ user_id: str,
+ item_id: str,
+ rating_type: str,
+ rating_value: str,
+ item_type: str = "card",
+ ) -> str:
+ """Create or update a rating"""
+ pass
+
+ @abstractmethod
+ def get_ratings_summary(
+ self, item_id: str, item_type: str = "card"
+ ) -> Dict[str, Any]:
+ """Get aggregated ratings for an item"""
+ pass
+
+ @abstractmethod
+ def get_user_ratings(
+ self, user_id: str, rating_type: Optional[str] = None, limit: int = 100
+ ) -> List[Dict[str, Any]]:
+ """Get all ratings by a user"""
+ pass
+
+
+class PreferenceStorage(BaseStorage):
+ """Interface for user preference storage"""
+
+ @abstractmethod
+ def get_user_preferences(self, user_id: str) -> Optional[Dict[str, Any]]:
+ """Get preferences for a user"""
+ pass
+
+ @abstractmethod
+ def upsert_preferences(
+ self, user_id: str, preferences: Dict[str, Any]
+ ) -> str:
+ """Create or update user preferences"""
+ pass
+
+ @abstractmethod
+ def add_liked_item(
+ self, user_id: str, item_id: str, item_type: str = "news"
+ ) -> bool:
+ """Add an item to liked list"""
+ pass
+
+ @abstractmethod
+ def add_disliked_item(
+ self, user_id: str, item_id: str, item_type: str = "news"
+ ) -> bool:
+ """Add an item to disliked list"""
+ pass
+
+ @abstractmethod
+ def update_preference_embedding(
+ self, user_id: str, embedding: List[float]
+ ) -> bool:
+ """Update the user's preference embedding"""
+ pass
+
+
+class SearchHistoryStorage(BaseStorage):
+ """Interface for search history storage (if tracking enabled)"""
+
+ @abstractmethod
+ def record_search(
+ self, user_id: str, query: str, search_data: Dict[str, Any]
+ ) -> str:
+ """Record a search query"""
+ pass
+
+ @abstractmethod
+ def get_recent_searches(
+ self, user_id: str, hours: int = 48, limit: int = 50
+ ) -> List[Dict[str, Any]]:
+ """Get recent searches for a user"""
+ pass
+
+ @abstractmethod
+ def link_to_subscription(
+ self, search_id: str, subscription_id: str
+ ) -> bool:
+ """Link a search to a subscription created from it"""
+ pass
+
+ @abstractmethod
+ def get_popular_searches(
+ self, hours: int = 24, limit: int = 20
+ ) -> List[Dict[str, Any]]:
+ """Get popular searches across all users"""
+ pass
+
+
+class NewsItemStorage(BaseStorage):
+ """Interface for news item storage (the raw news data)"""
+
+ @abstractmethod
+ def get_recent(
+ self, hours: int = 24, limit: int = 50
+ ) -> List[Dict[str, Any]]:
+ """Get recent news items"""
+ pass
+
+ @abstractmethod
+ def store_batch(self, news_items: List[Dict[str, Any]]) -> List[str]:
+ """Store multiple news items at once"""
+ pass
+
+ @abstractmethod
+ def update_votes(self, news_id: str, vote_type: str) -> bool:
+ """Update vote counts"""
+ pass
+
+ @abstractmethod
+ def get_by_category(
+ self, category: str, limit: int = 50
+ ) -> List[Dict[str, Any]]:
+ """Get news items by category"""
+ pass
+
+ @abstractmethod
+ def cleanup_old_items(self, days: int = 7) -> int:
+ """Remove old news items, return count deleted"""
+ pass
diff --git a/src/local_deep_research/news/core/storage_manager.py b/src/local_deep_research/news/core/storage_manager.py
new file mode 100644
index 0000000000..51fecc0a97
--- /dev/null
+++ b/src/local_deep_research/news/core/storage_manager.py
@@ -0,0 +1,384 @@
+"""
+Centralized storage manager for all news system data.
+Provides unified access to cards, subscriptions, ratings, and preferences.
+"""
+
+from typing import List, Dict, Any, Optional
+from datetime import datetime, timedelta, timezone
+from loguru import logger
+
+from .card_factory import CardFactory
+from .base_card import BaseCard
+from .card_storage import SQLCardStorage
+from .relevance_service import get_relevance_service
+from ..subscription_manager.storage import SQLSubscriptionStorage
+from ..rating_system.storage import SQLRatingStorage
+from ..preference_manager.storage import SQLPreferenceStorage
+# from ..database import init_news_database # Not needed - tables created on demand
+
+
+class StorageManager:
+ """
+ Unified storage interface for the news system.
+ Manages all data access across modules.
+ """
+
+ def __init__(self):
+ """Initialize storage interfaces."""
+ # Tables are created automatically when needed
+
+ # Initialize storage interfaces
+ self.cards = SQLCardStorage()
+ self.subscriptions = SQLSubscriptionStorage()
+ self.ratings = SQLRatingStorage()
+ self.preferences = SQLPreferenceStorage()
+
+ # Card factory for reconstruction
+ self.card_factory = CardFactory
+
+ # Relevance service for business logic
+ self.relevance_service = get_relevance_service()
+
+ logger.info("StorageManager initialized")
+
+ def get_user_feed(
+ self,
+ user_id: str,
+ limit: int = 20,
+ offset: int = 0,
+ include_seen: bool = True,
+ card_types: Optional[List[str]] = None,
+ ) -> List[BaseCard]:
+ """
+ Get personalized news feed for a user.
+
+ Args:
+ user_id: The user ID
+ limit: Maximum cards to return
+ offset: Pagination offset
+ include_seen: Whether to include already viewed cards
+ card_types: Filter by card types
+
+ Returns:
+ List of cards sorted by relevance
+ """
+ try:
+ # Get user preferences
+ user_prefs = self.preferences.get(user_id)
+
+ # Get recent cards
+ if user_prefs and user_prefs.get("liked_categories"):
+ # Filter by user's preferred categories
+ filters = {
+ "user_id": user_id,
+ "categories": user_prefs["liked_categories"],
+ }
+ else:
+ filters = {"user_id": user_id}
+
+ if card_types:
+ filters["card_type"] = card_types
+
+ # Get cards from storage
+ cards_data = self.cards.list(
+ filters=filters,
+ limit=limit * 2, # Get extra to filter
+ offset=offset,
+ )
+
+ # Reconstruct card objects
+ cards = []
+ for data in cards_data:
+ card = CardFactory.load_card(data["id"])
+ if card:
+ cards.append(card)
+
+ # Apply personalization
+ cards = self.relevance_service.personalize_feed(
+ cards, user_prefs, include_seen=include_seen
+ )
+
+ return cards[:limit]
+
+ except Exception as e:
+ logger.error(f"Error getting user feed: {e}")
+ return []
+
+ def get_trending_news(
+ self, hours: int = 24, limit: int = 10, min_impact: int = 7
+ ) -> List[BaseCard]:
+ """
+ Get trending news across all users.
+
+ Args:
+ hours: Look back period
+ limit: Maximum cards
+ min_impact: Minimum impact score
+
+ Returns:
+ List of trending news cards
+ """
+ try:
+ # Get recent high-impact cards
+ cards = CardFactory.get_recent_cards(
+ hours=hours, card_types=["news"], limit=limit * 2
+ )
+
+ # Use relevance service to filter and sort trending
+ return self.relevance_service.filter_trending(
+ cards, min_impact=min_impact, limit=limit
+ )
+
+ except Exception as e:
+ logger.error(f"Error getting trending news: {e}")
+ return []
+
+ def record_interaction(
+ self,
+ user_id: str,
+ card_id: str,
+ interaction_type: str,
+ metadata: Optional[Dict] = None,
+ ) -> bool:
+ """
+ Record user interaction with a card.
+
+ Args:
+ user_id: The user
+ card_id: The card
+ interaction_type: Type of interaction (view, vote, share, etc.)
+ metadata: Additional data
+
+ Returns:
+ Success status
+ """
+ try:
+ # Load the card
+ card = CardFactory.load_card(card_id)
+ if not card:
+ return False
+
+ # Update interaction data
+ if interaction_type == "view":
+ card.interaction["viewed"] = True
+ card.interaction["last_viewed"] = datetime.now(timezone.utc)
+ card.interaction["views"] = card.interaction.get("views", 0) + 1
+
+ elif interaction_type == "vote_up":
+ card.interaction["voted"] = "up"
+ card.interaction["votes_up"] = (
+ card.interaction.get("votes_up", 0) + 1
+ )
+ # Record in ratings
+ self.ratings.save(
+ {
+ "user_id": user_id,
+ "card_id": card_id,
+ "rating_type": "relevance",
+ "value": 1,
+ }
+ )
+
+ elif interaction_type == "vote_down":
+ card.interaction["voted"] = "down"
+ card.interaction["votes_down"] = (
+ card.interaction.get("votes_down", 0) + 1
+ )
+ # Record in ratings
+ self.ratings.save(
+ {
+ "user_id": user_id,
+ "card_id": card_id,
+ "rating_type": "relevance",
+ "value": -1,
+ }
+ )
+
+ elif interaction_type == "research":
+ card.interaction["researched"] = True
+ card.interaction["research_count"] = (
+ card.interaction.get("research_count", 0) + 1
+ )
+
+ # Add metadata if provided
+ if metadata:
+ card.interaction[f"{interaction_type}_metadata"] = metadata
+
+ # Save updated card
+ return CardFactory.update_card(card)
+
+ except Exception as e:
+ logger.error(f"Error recording interaction: {e}")
+ return False
+
+ def get_user_subscriptions(self, user_id: str) -> List[Any]:
+ """
+ Get all subscriptions for a user.
+
+ Args:
+ user_id: The user
+
+ Returns:
+ List of subscription objects
+ """
+ try:
+ return self.subscriptions.list({"user_id": user_id})
+ except Exception as e:
+ logger.error(f"Error getting user subscriptions: {e}")
+ return []
+
+ def get_user_stats(self, user_id: str) -> Dict[str, Any]:
+ """
+ Get statistics for a user.
+
+ Args:
+ user_id: The user
+
+ Returns:
+ Dictionary of statistics
+ """
+ try:
+ # Get counts from various storages
+ subscription_count = len(
+ self.subscriptions.list({"user_id": user_id})
+ )
+
+ # Get rating counts
+ ratings = self.ratings.list({"user_id": user_id})
+ votes_up = sum(1 for r in ratings if r.get("value", 0) > 0)
+ votes_down = sum(1 for r in ratings if r.get("value", 0) < 0)
+
+ # Get card interaction stats
+ user_cards = self.cards.list({"user_id": user_id})
+ total_views = sum(
+ c.get("interaction", {}).get("views", 0) for c in user_cards
+ )
+
+ return {
+ "subscriptions": subscription_count,
+ "votes_up": votes_up,
+ "votes_down": votes_down,
+ "total_views": total_views,
+ "cards_created": len(user_cards),
+ "member_since": user_cards[0]["created_at"]
+ if user_cards
+ else None,
+ }
+
+ except Exception as e:
+ logger.error(f"Error getting user stats: {e}")
+ return {}
+
+ def get_card(self, card_id: str) -> Optional[BaseCard]:
+ """
+ Get a single card by ID.
+
+ Args:
+ card_id: The card ID
+
+ Returns:
+ Card object or None
+ """
+ try:
+ return CardFactory.load_card(card_id)
+ except Exception as e:
+ logger.error(f"Error getting card: {e}")
+ return None
+
+ def get_card_interactions(self, card_id: str) -> List[Dict[str, Any]]:
+ """
+ Get all interactions for a card.
+
+ Args:
+ card_id: The card ID
+
+ Returns:
+ List of interaction records
+ """
+ try:
+ # Get ratings which represent votes
+ ratings = self.ratings.list({"card_id": card_id})
+
+ # Convert to interaction format
+ interactions = []
+ for rating in ratings:
+ interaction = {
+ "user_id": rating.get("user_id"),
+ "interaction_type": "vote",
+ "interaction_data": {
+ "vote": "up" if rating.get("value", 0) > 0 else "down"
+ },
+ "timestamp": rating.get("created_at"),
+ }
+ interactions.append(interaction)
+
+ return interactions
+
+ except Exception as e:
+ logger.error(f"Error getting card interactions: {e}")
+ return []
+
+ def update_card(self, card: BaseCard) -> bool:
+ """
+ Update a card in storage.
+
+ Args:
+ card: The card to update
+
+ Returns:
+ Success status
+ """
+ try:
+ return CardFactory.update_card(card)
+ except Exception as e:
+ logger.error(f"Error updating card: {e}")
+ return False
+
+ def cleanup_old_data(self, days: int = 30) -> Dict[str, int]:
+ """
+ Clean up old data from all storages.
+
+ Args:
+ days: Age threshold in days
+
+ Returns:
+ Counts of deleted items
+ """
+ try:
+ cutoff = datetime.now(timezone.utc) - timedelta(days=days)
+ counts = {}
+
+ # Clean old cards (except subscribed ones)
+ old_cards = self.cards.list(
+ {"created_before": cutoff, "not_subscribed": True}
+ )
+ deleted_cards = 0
+ for card_data in old_cards:
+ if self.cards.delete(card_data["id"]):
+ deleted_cards += 1
+ counts["cards"] = deleted_cards
+
+ # Clean old ratings
+ old_ratings = self.ratings.list({"created_before": cutoff})
+ counts["ratings"] = len(old_ratings)
+ for rating in old_ratings:
+ self.ratings.delete(rating["id"])
+
+ logger.info(f"Cleanup complete: {counts}")
+ return counts
+
+ except Exception as e:
+ logger.error(f"Error during cleanup: {e}")
+ return {}
+
+
+# Singleton instance
+_storage_manager = None
+
+
+def get_storage_manager() -> StorageManager:
+ """Get or create the global StorageManager instance."""
+ global _storage_manager
+ if _storage_manager is None:
+ _storage_manager = StorageManager()
+ return _storage_manager
diff --git a/src/local_deep_research/news/core/utils.py b/src/local_deep_research/news/core/utils.py
new file mode 100644
index 0000000000..f3d2f190a6
--- /dev/null
+++ b/src/local_deep_research/news/core/utils.py
@@ -0,0 +1,53 @@
+"""
+Core utilities for the news system.
+"""
+
+import uuid
+from datetime import datetime, timezone
+
+
+def generate_card_id() -> str:
+ """
+ Generate a unique ID for a news card using UUID.
+
+ Returns:
+ str: A unique UUID string
+ """
+ return str(uuid.uuid4())
+
+
+def generate_subscription_id() -> str:
+ """
+ Generate a unique ID for a subscription.
+
+ Returns:
+ str: A unique UUID string
+ """
+ return str(uuid.uuid4())
+
+
+def utc_now() -> datetime:
+ """
+ Get current UTC time with timezone awareness.
+
+ Returns:
+ datetime: Current UTC time
+ """
+ return datetime.now(timezone.utc)
+
+
+def hours_ago(dt: datetime) -> float:
+ """
+ Calculate how many hours ago a datetime was.
+
+ Args:
+ dt: The datetime to compare
+
+ Returns:
+ float: Number of hours ago (negative if in future)
+ """
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo=timezone.utc)
+
+ delta = utc_now() - dt
+ return delta.total_seconds() / 3600
diff --git a/src/local_deep_research/news/database.py b/src/local_deep_research/news/database.py
new file mode 100644
index 0000000000..d6f2f18a0a
--- /dev/null
+++ b/src/local_deep_research/news/database.py
@@ -0,0 +1,84 @@
+"""
+Database initialization for news subscription tables in main ldr.db.
+"""
+
+import os
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+from loguru import logger
+
+from .models import Base
+
+
+def init_news_tables(db_path=None):
+ """
+ Initialize news subscription tables in the main ldr.db database.
+
+ Args:
+ db_path: Path to the database file. If None, uses the main ldr.db
+ """
+ if db_path is None:
+ # Use the main ldr.db database in the root directory
+ db_path = os.path.join(os.path.dirname(__file__), "../../../ldr.db")
+ db_path = os.path.abspath(db_path)
+
+ if not os.path.exists(db_path):
+ logger.error(f"Database not found at {db_path}")
+ return False
+
+ try:
+ # Create engine for the main database
+ engine = create_engine(f"sqlite:///{db_path}", echo=False)
+
+ # Create only the news subscription tables (not research_history, etc.)
+ Base.metadata.create_all(
+ engine,
+ tables=[
+ Base.metadata.tables.get("news_subscriptions"),
+ Base.metadata.tables.get("news_subscription_folders"),
+ Base.metadata.tables.get("news_user_preferences"),
+ Base.metadata.tables.get("news_ratings"),
+ ],
+ )
+
+ logger.info(f"News subscription tables initialized in {db_path}")
+ return True
+
+ except Exception as e:
+ logger.error(f"Failed to initialize news tables: {e}")
+ return False
+
+
+def get_news_session(db_path=None):
+ """
+ Get a database session for the main ldr.db.
+ Tables are created automatically if they don't exist.
+
+ Args:
+ db_path: Path to the database file. If None, uses the main ldr.db
+
+ Returns:
+ SQLAlchemy session
+ """
+ if db_path is None:
+ # Use the main ldr.db database in the root directory
+ db_path = os.path.join(os.path.dirname(__file__), "../../../ldr.db")
+ db_path = os.path.abspath(db_path)
+
+ engine = create_engine(f"sqlite:///{db_path}", echo=False)
+
+ # Create tables if they don't exist
+ Base.metadata.create_all(
+ engine,
+ tables=[
+ Base.metadata.tables.get("news_subscriptions"),
+ Base.metadata.tables.get("news_subscription_folders"),
+ Base.metadata.tables.get("news_user_preferences"),
+ Base.metadata.tables.get("news_ratings"),
+ Base.metadata.tables.get("news_cards"),
+ Base.metadata.tables.get("news_card_versions"),
+ ],
+ )
+
+ Session = sessionmaker(bind=engine)
+ return Session()
diff --git a/src/local_deep_research/news/flask_api.py b/src/local_deep_research/news/flask_api.py
new file mode 100644
index 0000000000..be16c3dd02
--- /dev/null
+++ b/src/local_deep_research/news/flask_api.py
@@ -0,0 +1,804 @@
+"""
+Flask API endpoints for news system.
+Converted from FastAPI to match LDR's Flask architecture.
+"""
+
+from typing import Dict, Any
+from flask import Blueprint, request, jsonify
+from loguru import logger
+
+from . import api
+from .database import get_news_session
+from .folder_manager import FolderManager
+from .models import SubscriptionFolder
+from .constants import DEFAULT_FEED_LIMIT
+
+
+# Create Blueprint - no url_prefix here since parent blueprint already has /news
+news_api_bp = Blueprint("news_api", __name__, url_prefix="/api")
+
+# Components are initialized in api.py
+
+
+def get_user_id():
+ """Get current user ID or anonymous"""
+ # LDR doesn't use flask-login, so we get user_id from request
+ # For GET requests, only check args. For POST/PUT, check JSON body too
+ if request.method == "GET":
+ return request.args.get("user_id", "anonymous")
+ else:
+ # For POST/PUT requests, check JSON body first, then args
+ try:
+ if request.is_json and request.json:
+ return request.json.get(
+ "user_id", request.args.get("user_id", "anonymous")
+ )
+ except Exception:
+ pass
+ return request.args.get("user_id", "anonymous")
+
+
+@news_api_bp.route("/feed", methods=["GET"])
+def get_news_feed() -> Dict[str, Any]:
+ """
+ Get personalized news feed for user.
+
+ Query params:
+ user_id: User identifier (default: anonymous)
+ limit: Maximum number of cards to return (default: 20)
+ use_cache: Whether to use cached news (default: true)
+ strategy: Override default recommendation strategy
+ focus: Optional focus area for news
+ """
+ try:
+ # Get query parameters
+ user_id = request.args.get("user_id", "anonymous")
+ limit = int(request.args.get("limit", DEFAULT_FEED_LIMIT))
+ use_cache = request.args.get("use_cache", "true").lower() == "true"
+ strategy = request.args.get("strategy")
+ focus = request.args.get("focus")
+ subscription_id = request.args.get("subscription_id")
+
+ # Call the direct API function (now synchronous)
+ result = api.get_news_feed(
+ user_id=user_id,
+ limit=limit,
+ use_cache=use_cache,
+ focus=focus,
+ search_strategy=strategy,
+ subscription_id=subscription_id,
+ )
+
+ # Check for errors in result
+ if "error" in result and result.get("news_items") == []:
+ return jsonify(result), 400 if "must be between" in result[
+ "error"
+ ] else 500
+
+ # Debug: Log the result before returning
+ logger.info(
+ f"API returning {len(result.get('news_items', []))} news items"
+ )
+ if result.get("news_items"):
+ logger.info(
+ f"First item ID: {result['news_items'][0].get('id', 'NO_ID')}"
+ )
+
+ return jsonify(result)
+
+ except Exception as e:
+ logger.error(f"Error getting news feed: {e}")
+ return jsonify({"error": str(e), "news_items": []}), 500
+
+
+@news_api_bp.route("/subscribe", methods=["POST"])
+def create_subscription() -> Dict[str, Any]:
+ """
+ Create a new subscription for user.
+
+ JSON body:
+ user_id: User identifier
+ query: Search query or topic
+ subscription_type: "search" or "topic" (default: "search")
+ refresh_hours: Refresh interval in hours (default: 4)
+ """
+ try:
+ data = request.get_json(force=True)
+ except Exception:
+ # Handle invalid JSON
+ return jsonify({"error": "Invalid JSON data"}), 400
+
+ try:
+ if not data:
+ return jsonify({"error": "No JSON data provided"}), 400
+
+ # Extract parameters
+ user_id = data.get("user_id")
+ query = data.get("query")
+ subscription_type = data.get("subscription_type", "search")
+ refresh_hours = data.get("refresh_hours", 4)
+
+ # Validate required fields
+ if not user_id or not query:
+ return jsonify({"error": "user_id and query are required"}), 400
+
+ # Call the direct API function
+ result = api.create_subscription(
+ user_id=user_id,
+ query=query,
+ subscription_type=subscription_type,
+ refresh_hours=refresh_hours,
+ )
+
+ return jsonify(result)
+
+ except ValueError as e:
+ return jsonify({"error": str(e)}), 400
+ except Exception as e:
+ logger.error(f"Error creating subscription: {e}")
+ return jsonify({"error": str(e)}), 500
+
+
+@news_api_bp.route("/vote", methods=["POST"])
+def vote_on_news() -> Dict[str, Any]:
+ """
+ Submit vote on a news item.
+
+ JSON body:
+ user_id: User identifier
+ card_id: ID of the news card
+ vote: "up" or "down"
+ """
+ try:
+ data = request.get_json()
+ if not data:
+ return jsonify({"error": "No JSON data provided"}), 400
+
+ user_id = data.get("user_id")
+ card_id = data.get("card_id")
+ vote = data.get("vote")
+
+ # Validate
+ if not all([user_id, card_id, vote]):
+ return jsonify(
+ {"error": "user_id, card_id, and vote are required"}
+ ), 400
+
+ # Call the direct API function
+ result = api.submit_feedback(
+ card_id=card_id, user_id=user_id, vote=vote
+ )
+
+ return jsonify(result)
+
+ except ValueError as e:
+ error_msg = str(e)
+ if "not found" in error_msg.lower():
+ return jsonify({"error": error_msg}), 404
+ else:
+ return jsonify({"error": error_msg}), 400
+ except Exception as e:
+ logger.error(f"Error submitting vote: {e}")
+ return jsonify({"error": str(e)}), 500
+
+
+@news_api_bp.route("/feedback/<card_id>", methods=["POST"])
+def submit_feedback(card_id: str) -> Dict[str, Any]:
+ """
+ Submit feedback (vote) for a news card.
+
+ JSON body:
+ user_id: User identifier
+ vote: "up" or "down"
+ """
+ try:
+ data = request.get_json()
+ if not data:
+ return jsonify({"error": "No JSON data provided"}), 400
+
+ user_id = data.get("user_id")
+ vote = data.get("vote")
+
+ # Validate
+ if not user_id or not vote:
+ return jsonify({"error": "user_id and vote are required"}), 400
+
+ # Call the direct API function
+ result = api.submit_feedback(
+ card_id=card_id, user_id=user_id, vote=vote
+ )
+
+ return jsonify(result)
+
+ except ValueError as e:
+ error_msg = str(e)
+ if "not found" in error_msg.lower():
+ return jsonify({"error": error_msg}), 404
+ elif "must be" in error_msg.lower():
+ return jsonify({"error": error_msg}), 400
+ else:
+ return jsonify({"error": error_msg}), 400
+ except Exception as e:
+ logger.error(f"Error submitting feedback: {e}")
+ return jsonify({"error": str(e)}), 500
+
+
+@news_api_bp.route("/research/<card_id>", methods=["POST"])
+def research_news_item(card_id: str) -> Dict[str, Any]:
+ """
+ Perform deeper research on a news item.
+
+ JSON body:
+ depth: "quick", "detailed", or "report" (default: "quick")
+ """
+ try:
+ data = request.get_json() or {}
+ depth = data.get("depth", "quick")
+
+ # Call the API function which handles the research
+ result = api.research_news_item(card_id, depth)
+
+ return jsonify(result)
+
+ except Exception as e:
+ logger.error(f"Error researching news item: {e}")
+ return jsonify({"error": str(e)}), 500
+
+
+@news_api_bp.route("/subscriptions/<user_id>", methods=["GET"])
+def get_user_subscriptions(user_id: str) -> Dict[str, Any]:
+ """Get all subscriptions for a user."""
+ try:
+ # Use the API function
+ result = api.get_subscriptions(user_id)
+ return jsonify(result)
+
+ except Exception as e:
+ logger.error(f"Error getting subscriptions: {e}")
+ return jsonify({"error": str(e)}), 500
+
+
+@news_api_bp.route("/subscriptions/<subscription_id>", methods=["DELETE"])
+def delete_subscription(subscription_id: str) -> Dict[str, Any]:
+ """Delete a subscription."""
+ try:
+ # Call the direct API function
+ success = api.delete_subscription(subscription_id)
+
+ if success:
+ return jsonify(
+ {
+ "status": "success",
+ "message": f"Subscription {subscription_id} deleted",
+ }
+ )
+ else:
+ return jsonify({"error": "Subscription not found"}), 404
+
+ except Exception as e:
+ logger.error(f"Error deleting subscription: {e}")
+ return jsonify({"error": str(e)}), 500
+
+
+@news_api_bp.route("/subscriptions/<subscription_id>/run", methods=["POST"])
+def run_subscription_now(subscription_id: str) -> Dict[str, Any]:
+ """Manually trigger a subscription to run now."""
+ try:
+ # Get the subscription from the API
+ subscription_data = api.get_subscriptions("anonymous")
+
+ # Find the specific subscription
+ subscription = None
+ for sub in subscription_data.get("subscriptions", []):
+ if sub["id"] == subscription_id:
+ subscription = sub
+ break
+
+ if not subscription:
+ return jsonify({"error": "Subscription not found"}), 404
+
+ # Use the same simple approach as the news page
+ from ..utilities.db_utils import get_db_setting
+ from datetime import datetime
+
+ # Get the query and update dates
+ query = subscription["query"]
+
+ # Update any date placeholders with current date
+ current_date = datetime.now().strftime("%Y-%m-%d")
+
+ # Replace YYYY-MM-DD placeholder ONLY (not all dates)
+ query = query.replace("YYYY-MM-DD", current_date)
+
+ # Build request data similar to news page
+ request_data = {
+ "query": query,
+ "mode": "quick",
+ "model_provider": get_db_setting("llm.provider", "OLLAMA"),
+ "model": get_db_setting("llm.model", "llama3"),
+ "strategy": "source-based",
+ "metadata": {
+ "is_news_search": True,
+ "search_type": "news_analysis",
+ "display_in": "news_feed",
+ "subscription_id": subscription_id,
+ "triggered_by": "manual",
+ "original_query": subscription[
+ "query"
+ ], # Store original query with placeholder
+ "processed_query": query, # Store processed query with replaced date
+ "news_date": current_date, # Store the actual date used
+ },
+ }
+
+ # Call the main research API endpoint (use the one from research blueprint)
+ import requests
+ from ...utilities.db_utils import get_db_setting
+
+ # Get configured host and port
+ host = get_db_setting("web.host", "127.0.0.1")
+ port = get_db_setting("web.port", 5000)
+
+ response = requests.post(
+ f"http://{host}:{port}/research/api/start_research",
+ json=request_data,
+ headers={"Content-Type": "application/json"},
+ )
+
+ if response.ok:
+ data = response.json()
+ if data.get("status") == "success":
+ return jsonify(
+ {
+ "status": "success",
+ "message": "Research started",
+ "research_id": data.get("research_id"),
+ "url": f"/progress/{data.get('research_id')}",
+ }
+ )
+ else:
+ return jsonify(
+ {"error": data.get("message", "Failed to start research")}
+ ), 500
+ else:
+ return jsonify(
+ {"error": f"Failed to start research: {response.status_code}"}
+ ), response.status_code
+
+ except Exception as e:
+ logger.error(f"Error running subscription: {e}", exc_info=True)
+ return jsonify({"error": str(e)}), 500
+
+
+@news_api_bp.route("/subscriptions/<subscription_id>/history", methods=["GET"])
+def get_subscription_history(subscription_id: str) -> Dict[str, Any]:
+ """Get research history for a subscription."""
+ try:
+ limit = int(request.args.get("limit", DEFAULT_FEED_LIMIT))
+ result = api.get_subscription_history(subscription_id, limit)
+ return jsonify(result)
+ except Exception as e:
+ logger.error(f"Error getting subscription history: {e}")
+ return jsonify({"error": str(e)}), 500
+
+
+@news_api_bp.route("/preferences", methods=["POST"])
+def save_preferences() -> Dict[str, Any]:
+ """Save user preferences for news."""
+ try:
+ data = request.get_json()
+ if not data:
+ return jsonify({"error": "No JSON data provided"}), 400
+
+ user_id = data.get("user_id")
+ preferences = data.get("preferences", {})
+
+ if not user_id:
+ return jsonify({"error": "user_id is required"}), 400
+
+ # Call the direct API function
+ result = api.save_news_preferences(user_id, preferences)
+
+ return jsonify(result)
+
+ except Exception as e:
+ logger.error(f"Error saving preferences: {e}")
+ return jsonify({"error": str(e)}), 500
+
+
+@news_api_bp.route("/categories", methods=["GET"])
+def get_categories() -> Dict[str, Any]:
+ """Get news category distribution."""
+ try:
+ # Call the direct API function
+ result = api.get_news_categories()
+
+ return jsonify(result)
+
+ except Exception as e:
+ logger.error(f"Error getting categories: {e}")
+ return jsonify({"error": str(e)}), 500
+
+
+@news_api_bp.route("/scheduler/status", methods=["GET"])
+def get_scheduler_status() -> Dict[str, Any]:
+ """Get background scheduler status."""
+ try:
+ from flask import current_app
+ from .subscription_manager.scheduler import SCHEDULER_AVAILABLE
+ from ..web.models.database import get_db_connection
+
+ # Check if scheduler is available and get status
+ result = {
+ "scheduler_available": SCHEDULER_AVAILABLE,
+ "is_running": False,
+ "next_check": None,
+ "jobs_count": 0,
+ "due_subscriptions": 0,
+ "upcoming_refreshes": [],
+ }
+
+ if (
+ SCHEDULER_AVAILABLE
+ and hasattr(current_app, "news_scheduler")
+ and current_app.news_scheduler
+ ):
+ scheduler = current_app.news_scheduler
+ result["is_running"] = scheduler.is_running
+
+ if scheduler.is_running and scheduler.scheduler:
+ jobs = scheduler.scheduler.get_jobs()
+ result["jobs_count"] = len(jobs)
+
+ # Get next scheduled run time
+ for job in jobs:
+ if job.id == "subscription_checker":
+ result["next_check"] = (
+ job.next_run_time.isoformat()
+ if job.next_run_time
+ else None
+ )
+ break
+
+ # Get subscription statistics
+ try:
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ # Count due subscriptions
+ cursor.execute("""
+ SELECT COUNT(*)
+ FROM news_subscriptions
+ WHERE status = 'active'
+ AND (next_refresh IS NULL OR next_refresh <= datetime('now'))
+ """)
+ result["due_subscriptions"] = cursor.fetchone()[0]
+
+ # Get upcoming refreshes
+ cursor.execute("""
+ SELECT id, query_or_topic, subscription_type, next_refresh
+ FROM news_subscriptions
+ WHERE status = 'active'
+ ORDER BY COALESCE(next_refresh, datetime('now')) ASC
+ LIMIT 5
+ """)
+ result["upcoming_refreshes"] = [
+ {
+ "id": row[0],
+ "name": row[1], # Using query_or_topic as name
+ "type": row[2],
+ "next_refresh": row[3],
+ }
+ for row in cursor.fetchall()
+ ]
+
+ conn.close()
+ except Exception as e:
+ logger.warning(f"Could not get subscription details: {e}")
+
+ return jsonify(result)
+
+ except Exception as e:
+ logger.error(f"Error getting scheduler status: {e}")
+ return jsonify({"error": str(e)}), 500
+
+
+@news_api_bp.route("/scheduler/start", methods=["POST"])
+def start_scheduler() -> Dict[str, Any]:
+ """Start the subscription scheduler."""
+ try:
+ from flask import current_app
+ from .subscription_manager.scheduler import (
+ SubscriptionScheduler,
+ SCHEDULER_AVAILABLE,
+ )
+
+ if not SCHEDULER_AVAILABLE:
+ return jsonify({"error": "APScheduler is not installed"}), 503
+
+ # Check if scheduler exists
+ if (
+ not hasattr(current_app, "news_scheduler")
+ or not current_app.news_scheduler
+ ):
+ # Create new scheduler instance
+ scheduler = SubscriptionScheduler()
+ current_app.news_scheduler = scheduler
+ scheduler.start()
+ logger.info("News scheduler started via API")
+ else:
+ scheduler = current_app.news_scheduler
+ if not scheduler.is_running:
+ scheduler.start()
+ logger.info("News scheduler restarted via API")
+ else:
+ return jsonify({"message": "Scheduler is already running"}), 200
+
+ return jsonify({"status": "success", "message": "Scheduler started"})
+
+ except Exception as e:
+ logger.error(f"Error starting scheduler: {e}")
+ return jsonify({"error": str(e)}), 500
+
+
+@news_api_bp.route("/scheduler/stop", methods=["POST"])
+def stop_scheduler() -> Dict[str, Any]:
+ """Stop the subscription scheduler."""
+ try:
+ from flask import current_app
+
+ if (
+ hasattr(current_app, "news_scheduler")
+ and current_app.news_scheduler
+ ):
+ scheduler = current_app.news_scheduler
+ if scheduler.is_running:
+ scheduler.stop()
+ logger.info("News scheduler stopped via API")
+ return jsonify(
+ {"status": "success", "message": "Scheduler stopped"}
+ )
+ else:
+ return jsonify({"message": "Scheduler is not running"}), 200
+ else:
+ return jsonify({"message": "No scheduler instance found"}), 404
+
+ except Exception as e:
+ logger.error(f"Error stopping scheduler: {e}")
+ return jsonify({"error": str(e)}), 500
+
+
+@news_api_bp.route("/scheduler/check-now", methods=["POST"])
+def check_subscriptions_now() -> Dict[str, Any]:
+ """Manually trigger subscription checking."""
+ try:
+ from flask import current_app
+
+ if (
+ not hasattr(current_app, "news_scheduler")
+ or not current_app.news_scheduler
+ ):
+ return jsonify({"error": "Scheduler not initialized"}), 503
+
+ scheduler = current_app.news_scheduler
+ if not scheduler.is_running:
+ return jsonify({"error": "Scheduler is not running"}), 503
+
+ # Run the check subscriptions task immediately
+ scheduler_instance = current_app.news_scheduler
+
+ # Get count of due subscriptions
+ from ..web.models.database import get_db_connection
+
+ conn = get_db_connection()
+ cursor = conn.cursor()
+ cursor.execute("""
+ SELECT COUNT(*)
+ FROM news_subscriptions
+ WHERE status = 'active'
+ AND (next_refresh IS NULL OR next_refresh <= datetime('now'))
+ """)
+ count = cursor.fetchone()[0]
+ conn.close()
+
+ # Trigger the check asynchronously
+ import threading
+
+ check_thread = threading.Thread(
+ target=scheduler_instance._check_subscriptions
+ )
+ check_thread.daemon = True
+ check_thread.start()
+
+ return jsonify(
+ {
+ "status": "success",
+ "message": f"Checking {count} due subscriptions",
+ "count": count,
+ }
+ )
+
+ except Exception as e:
+ logger.error(f"Error checking subscriptions: {e}")
+ return jsonify({"error": str(e)}), 500
+
+
+# Folder and subscription management routes
+@news_api_bp.route("/subscription/folders", methods=["GET"])
+def get_folders():
+ """Get all folders for the current user"""
+ try:
+ user_id = get_user_id()
+
+ with get_news_session() as session:
+ manager = FolderManager(session)
+ folders = manager.get_user_folders(user_id)
+
+ return jsonify([folder.to_dict() for folder in folders])
+
+ except Exception as e:
+ logger.error(f"Error getting folders: {e}")
+ return jsonify({"error": str(e)}), 500
+
+
+@news_api_bp.route("/subscription/folders", methods=["POST"])
+def create_folder():
+ """Create a new folder"""
+ try:
+ user_id = get_user_id()
+ data = request.json
+
+ if not data.get("name"):
+ return jsonify({"error": "Folder name is required"}), 400
+
+ with get_news_session() as session:
+ manager = FolderManager(session)
+
+ # Check if folder already exists
+ existing = (
+ session.query(SubscriptionFolder)
+ .filter_by(user_id=user_id, name=data["name"])
+ .first()
+ )
+ if existing:
+ return jsonify({"error": "Folder already exists"}), 409
+
+ folder = manager.create_folder(
+ user_id=user_id,
+ name=data["name"],
+ description=data.get("description"),
+ )
+
+ return jsonify(folder.to_dict()), 201
+
+ except Exception as e:
+ logger.error(f"Error creating folder: {e}")
+ return jsonify({"error": str(e)}), 500
+
+
+@news_api_bp.route("/subscription/folders/<folder_id>", methods=["PUT"])
+def update_folder(folder_id):
+ """Update a folder"""
+ try:
+ data = request.json
+
+ with get_news_session() as session:
+ manager = FolderManager(session)
+ folder = manager.update_folder(folder_id, **data)
+
+ if not folder:
+ return jsonify({"error": "Folder not found"}), 404
+
+ return jsonify(folder.to_dict())
+
+ except Exception as e:
+ logger.error(f"Error updating folder: {e}")
+ return jsonify({"error": str(e)}), 500
+
+
+@news_api_bp.route("/subscription/folders/<folder_id>", methods=["DELETE"])
+def delete_folder(folder_id):
+ """Delete a folder"""
+ try:
+ move_to = request.args.get("move_to")
+
+ with get_news_session() as session:
+ manager = FolderManager(session)
+ success = manager.delete_folder(folder_id, move_to)
+
+ if not success:
+ return jsonify({"error": "Folder not found"}), 404
+
+ return jsonify({"status": "deleted"}), 200
+
+ except Exception as e:
+ logger.error(f"Error deleting folder: {e}")
+ return jsonify({"error": str(e)}), 500
+
+
+@news_api_bp.route("/subscription/subscriptions/organized", methods=["GET"])
+def get_subscriptions_organized():
+ """Get subscriptions organized by folder"""
+ try:
+ user_id = get_user_id()
+
+ with get_news_session() as session:
+ manager = FolderManager(session)
+ organized = manager.get_subscriptions_by_folder(user_id)
+
+ # Convert to JSON-friendly format
+ result = {}
+ for folder, subs in organized.items():
+ result[folder] = [sub.to_dict() for sub in subs]
+
+ return jsonify(result)
+
+ except Exception as e:
+ logger.error(f"Error getting organized subscriptions: {e}")
+ return jsonify({"error": str(e)}), 500
+
+
+@news_api_bp.route(
+ "/subscription/subscriptions/<subscription_id>", methods=["PUT"]
+)
+def update_subscription_folder(subscription_id):
+ """Update a subscription (mainly for folder assignment)"""
+ try:
+ data = request.json
+
+ with get_news_session() as session:
+ manager = FolderManager(session)
+ sub = manager.update_subscription(subscription_id, **data)
+
+ if not sub:
+ return jsonify({"error": "Subscription not found"}), 404
+
+ return jsonify(sub.to_dict())
+
+ except Exception as e:
+ logger.error(f"Error updating subscription: {e}")
+ return jsonify({"error": str(e)}), 500
+
+
+@news_api_bp.route("/subscription/stats", methods=["GET"])
+def get_subscription_stats():
+ """Get subscription statistics"""
+ try:
+ user_id = get_user_id()
+
+ with get_news_session() as session:
+ manager = FolderManager(session)
+ stats = manager.get_subscription_stats(user_id)
+
+ return jsonify(stats)
+
+ except Exception as e:
+ logger.error(f"Error getting stats: {e}")
+ return jsonify({"error": str(e)}), 500
+
+
+# Error handlers
+@news_api_bp.errorhandler(400)
+def bad_request(e):
+ return jsonify({"error": str(e)}), 400
+
+
+@news_api_bp.errorhandler(404)
+def not_found(e):
+ return jsonify({"error": str(e)}), 404
+
+
+@news_api_bp.errorhandler(500)
+def internal_error(e):
+ return jsonify({"error": "Internal server error"}), 500
+
+
+@news_api_bp.route("/debug", methods=["GET"])
+def debug_database():
+ """Debug endpoint to check database content."""
+ try:
+ result = api.debug_research_items()
+ return jsonify(result)
+ except Exception as e:
+ logger.error(f"Error in debug endpoint: {e}")
+ return jsonify({"error": str(e)}), 500
diff --git a/src/local_deep_research/news/folder_manager.py b/src/local_deep_research/news/folder_manager.py
new file mode 100644
index 0000000000..141e3578b8
--- /dev/null
+++ b/src/local_deep_research/news/folder_manager.py
@@ -0,0 +1,201 @@
+"""
+Simple folder manager for subscription organization.
+Handles folder CRUD operations for the API routes.
+"""
+
+from typing import List, Optional, Dict, Any
+from datetime import datetime, timezone
+from sqlalchemy.orm import Session
+from .models import SubscriptionFolder, BaseSubscription
+
+
+class FolderManager:
+ """Manages subscription folders and organization."""
+
+ def __init__(self, session: Session):
+ self.session = session
+
+ def get_user_folders(self, user_id: str) -> List[SubscriptionFolder]:
+ """Get all folders for a user."""
+ return (
+ self.session.query(SubscriptionFolder)
+ .filter_by(user_id=user_id)
+ .order_by(SubscriptionFolder.name)
+ .all()
+ )
+
+ def create_folder(
+ self, user_id: str, name: str, description: Optional[str] = None
+ ) -> SubscriptionFolder:
+ """Create a new folder."""
+ import uuid
+
+ folder = SubscriptionFolder(
+ id=str(uuid.uuid4()),
+ user_id=user_id,
+ name=name,
+ description=description,
+ )
+ self.session.add(folder)
+ self.session.commit()
+ return folder
+
+ def update_folder(
+ self, folder_id: int, **kwargs
+ ) -> Optional[SubscriptionFolder]:
+ """Update a folder."""
+ folder = self.session.query(SubscriptionFolder).get(folder_id)
+ if not folder:
+ return None
+
+ for key, value in kwargs.items():
+ if hasattr(folder, key) and key not in [
+ "id",
+ "user_id",
+ "created_at",
+ ]:
+ setattr(folder, key, value)
+
+ folder.updated_at = datetime.now(timezone.utc)
+ self.session.commit()
+ return folder
+
+ def delete_folder(
+ self, folder_id: int, move_to: Optional[str] = None
+ ) -> bool:
+ """Delete a folder, optionally moving subscriptions to another folder."""
+ folder = self.session.query(SubscriptionFolder).get(folder_id)
+ if not folder:
+ return False
+
+ # Move subscriptions if specified
+ if move_to:
+ self.session.query(BaseSubscription).filter_by(
+ folder=folder.name
+ ).update({"folder": move_to})
+ else:
+ # Set to None if no target folder
+ self.session.query(BaseSubscription).filter_by(
+ folder=folder.name
+ ).update({"folder": None})
+
+ self.session.delete(folder)
+ self.session.commit()
+ return True
+
+ def get_subscriptions_by_folder(self, user_id: str) -> Dict[str, Any]:
+ """Get subscriptions organized by folder."""
+ folders = self.get_user_folders(user_id)
+
+ result = {"folders": [], "uncategorized": []}
+
+ # Get subscriptions for each folder
+ for folder in folders:
+ subs = (
+ self.session.query(BaseSubscription)
+ .filter_by(user_id=user_id, folder=folder.name, status="active")
+ .all()
+ )
+
+ result["folders"].append(
+ {
+ "folder": folder.to_dict(),
+ "subscriptions": [self._sub_to_dict(s) for s in subs],
+ }
+ )
+
+ # Get uncategorized subscriptions
+ uncategorized = (
+ self.session.query(BaseSubscription)
+ .filter_by(user_id=user_id, folder=None, status="active")
+ .all()
+ )
+
+ result["uncategorized"] = [self._sub_to_dict(s) for s in uncategorized]
+
+ return result
+
+ def update_subscription(
+ self, subscription_id: str, **kwargs
+ ) -> Optional[BaseSubscription]:
+ """Update a subscription."""
+ sub = (
+ self.session.query(BaseSubscription)
+ .filter_by(id=subscription_id)
+ .first()
+ )
+ if not sub:
+ return None
+
+ for key, value in kwargs.items():
+ if hasattr(sub, key) and key not in ["id", "user_id", "created_at"]:
+ setattr(sub, key, value)
+
+ sub.updated_at = datetime.now(timezone.utc)
+ self.session.commit()
+ return sub
+
+ def delete_subscription(self, subscription_id: str) -> bool:
+ """Delete a subscription."""
+ sub = (
+ self.session.query(BaseSubscription)
+ .filter_by(id=subscription_id)
+ .first()
+ )
+ if not sub:
+ return False
+
+ self.session.delete(sub)
+ self.session.commit()
+ return True
+
+ def 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()
+ )
+
+ active = (
+ self.session.query(BaseSubscription)
+ .filter_by(user_id=user_id, status="active")
+ .count()
+ )
+
+ by_type = {}
+ for sub_type in ["search", "topic"]:
+ count = (
+ self.session.query(BaseSubscription)
+ .filter_by(
+ user_id=user_id, subscription_type=sub_type, status="active"
+ )
+ .count()
+ )
+ by_type[sub_type] = count
+
+ return {
+ "total": total,
+ "active": active,
+ "by_type": by_type,
+ "folders": len(self.get_user_folders(user_id)),
+ }
+
+ def _sub_to_dict(self, sub: BaseSubscription) -> Dict[str, Any]:
+ """Convert subscription to dictionary."""
+ return {
+ "id": sub.id,
+ "type": sub.subscription_type,
+ "query_or_topic": sub.query_or_topic,
+ "created_at": sub.created_at.isoformat()
+ if sub.created_at
+ else None,
+ "last_refresh": sub.last_refresh.isoformat()
+ if sub.last_refresh
+ else None,
+ "next_refresh": sub.next_refresh.isoformat()
+ if sub.next_refresh
+ else None,
+ "refresh_interval_hours": sub.refresh_interval_hours,
+ "status": sub.status,
+ }
diff --git a/src/local_deep_research/news/init_tables.py b/src/local_deep_research/news/init_tables.py
new file mode 100755
index 0000000000..f1e285f1d7
--- /dev/null
+++ b/src/local_deep_research/news/init_tables.py
@@ -0,0 +1,178 @@
+#!/usr/bin/env python3
+"""
+Standalone script to initialize news database tables.
+Can be run directly to ensure all news tables are created in ldr.db.
+"""
+
+import sys
+from pathlib import Path
+from sqlalchemy import create_engine, inspect
+from loguru import logger
+
+# Add parent directory to path for imports
+sys.path.insert(0, str(Path(__file__).parent.parent.parent))
+
+from local_deep_research.news.models import (
+ Base,
+ BaseSubscription,
+ SubscriptionFolder,
+ UserPreference,
+ Rating,
+ NewsCard,
+ CardVersion,
+)
+
+
+def init_news_tables(db_path=None):
+ """
+ Initialize all news tables in the database.
+
+ Args:
+ db_path: Path to the database file. If None, uses the default ldr.db location.
+
+ Returns:
+ bool: True if successful, False otherwise
+ """
+ if db_path is None:
+ # Use the default ldr.db location in data directory
+ data_dir = Path(__file__).parent.parent.parent.parent / "data"
+ data_dir.mkdir(exist_ok=True)
+ db_path = data_dir / "ldr.db"
+
+ db_path = Path(db_path).absolute()
+
+ if not db_path.exists():
+ logger.error(f"Database not found at {db_path}")
+ logger.info(
+ "Please ensure the main application has been run at least once to create the database."
+ )
+ return False
+
+ try:
+ # Create engine
+ engine = create_engine(f"sqlite:///{db_path}", echo=False)
+ inspector = inspect(engine)
+
+ logger.info(f"Initializing news tables in {db_path}")
+
+ # List of tables to create
+ tables_to_create = [
+ ("news_subscriptions", BaseSubscription.__table__),
+ ("news_subscription_folders", SubscriptionFolder.__table__),
+ ("news_user_preferences", UserPreference.__table__),
+ ("news_ratings", Rating.__table__),
+ ("news_cards", NewsCard.__table__),
+ ("news_card_versions", CardVersion.__table__),
+ ]
+
+ created_count = 0
+ for table_name, table_obj in tables_to_create:
+ if not inspector.has_table(table_name):
+ logger.info(f"Creating table: {table_name}")
+ Base.metadata.create_all(engine, tables=[table_obj])
+ created_count += 1
+ else:
+ logger.debug(f"Table already exists: {table_name}")
+
+ if created_count > 0:
+ logger.success(f"Successfully created {created_count} news tables")
+ else:
+ logger.info("All news tables already exist")
+
+ # Verify all tables exist
+ existing_tables = inspector.get_table_names()
+ news_tables = [name for name, _ in tables_to_create]
+ missing_tables = [t for t in news_tables if t not in existing_tables]
+
+ if missing_tables:
+ logger.error(f"Failed to create tables: {missing_tables}")
+ return False
+
+ return True
+
+ except Exception as e:
+ logger.error(f"Failed to initialize news tables: {e}")
+ import traceback
+
+ traceback.print_exc()
+ return False
+
+
+def verify_news_tables(db_path=None):
+ """
+ Verify that all news tables exist and show their structure.
+
+ Args:
+ db_path: Path to the database file. If None, uses the default ldr.db location.
+ """
+ if db_path is None:
+ data_dir = Path(__file__).parent.parent.parent.parent / "data"
+ db_path = data_dir / "ldr.db"
+
+ db_path = Path(db_path).absolute()
+
+ if not db_path.exists():
+ logger.error(f"Database not found at {db_path}")
+ return
+
+ try:
+ engine = create_engine(f"sqlite:///{db_path}", echo=False)
+ inspector = inspect(engine)
+
+ logger.info(f"Verifying news tables in {db_path}")
+
+ news_tables = [
+ "news_subscriptions",
+ "news_subscription_folders",
+ "news_user_preferences",
+ "news_ratings",
+ "news_cards",
+ "news_card_versions",
+ ]
+
+ for table_name in news_tables:
+ if inspector.has_table(table_name):
+ logger.success(f"✓ Table exists: {table_name}")
+ # Show columns
+ columns = inspector.get_columns(table_name)
+ for col in columns:
+ logger.debug(f" - {col['name']}: {col['type']}")
+ else:
+ logger.error(f"✗ Table missing: {table_name}")
+
+ except Exception as e:
+ logger.error(f"Failed to verify news tables: {e}")
+ import traceback
+
+ traceback.print_exc()
+
+
+if __name__ == "__main__":
+ import argparse
+
+ parser = argparse.ArgumentParser(
+ description="Initialize news database tables"
+ )
+ parser.add_argument(
+ "--db-path",
+ type=str,
+ help="Path to the database file (default: data/ldr.db)",
+ )
+ parser.add_argument(
+ "--verify",
+ action="store_true",
+ help="Only verify tables without creating them",
+ )
+
+ args = parser.parse_args()
+
+ if args.verify:
+ verify_news_tables(args.db_path)
+ else:
+ success = init_news_tables(args.db_path)
+ if success:
+ logger.info("News tables initialization complete!")
+ verify_news_tables(args.db_path)
+ else:
+ logger.error("News tables initialization failed!")
+ sys.exit(1)
diff --git a/src/local_deep_research/news/models.py b/src/local_deep_research/news/models.py
new file mode 100644
index 0000000000..6822291ab0
--- /dev/null
+++ b/src/local_deep_research/news/models.py
@@ -0,0 +1,305 @@
+"""
+Database models for news subscriptions and related functionality.
+These tables are created in the main ldr.db database.
+"""
+
+from sqlalchemy import (
+ Column,
+ Integer,
+ String,
+ DateTime,
+ JSON,
+ Text,
+ Boolean,
+ ForeignKey,
+ Enum,
+)
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import relationship
+from datetime import datetime, timezone
+import enum
+
+Base = declarative_base()
+
+
+class CardType(enum.Enum):
+ """Types of cards in the system"""
+
+ NEWS = "news"
+ RESEARCH = "research"
+ UPDATE = "update"
+ OVERVIEW = "overview"
+
+
+class RatingType(enum.Enum):
+ """Types of ratings"""
+
+ RELEVANCE = "relevance" # Thumbs up/down
+ QUALITY = "quality" # 1-5 stars
+
+
+class SubscriptionType(enum.Enum):
+ """Types of subscriptions"""
+
+ SEARCH = "search"
+ TOPIC = "topic"
+
+
+class SubscriptionStatus(enum.Enum):
+ """Status of subscriptions"""
+
+ ACTIVE = "active"
+ PAUSED = "paused"
+ EXPIRED = "expired"
+ ERROR = "error"
+
+
+class BaseSubscription(Base):
+ """Base subscription model for search and topic subscriptions"""
+
+ __tablename__ = "news_subscriptions"
+ __table_args__ = {"extend_existing": True} # Allow redefinition
+
+ id = Column(String(50), primary_key=True)
+ user_id = Column(String(50), nullable=False)
+
+ # Subscription details
+ name = Column(String(255)) # Optional friendly name
+ subscription_type = Column(
+ String(20), nullable=False
+ ) # 'search' or 'topic'
+ query_or_topic = Column(Text, nullable=False)
+ refresh_interval_hours = Column(Integer, default=24)
+ refresh_hours = Column(Integer, default=24) # Alias for compatibility
+ frequency = Column(
+ String(50), default="daily"
+ ) # daily, weekly, hourly, etc.
+
+ # Timing
+ created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
+ updated_at = Column(
+ DateTime,
+ default=lambda: datetime.now(timezone.utc),
+ onupdate=lambda: datetime.now(timezone.utc),
+ )
+ last_refresh = Column(DateTime)
+ next_refresh = Column(DateTime)
+ expires_at = Column(DateTime) # Optional expiration
+
+ # Source tracking
+ source_type = Column(String(50)) # 'manual', 'research', 'news_topic'
+ source_id = Column(String(100)) # ID of source (research_id, news_id)
+ created_from = Column(Text) # Description of source
+
+ # Organization
+ folder = Column(String(100)) # Folder name
+ folder_id = Column(String(36)) # Folder ID
+ notes = Column(Text) # User notes
+
+ # Status and stats
+ status = Column(
+ String(20), default="active"
+ ) # active, paused, expired, error
+ is_active = Column(Boolean, default=True)
+ refresh_count = Column(Integer, default=0)
+ total_runs = Column(Integer, default=0) # Alias for refresh_count
+ results_count = Column(Integer, default=0)
+ last_error = Column(Text)
+ error_count = Column(Integer, default=0)
+
+ def to_dict(self):
+ """Convert subscription to dictionary"""
+ return {
+ "id": self.id,
+ "user_id": self.user_id,
+ "name": self.name,
+ "subscription_type": self.subscription_type,
+ "query_or_topic": self.query_or_topic,
+ "query": self.query_or_topic, # Alias for compatibility
+ "refresh_interval_hours": self.refresh_interval_hours,
+ "refresh_hours": self.refresh_hours or self.refresh_interval_hours,
+ "frequency": self.frequency,
+ "created_at": self.created_at.isoformat()
+ if self.created_at
+ else None,
+ "updated_at": self.updated_at.isoformat()
+ if self.updated_at
+ else None,
+ "last_refresh": self.last_refresh.isoformat()
+ if self.last_refresh
+ else None,
+ "last_refreshed": self.last_refresh.isoformat()
+ if self.last_refresh
+ else None, # Alias
+ "next_refresh": self.next_refresh.isoformat()
+ if self.next_refresh
+ else None,
+ "expires_at": self.expires_at.isoformat()
+ if self.expires_at
+ else None,
+ "source_type": self.source_type,
+ "source_id": self.source_id,
+ "created_from": self.created_from,
+ "folder": self.folder,
+ "folder_id": self.folder_id,
+ "notes": self.notes,
+ "status": self.status,
+ "is_active": self.is_active,
+ "refresh_count": self.refresh_count,
+ "total_runs": self.total_runs or self.refresh_count,
+ "results_count": self.results_count,
+ "last_error": self.last_error,
+ "error_count": self.error_count,
+ }
+
+
+class SubscriptionFolder(Base):
+ """Folders for organizing subscriptions"""
+
+ __tablename__ = "news_subscription_folders"
+ __table_args__ = {"extend_existing": True}
+
+ id = Column(String(50), primary_key=True)
+ user_id = Column(String(50), nullable=False)
+ name = Column(String(100), nullable=False)
+ description = Column(Text)
+ color = Column(String(7)) # Hex color
+ icon = Column(String(50)) # Icon name
+ item_count = Column(Integer, default=0)
+ created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
+ updated_at = Column(
+ DateTime,
+ default=lambda: datetime.now(timezone.utc),
+ onupdate=lambda: datetime.now(timezone.utc),
+ )
+
+ def to_dict(self):
+ """Convert folder to dictionary"""
+ return {
+ "id": self.id,
+ "name": self.name,
+ "description": self.description,
+ "color": self.color,
+ "icon": self.icon,
+ "item_count": self.item_count,
+ "created_at": self.created_at.isoformat()
+ if self.created_at
+ else None,
+ "updated_at": self.updated_at.isoformat()
+ if self.updated_at
+ else None,
+ }
+
+
+class UserPreference(Base):
+ """User preferences for news personalization"""
+
+ __tablename__ = "news_user_preferences"
+ __table_args__ = {"extend_existing": True}
+
+ id = Column(Integer, primary_key=True)
+ user_id = Column(String(50), unique=True, nullable=False)
+
+ # Preferences
+ interests = Column(JSON) # List of interest keywords
+ preferred_categories = Column(JSON) # List of preferred news categories
+ disliked_categories = Column(JSON) # List of disliked categories
+
+ # Settings
+ refresh_interval_hours = Column(Integer, default=24)
+ max_items_per_refresh = Column(Integer, default=20)
+
+ # Personalization data
+ preference_embedding = Column(JSON) # User preference vector
+ last_updated = Column(
+ DateTime,
+ default=lambda: datetime.now(timezone.utc),
+ onupdate=lambda: datetime.now(timezone.utc),
+ )
+
+
+class Rating(Base):
+ """User ratings/feedback on news items"""
+
+ __tablename__ = "news_ratings"
+ __table_args__ = {"extend_existing": True}
+
+ id = Column(Integer, primary_key=True)
+ user_id = Column(String(50), nullable=False)
+ item_id = Column(
+ String(100), nullable=False
+ ) # Can be research_id or card_id
+ item_type = Column(String(20), nullable=False) # 'research', 'card'
+
+ # Ratings
+ relevance_vote = Column(String(10)) # 'up', 'down'
+ quality_rating = Column(Integer) # 1-5 stars
+
+ # Metadata
+ created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
+ updated_at = Column(
+ DateTime,
+ default=lambda: datetime.now(timezone.utc),
+ onupdate=lambda: datetime.now(timezone.utc),
+ )
+
+
+class NewsCard(Base):
+ """News card model for unified card system"""
+
+ __tablename__ = "news_cards"
+ __table_args__ = {"extend_existing": True}
+
+ id = Column(String(50), primary_key=True)
+ card_type = Column(Enum(CardType), nullable=False, default=CardType.NEWS)
+
+ # Content
+ headline = Column(String(200), nullable=False)
+ summary = Column(Text)
+ content = Column(JSON) # Flexible content storage
+
+ # Metadata
+ source_type = Column(String(50)) # 'search', 'subscription', 'manual'
+ source_id = Column(String(100)) # ID of source
+ parent_card_id = Column(String(50), ForeignKey("news_cards.id"))
+
+ # User interaction
+ user_id = Column(String(50), nullable=False)
+ archived = Column(Boolean, default=False)
+ pinned = Column(Boolean, default=False)
+
+ # Timestamps
+ created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
+ updated_at = Column(
+ DateTime,
+ default=lambda: datetime.now(timezone.utc),
+ onupdate=lambda: datetime.now(timezone.utc),
+ )
+
+ # Relationships
+ versions = relationship(
+ "CardVersion", back_populates="card", cascade="all, delete-orphan"
+ )
+ parent = relationship("NewsCard", remote_side=[id])
+
+
+class CardVersion(Base):
+ """Version history for cards"""
+
+ __tablename__ = "news_card_versions"
+ __table_args__ = {"extend_existing": True}
+
+ id = Column(Integer, primary_key=True)
+ card_id = Column(String(50), ForeignKey("news_cards.id"), nullable=False)
+ version_number = Column(Integer, nullable=False)
+
+ # Version content
+ content_snapshot = Column(JSON) # Full content at this version
+ change_summary = Column(Text) # What changed
+
+ # Metadata
+ created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
+ created_by = Column(String(50)) # 'system' or user_id
+
+ # Relationship
+ card = relationship("NewsCard", back_populates="versions")
diff --git a/src/local_deep_research/news/preference_manager/__init__.py b/src/local_deep_research/news/preference_manager/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/src/local_deep_research/news/preference_manager/base_preference.py b/src/local_deep_research/news/preference_manager/base_preference.py
new file mode 100644
index 0000000000..79e41a7a3b
--- /dev/null
+++ b/src/local_deep_research/news/preference_manager/base_preference.py
@@ -0,0 +1,285 @@
+"""
+Base class for preference management.
+Following LDR's pattern from BaseSearchStrategy.
+"""
+
+from abc import ABC, abstractmethod
+from typing import Dict, Any, List, Optional
+from datetime import timedelta
+from loguru import logger
+
+from ..core.utils import utc_now
+
+
+class BasePreferenceManager(ABC):
+ """Abstract base class for preference management."""
+
+ def __init__(self, storage_backend: Optional[Any] = None):
+ """
+ Initialize the base preference manager.
+
+ Args:
+ storage_backend: Optional storage backend for preferences
+ """
+ self.storage_backend = storage_backend
+
+ @abstractmethod
+ def get_preferences(self, user_id: str) -> Dict[str, Any]:
+ """
+ Get user preferences.
+
+ Args:
+ user_id: ID of the user
+
+ Returns:
+ Dictionary of user preferences
+ """
+ pass
+
+ @abstractmethod
+ def update_preferences(
+ self, user_id: str, preferences: Dict[str, Any]
+ ) -> Dict[str, Any]:
+ """
+ Update user preferences.
+
+ Args:
+ user_id: ID of the user
+ preferences: Dictionary of preferences to update
+
+ Returns:
+ Updated preferences
+ """
+ pass
+
+ def add_interest(
+ self, user_id: str, interest: str, weight: float = 1.0
+ ) -> None:
+ """
+ Add an interest to user preferences.
+
+ Args:
+ user_id: ID of the user
+ interest: The interest to add
+ weight: Weight/importance of this interest
+ """
+ prefs = self.get_preferences(user_id)
+
+ if "interests" not in prefs:
+ prefs["interests"] = {}
+
+ prefs["interests"][interest] = weight
+ prefs["interests_updated_at"] = utc_now().isoformat()
+
+ self.update_preferences(user_id, prefs)
+ logger.info(f"Added interest '{interest}' for user {user_id}")
+
+ def remove_interest(self, user_id: str, interest: str) -> None:
+ """
+ Remove an interest from user preferences.
+
+ Args:
+ user_id: ID of the user
+ interest: The interest to remove
+ """
+ prefs = self.get_preferences(user_id)
+
+ if "interests" in prefs and interest in prefs["interests"]:
+ del prefs["interests"][interest]
+ prefs["interests_updated_at"] = utc_now().isoformat()
+
+ self.update_preferences(user_id, prefs)
+ logger.info(f"Removed interest '{interest}' for user {user_id}")
+
+ def ignore_topic(self, user_id: str, topic: str) -> None:
+ """
+ Add a topic to the ignore list.
+
+ Args:
+ user_id: ID of the user
+ topic: Topic to ignore
+ """
+ prefs = self.get_preferences(user_id)
+
+ if "disliked_topics" not in prefs:
+ prefs["disliked_topics"] = []
+
+ if topic not in prefs["disliked_topics"]:
+ prefs["disliked_topics"].append(topic)
+ prefs["preferences_updated_at"] = utc_now().isoformat()
+
+ self.update_preferences(user_id, prefs)
+ logger.info(f"Added '{topic}' to ignore list for user {user_id}")
+
+ def boost_source(
+ self, user_id: str, source: str, weight: float = 1.5
+ ) -> None:
+ """
+ Boost a particular news source.
+
+ Args:
+ user_id: ID of the user
+ source: Source domain to boost
+ weight: Boost weight
+ """
+ prefs = self.get_preferences(user_id)
+
+ if "source_weights" not in prefs:
+ prefs["source_weights"] = {}
+
+ prefs["source_weights"][source] = weight
+ prefs["preferences_updated_at"] = utc_now().isoformat()
+
+ self.update_preferences(user_id, prefs)
+ logger.info(
+ f"Set source weight for '{source}' to {weight} for user {user_id}"
+ )
+
+ def get_default_preferences(self) -> Dict[str, Any]:
+ """
+ Get default preferences for new users.
+
+ Returns:
+ Dictionary of default preferences
+ """
+ return {
+ "liked_categories": [],
+ "disliked_categories": [],
+ "liked_topics": [],
+ "disliked_topics": [],
+ "interests": {},
+ "source_weights": {},
+ "impact_threshold": 5, # Default threshold
+ "focus_preferences": {
+ "surprising": False,
+ "breaking": True,
+ "positive": False,
+ "local": False,
+ },
+ "custom_search_terms": "",
+ "search_strategy": "news_aggregation",
+ "created_at": utc_now().isoformat(),
+ "preferences_updated_at": utc_now().isoformat(),
+ }
+
+
+class TopicRegistry:
+ """
+ Registry for dynamically discovered topics.
+ Not user-specific - tracks global topic trends.
+ """
+
+ def __init__(self, llm_client: Optional[Any] = None):
+ """
+ Initialize topic registry.
+
+ Args:
+ llm_client: LLM client for topic extraction
+ """
+ self.llm_client = llm_client
+ self.topics: Dict[str, Dict[str, Any]] = {}
+
+ def extract_topics(self, content: str, max_topics: int = 5) -> List[str]:
+ """
+ Extract topics from content using LLM.
+
+ Args:
+ content: Text content to analyze
+ max_topics: Maximum number of topics to extract
+
+ Returns:
+ List of extracted topics
+ """
+ if not self.llm_client:
+ logger.warning("No LLM client available for topic extraction")
+ return []
+
+ try:
+ prompt = f"""
+ Extract {max_topics} key topics from this content.
+ Return only the topic names, one per line.
+ Make them specific but not too narrow.
+
+ Content: {content[:1000]}
+ """
+
+ response = self.llm_client.invoke(prompt)
+ content = (
+ response.content
+ if hasattr(response, "content")
+ else str(response)
+ )
+
+ # Parse topics from response
+ topics = [
+ topic.strip()
+ for topic in content.strip().split("\n")
+ if topic.strip()
+ ][:max_topics]
+
+ # Register discovered topics
+ for topic in topics:
+ self.register_topic(topic)
+
+ return topics
+
+ except Exception as e:
+ logger.error(f"Error extracting topics: {e}")
+ return []
+
+ def register_topic(self, topic: str) -> None:
+ """
+ Register a discovered topic.
+
+ Args:
+ topic: Topic to register
+ """
+ if topic not in self.topics:
+ self.topics[topic] = {
+ "first_seen": utc_now(),
+ "count": 0,
+ "last_seen": utc_now(),
+ }
+
+ self.topics[topic]["count"] += 1
+ self.topics[topic]["last_seen"] = utc_now()
+
+ def get_trending_topics(
+ self, hours: int = 24, limit: int = 10
+ ) -> List[str]:
+ """
+ Get trending topics from the last N hours.
+
+ Args:
+ hours: Look back period in hours
+ limit: Maximum number of topics to return
+
+ Returns:
+ List of trending topic names
+ """
+ cutoff_time = utc_now() - timedelta(hours=hours)
+
+ # Filter topics seen recently
+ recent_topics = [
+ (topic, data)
+ for topic, data in self.topics.items()
+ if data["last_seen"] >= cutoff_time
+ ]
+
+ # Sort by count (most frequent first)
+ recent_topics.sort(key=lambda x: x[1]["count"], reverse=True)
+
+ # Return topic names only
+ return [topic for topic, _ in recent_topics[:limit]]
+
+ def get_topic_info(self, topic: str) -> Optional[Dict[str, Any]]:
+ """
+ Get information about a specific topic.
+
+ Args:
+ topic: Topic to look up
+
+ Returns:
+ Topic information or None if not found
+ """
+ return self.topics.get(topic)
diff --git a/src/local_deep_research/news/preference_manager/storage.py b/src/local_deep_research/news/preference_manager/storage.py
new file mode 100644
index 0000000000..e73b8ccb51
--- /dev/null
+++ b/src/local_deep_research/news/preference_manager/storage.py
@@ -0,0 +1,210 @@
+"""
+SQLAlchemy storage implementation for user preferences.
+"""
+
+from typing import List, Optional, Dict, Any
+from sqlalchemy.orm import Session
+
+from ..core.storage import PreferenceStorage
+from ..models import UserPreference
+from ..cache import NewsCache
+
+
+class SQLPreferenceStorage(PreferenceStorage):
+ """SQLAlchemy implementation of preference storage"""
+
+ def __init__(self, session: Optional[Session] = None):
+ self.cache = NewsCache()
+ self._session = session
+
+ @property
+ def session(self):
+ """Get database session"""
+ if self._session:
+ return self._session
+ return self.cache.get_session()
+
+ def create(self, data: Dict[str, Any]) -> str:
+ """Create new user preferences"""
+ with self.session as session:
+ prefs = UserPreference(
+ user_id=data["user_id"],
+ liked_categories=data.get("liked_categories", []),
+ disliked_categories=data.get("disliked_categories", []),
+ liked_topics=data.get("liked_topics", []),
+ disliked_topics=data.get("disliked_topics", []),
+ impact_threshold=data.get("impact_threshold", 5),
+ focus_preferences=data.get("focus_preferences", {}),
+ custom_prompt=data.get("custom_prompt"),
+ custom_search_terms=data.get("custom_search_terms"),
+ preference_embedding=data.get("preference_embedding"),
+ liked_news_ids=data.get("liked_news_ids", []),
+ disliked_news_ids=data.get("disliked_news_ids", []),
+ )
+
+ session.add(prefs)
+ session.commit()
+
+ return str(prefs.id)
+
+ def get(self, id: str) -> Optional[Dict[str, Any]]:
+ """Get preferences by ID"""
+ with self.session as session:
+ prefs = session.query(UserPreference).filter_by(id=int(id)).first()
+ return prefs.to_dict() if prefs else None
+
+ def update(self, id: str, data: Dict[str, Any]) -> bool:
+ """Update preferences"""
+ with self.session as session:
+ prefs = session.query(UserPreference).filter_by(id=int(id)).first()
+ if not prefs:
+ return False
+
+ # Update fields
+ for field, value in data.items():
+ if hasattr(prefs, field):
+ setattr(prefs, field, value)
+
+ session.commit()
+ return True
+
+ def delete(self, id: str) -> bool:
+ """Delete preferences"""
+ with self.session as session:
+ prefs = session.query(UserPreference).filter_by(id=int(id)).first()
+ if not prefs:
+ return False
+
+ session.delete(prefs)
+ session.commit()
+ return True
+
+ def list(
+ self,
+ filters: Optional[Dict[str, Any]] = None,
+ limit: int = 100,
+ offset: int = 0,
+ ) -> List[Dict[str, Any]]:
+ """List preferences (usually just one per user)"""
+ with self.session as session:
+ query = session.query(UserPreference)
+
+ if filters and "user_id" in filters:
+ query = query.filter_by(user_id=filters["user_id"])
+
+ prefs = query.limit(limit).offset(offset).all()
+ return [p.to_dict() for p in prefs]
+
+ def get_user_preferences(self, user_id: str) -> Optional[Dict[str, Any]]:
+ """Get preferences for a user"""
+ with self.session as session:
+ prefs = (
+ session.query(UserPreference).filter_by(user_id=user_id).first()
+ )
+ return prefs.to_dict() if prefs else None
+
+ def upsert_preferences(
+ self, user_id: str, preferences: Dict[str, Any]
+ ) -> str:
+ """Create or update user preferences"""
+ existing = self.get_user_preferences(user_id)
+
+ if existing:
+ # Update existing preferences
+ with self.session as session:
+ prefs = (
+ session.query(UserPreference)
+ .filter_by(user_id=user_id)
+ .first()
+ )
+
+ # Update fields
+ for field, value in preferences.items():
+ if hasattr(prefs, field):
+ setattr(prefs, field, value)
+
+ session.commit()
+ return str(prefs.id)
+ else:
+ # Create new preferences
+ preferences["user_id"] = user_id
+ return self.create(preferences)
+
+ def add_liked_item(
+ self, user_id: str, item_id: str, item_type: str = "news"
+ ) -> bool:
+ """Add an item to liked list"""
+ with self.session as session:
+ prefs = (
+ session.query(UserPreference).filter_by(user_id=user_id).first()
+ )
+
+ if not prefs:
+ # Create new preferences
+ prefs = UserPreference(
+ user_id=user_id,
+ liked_news_ids=[item_id] if item_type == "news" else [],
+ disliked_news_ids=[],
+ )
+ session.add(prefs)
+ else:
+ # Update existing preferences
+ if item_type == "news":
+ liked_ids = prefs.liked_news_ids or []
+ if item_id not in liked_ids:
+ liked_ids.append(item_id)
+ # Keep last 100 items
+ prefs.liked_news_ids = liked_ids[-100:]
+
+ session.commit()
+ return True
+
+ def add_disliked_item(
+ self, user_id: str, item_id: str, item_type: str = "news"
+ ) -> bool:
+ """Add an item to disliked list"""
+ with self.session as session:
+ prefs = (
+ session.query(UserPreference).filter_by(user_id=user_id).first()
+ )
+
+ if not prefs:
+ # Create new preferences
+ prefs = UserPreference(
+ user_id=user_id,
+ liked_news_ids=[],
+ disliked_news_ids=[item_id] if item_type == "news" else [],
+ )
+ session.add(prefs)
+ else:
+ # Update existing preferences
+ if item_type == "news":
+ disliked_ids = prefs.disliked_news_ids or []
+ if item_id not in disliked_ids:
+ disliked_ids.append(item_id)
+ # Keep last 100 items
+ prefs.disliked_news_ids = disliked_ids[-100:]
+
+ session.commit()
+ return True
+
+ def update_preference_embedding(
+ self, user_id: str, embedding: List[float]
+ ) -> bool:
+ """Update the user's preference embedding"""
+ with self.session as session:
+ prefs = (
+ session.query(UserPreference).filter_by(user_id=user_id).first()
+ )
+
+ if not prefs:
+ # Create new preferences with embedding
+ prefs = UserPreference(
+ user_id=user_id, preference_embedding=embedding
+ )
+ session.add(prefs)
+ else:
+ prefs.preference_embedding = embedding
+
+ session.commit()
+ return True
diff --git a/src/local_deep_research/news/rating_system/__init__.py b/src/local_deep_research/news/rating_system/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/src/local_deep_research/news/rating_system/base_rater.py b/src/local_deep_research/news/rating_system/base_rater.py
new file mode 100644
index 0000000000..0dd58ec996
--- /dev/null
+++ b/src/local_deep_research/news/rating_system/base_rater.py
@@ -0,0 +1,279 @@
+"""
+Base class for rating systems.
+Following LDR's pattern from BaseSearchStrategy.
+"""
+
+from abc import ABC, abstractmethod
+from typing import List, Dict, Any, Optional
+from loguru import logger
+
+from ..core.utils import utc_now
+
+
+class BaseRatingSystem(ABC):
+ """Abstract base class for all rating systems."""
+
+ def __init__(self, storage_backend: Optional[Any] = None):
+ """
+ Initialize the base rating system.
+
+ Args:
+ storage_backend: Optional storage backend for ratings
+ """
+ self.storage_backend = storage_backend
+ self.rating_type = self.__class__.__name__
+
+ @abstractmethod
+ def rate(
+ self,
+ user_id: str,
+ card_id: str,
+ rating_value: Any,
+ metadata: Optional[Dict[str, Any]] = None,
+ ) -> Dict[str, Any]:
+ """
+ Record a rating from a user.
+
+ Args:
+ user_id: ID of the user making the rating
+ card_id: ID of the card being rated
+ rating_value: The rating value (type depends on implementation)
+ metadata: Optional additional metadata
+
+ Returns:
+ Dict containing rating confirmation and any updates
+ """
+ pass
+
+ @abstractmethod
+ def get_rating(
+ self, user_id: str, card_id: str
+ ) -> Optional[Dict[str, Any]]:
+ """
+ Get a user's rating for a specific card.
+
+ Args:
+ user_id: ID of the user
+ card_id: ID of the card
+
+ Returns:
+ Rating information or None if not rated
+ """
+ pass
+
+ @abstractmethod
+ def get_rating_type(self) -> str:
+ """
+ Get the type of rating this system handles.
+
+ Returns:
+ str: Rating type identifier
+ """
+ pass
+
+ def get_recent_ratings(
+ self, user_id: str, limit: int = 50
+ ) -> List[Dict[str, Any]]:
+ """
+ Get recent ratings by a user.
+
+ Args:
+ user_id: ID of the user
+ limit: Maximum number of ratings to return
+
+ Returns:
+ List of recent ratings
+ """
+ # Default implementation - should be overridden if storage is available
+ logger.warning(
+ f"get_recent_ratings not implemented for {self.rating_type}"
+ )
+ return []
+
+ def get_card_ratings(
+ self, card_id: str, rating_type: Optional[str] = None
+ ) -> Dict[str, Any]:
+ """
+ Get aggregated ratings for a card.
+
+ Args:
+ card_id: ID of the card
+ rating_type: Optional specific rating type to filter
+
+ Returns:
+ Aggregated rating information
+ """
+ # Default implementation - should be overridden
+ logger.warning(
+ f"get_card_ratings not implemented for {self.rating_type}"
+ )
+ return {"total": 0, "average": None}
+
+ def remove_rating(self, user_id: str, card_id: str) -> bool:
+ """
+ Remove a user's rating for a card.
+
+ Args:
+ user_id: ID of the user
+ card_id: ID of the card
+
+ Returns:
+ bool: True if rating was removed
+ """
+ # Default implementation
+ logger.warning(f"remove_rating not implemented for {self.rating_type}")
+ return False
+
+ def _create_rating_record(
+ self,
+ user_id: str,
+ card_id: str,
+ rating_value: Any,
+ metadata: Optional[Dict[str, Any]] = None,
+ ) -> Dict[str, Any]:
+ """
+ Create a standard rating record.
+
+ Helper method for subclasses to create consistent rating records.
+ """
+ return {
+ "user_id": user_id,
+ "card_id": card_id,
+ "rating_type": self.get_rating_type(),
+ "rating_value": rating_value,
+ "rated_at": utc_now().isoformat(),
+ "metadata": metadata or {},
+ }
+
+ def _validate_rating_value(self, rating_value: Any) -> None:
+ """
+ Validate that a rating value is acceptable.
+ Should be overridden by subclasses with specific validation.
+
+ Args:
+ rating_value: The value to validate
+
+ Raises:
+ ValueError: If the rating value is invalid
+ """
+ if rating_value is None:
+ raise ValueError("Rating value cannot be None")
+
+
+class QualityRatingSystem(BaseRatingSystem):
+ """Rating system for article quality (1-5 stars)."""
+
+ def get_rating_type(self) -> str:
+ return "quality"
+
+ def rate(
+ self,
+ user_id: str,
+ card_id: str,
+ rating_value: int,
+ metadata: Optional[Dict[str, Any]] = None,
+ ) -> Dict[str, Any]:
+ """
+ Rate the quality of an article.
+
+ Args:
+ rating_value: Integer from 1-5 stars
+ """
+ self._validate_rating_value(rating_value)
+
+ record = self._create_rating_record(
+ user_id, card_id, rating_value, metadata
+ )
+
+ # Store the rating (implementation depends on storage backend)
+ if self.storage_backend:
+ # Storage implementation would go here
+ pass
+
+ logger.info(
+ f"User {user_id} rated card {card_id} quality: {rating_value} stars"
+ )
+
+ return {
+ "success": True,
+ "rating": record,
+ "message": f"Quality rating of {rating_value} stars recorded",
+ }
+
+ def _validate_rating_value(self, rating_value: Any) -> None:
+ """Validate that rating is between 1-5."""
+ super()._validate_rating_value(rating_value)
+
+ if not isinstance(rating_value, int):
+ raise ValueError("Quality rating must be an integer")
+
+ if rating_value < 1 or rating_value > 5:
+ raise ValueError("Quality rating must be between 1 and 5 stars")
+
+ def get_rating(
+ self, user_id: str, card_id: str
+ ) -> Optional[Dict[str, Any]]:
+ """Get a user's quality rating for a card."""
+ # Implementation depends on storage backend
+ if self.storage_backend:
+ # Storage query would go here
+ pass
+ return None
+
+
+class RelevanceRatingSystem(BaseRatingSystem):
+ """Rating system for personal relevance (thumbs up/down)."""
+
+ def get_rating_type(self) -> str:
+ return "relevance"
+
+ def rate(
+ self,
+ user_id: str,
+ card_id: str,
+ rating_value: str,
+ metadata: Optional[Dict[str, Any]] = None,
+ ) -> Dict[str, Any]:
+ """
+ Rate the relevance of an article.
+
+ Args:
+ rating_value: "up" or "down"
+ """
+ self._validate_rating_value(rating_value)
+
+ record = self._create_rating_record(
+ user_id, card_id, rating_value, metadata
+ )
+
+ # Store the rating (implementation depends on storage backend)
+ if self.storage_backend:
+ # Storage implementation would go here
+ pass
+
+ logger.info(
+ f"User {user_id} rated card {card_id} relevance: thumbs {rating_value}"
+ )
+
+ return {
+ "success": True,
+ "rating": record,
+ "message": f"Relevance rating of thumbs {rating_value} recorded",
+ }
+
+ def _validate_rating_value(self, rating_value: Any) -> None:
+ """Validate that rating is up or down."""
+ super()._validate_rating_value(rating_value)
+
+ if rating_value not in ["up", "down"]:
+ raise ValueError("Relevance rating must be 'up' or 'down'")
+
+ def get_rating(
+ self, user_id: str, card_id: str
+ ) -> Optional[Dict[str, Any]]:
+ """Get a user's relevance rating for a card."""
+ # Implementation depends on storage backend
+ if self.storage_backend:
+ # Storage query would go here
+ pass
+ return None
diff --git a/src/local_deep_research/news/rating_system/storage.py b/src/local_deep_research/news/rating_system/storage.py
new file mode 100644
index 0000000000..d38b6f78be
--- /dev/null
+++ b/src/local_deep_research/news/rating_system/storage.py
@@ -0,0 +1,243 @@
+"""
+SQLAlchemy storage implementation for ratings.
+"""
+
+from typing import List, Optional, Dict, Any
+from sqlalchemy.orm import Session
+from sqlalchemy import desc
+
+from ..core.storage import RatingStorage
+from ..models import Rating, RatingType
+from ..cache import NewsCache
+
+
+class SQLRatingStorage(RatingStorage):
+ """SQLAlchemy implementation of rating storage"""
+
+ def __init__(self, session: Optional[Session] = None):
+ self.cache = NewsCache()
+ self._session = session
+
+ @property
+ def session(self):
+ """Get database session"""
+ if self._session:
+ return self._session
+ return self.cache.get_session()
+
+ def create(self, data: Dict[str, Any]) -> str:
+ """Create a new rating"""
+ with self.session as session:
+ rating = Rating(
+ user_id=data["user_id"],
+ item_id=data["item_id"],
+ item_type=data.get("item_type", "card"),
+ relevance_vote=data.get(
+ "rating_value"
+ ), # Map rating_value to relevance_vote
+ quality_rating=data.get("quality_rating"),
+ )
+
+ session.add(rating)
+ session.commit()
+
+ return str(rating.id)
+
+ def get(self, id: str) -> Optional[Dict[str, Any]]:
+ """Get a rating by ID"""
+ with self.session as session:
+ rating = session.query(Rating).filter_by(id=int(id)).first()
+ if not rating:
+ return None
+ return {
+ "id": rating.id,
+ "user_id": rating.user_id,
+ "item_id": rating.item_id,
+ "item_type": rating.item_type,
+ "relevance_vote": rating.relevance_vote,
+ "quality_rating": rating.quality_rating,
+ "created_at": rating.created_at,
+ "updated_at": rating.updated_at,
+ }
+
+ def update(self, id: str, data: Dict[str, Any]) -> bool:
+ """Update a rating"""
+ with self.session as session:
+ rating = session.query(Rating).filter_by(id=int(id)).first()
+ if not rating:
+ return False
+
+ # Update allowed fields
+ if "rating_value" in data:
+ rating.rating_value = data["rating_value"]
+ if "comment" in data:
+ rating.comment = data["comment"]
+
+ session.commit()
+ return True
+
+ def delete(self, id: str) -> bool:
+ """Delete a rating"""
+ with self.session as session:
+ rating = session.query(Rating).filter_by(id=int(id)).first()
+ if not rating:
+ return False
+
+ session.delete(rating)
+ session.commit()
+ return True
+
+ def list(
+ self,
+ filters: Optional[Dict[str, Any]] = None,
+ limit: int = 100,
+ offset: int = 0,
+ ) -> List[Dict[str, Any]]:
+ """List ratings with optional filtering"""
+ with self.session as session:
+ query = session.query(Rating)
+
+ if filters:
+ if "user_id" in filters:
+ query = query.filter_by(user_id=filters["user_id"])
+ if "item_id" in filters:
+ query = query.filter_by(item_id=filters["item_id"])
+ if "item_type" in filters:
+ query = query.filter_by(item_type=filters["item_type"])
+ # For backward compatibility, also check card_id
+ if "card_id" in filters:
+ query = query.filter_by(item_id=filters["card_id"])
+
+ ratings = (
+ query.order_by(desc(Rating.created_at))
+ .limit(limit)
+ .offset(offset)
+ .all()
+ )
+ return [
+ {
+ "id": rating.id,
+ "user_id": rating.user_id,
+ "item_id": rating.item_id,
+ "item_type": rating.item_type,
+ "relevance_vote": rating.relevance_vote,
+ "quality_rating": rating.quality_rating,
+ "created_at": rating.created_at,
+ "updated_at": rating.updated_at,
+ }
+ for rating in ratings
+ ]
+
+ def get_user_rating(
+ self, user_id: str, item_id: str, rating_type: str
+ ) -> Optional[Dict[str, Any]]:
+ """Get a user's rating for a specific item"""
+ with self.session as session:
+ query = session.query(Rating).filter_by(
+ user_id=user_id, rating_type=RatingType(rating_type)
+ )
+
+ # Check both card and news item IDs
+ rating = query.filter(
+ (Rating.card_id == item_id) | (Rating.news_item_id == item_id)
+ ).first()
+
+ return rating.to_dict() if rating else None
+
+ def upsert_rating(
+ self,
+ user_id: str,
+ item_id: str,
+ rating_type: str,
+ rating_value: str,
+ item_type: str = "card",
+ ) -> str:
+ """Create or update a rating"""
+ # Check if rating exists
+ existing = self.get_user_rating(user_id, item_id, rating_type)
+
+ if existing:
+ # Update existing rating
+ self.update(str(existing["id"]), {"rating_value": rating_value})
+ return str(existing["id"])
+ else:
+ # Create new rating
+ data = {
+ "user_id": user_id,
+ "item_id": item_id,
+ "item_type": item_type,
+ "rating_type": rating_type,
+ "rating_value": rating_value,
+ }
+ return self.create(data)
+
+ def get_ratings_summary(
+ self, item_id: str, item_type: str = "card"
+ ) -> Dict[str, Any]:
+ """Get aggregated ratings for an item"""
+ with self.session as session:
+ # Build query based on item type
+ if item_type == "card":
+ base_query = session.query(Rating).filter_by(card_id=item_id)
+ else:
+ base_query = session.query(Rating).filter_by(
+ news_item_id=item_id
+ )
+
+ # Get quality ratings
+ quality_ratings = base_query.filter_by(
+ rating_type=RatingType.QUALITY
+ ).all()
+ quality_values = [
+ int(r.rating_value)
+ for r in quality_ratings
+ if r.rating_value.isdigit()
+ ]
+
+ # Get relevance ratings
+ relevance_ratings = base_query.filter_by(
+ rating_type=RatingType.RELEVANCE
+ ).all()
+ up_votes = sum(
+ 1 for r in relevance_ratings if r.rating_value == "up"
+ )
+ down_votes = sum(
+ 1 for r in relevance_ratings if r.rating_value == "down"
+ )
+
+ return {
+ "item_id": item_id,
+ "item_type": item_type,
+ "quality": {
+ "count": len(quality_values),
+ "average": sum(quality_values) / len(quality_values)
+ if quality_values
+ else 0,
+ "distribution": self._get_rating_distribution(
+ quality_values
+ ),
+ },
+ "relevance": {
+ "up_votes": up_votes,
+ "down_votes": down_votes,
+ "net_score": up_votes - down_votes,
+ },
+ }
+
+ def get_user_ratings(
+ self, user_id: str, rating_type: Optional[str] = None, limit: int = 100
+ ) -> List[Dict[str, Any]]:
+ """Get all ratings by a user"""
+ filters = {"user_id": user_id}
+ if rating_type:
+ filters["rating_type"] = rating_type
+
+ return self.list(filters, limit)
+
+ def _get_rating_distribution(self, ratings: List[int]) -> Dict[int, int]:
+ """Get distribution of ratings (1-5)"""
+ distribution = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
+ for rating in ratings:
+ if 1 <= rating <= 5:
+ distribution[rating] += 1
+ return distribution
diff --git a/src/local_deep_research/news/recommender/__init__.py b/src/local_deep_research/news/recommender/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/src/local_deep_research/news/recommender/base_recommender.py b/src/local_deep_research/news/recommender/base_recommender.py
new file mode 100644
index 0000000000..9672d3ba92
--- /dev/null
+++ b/src/local_deep_research/news/recommender/base_recommender.py
@@ -0,0 +1,203 @@
+"""
+Base class for all news recommendation strategies.
+Following LDR's pattern from BaseSearchStrategy.
+"""
+
+from abc import ABC, abstractmethod
+from typing import List, Dict, Any, Optional, Callable
+from loguru import logger
+
+from ..core.base_card import NewsCard
+from ..preference_manager.base_preference import BasePreferenceManager
+from ..rating_system.base_rater import BaseRatingSystem
+
+
+class BaseRecommender(ABC):
+ """Abstract base class for all recommendation strategies."""
+
+ def __init__(
+ self,
+ preference_manager: Optional[BasePreferenceManager] = None,
+ rating_system: Optional[BaseRatingSystem] = None,
+ topic_registry: Optional[Any] = None,
+ search_system: Optional[Any] = None,
+ ):
+ """
+ Initialize the base recommender with common dependencies.
+
+ Args:
+ preference_manager: Manager for user preferences
+ rating_system: System for tracking ratings
+ topic_registry: Registry of discovered topics
+ search_system: LDR search system for executing queries
+ """
+ self.preference_manager = preference_manager
+ self.rating_system = rating_system
+ self.topic_registry = topic_registry
+ self.search_system = search_system
+
+ # Progress tracking (following LDR pattern)
+ self.progress_callback = None
+
+ # Strategy name for identification
+ self.strategy_name = self.__class__.__name__
+
+ def set_progress_callback(
+ self, callback: Callable[[str, int, dict], None]
+ ) -> None:
+ """Set a callback function to receive progress updates."""
+ self.progress_callback = callback
+
+ def _update_progress(
+ self,
+ message: str,
+ progress_percent: Optional[int] = None,
+ metadata: Optional[dict] = None,
+ ) -> None:
+ """Send a progress update via the callback if available."""
+ if self.progress_callback:
+ self.progress_callback(message, progress_percent, metadata or {})
+
+ @abstractmethod
+ def generate_recommendations(
+ self, user_id: str, context: Optional[Dict[str, Any]] = None
+ ) -> List[NewsCard]:
+ """
+ Generate news recommendations for a user.
+
+ Args:
+ user_id: The user to generate recommendations for
+ context: Optional context (e.g., current page, recent activity)
+
+ Returns:
+ List of NewsCard objects representing recommendations
+ """
+ pass
+
+ def _get_user_preferences(self, user_id: str) -> Dict[str, Any]:
+ """Get user preferences if preference manager is available."""
+ if self.preference_manager:
+ return self.preference_manager.get_preferences(user_id)
+ return {}
+
+ def _get_user_ratings(
+ self, user_id: str, limit: int = 50
+ ) -> List[Dict[str, Any]]:
+ """Get recent user ratings if rating system is available."""
+ if self.rating_system:
+ return self.rating_system.get_recent_ratings(user_id, limit)
+ return []
+
+ def _execute_search(
+ self, query: str, strategy: Optional[str] = None
+ ) -> Dict[str, Any]:
+ """
+ Execute a search using the LDR search system.
+
+ Args:
+ query: The search query
+ strategy: Optional search strategy to use
+
+ Returns:
+ Search results dictionary
+ """
+ if not self.search_system:
+ logger.warning("No search system available for recommendations")
+ return {"error": "Search system not configured"}
+
+ try:
+ # Use news strategy by default if available
+ if strategy is None:
+ strategy = "news_aggregation"
+
+ # Execute search
+ results = self.search_system.analyze_topic(query)
+ return results
+
+ except Exception as e:
+ logger.error(f"Error executing search for recommendations: {e}")
+ return {"error": str(e)}
+
+ def _filter_by_preferences(
+ self, cards: List[NewsCard], preferences: Dict[str, Any]
+ ) -> List[NewsCard]:
+ """
+ Filter cards based on user preferences.
+
+ Args:
+ cards: List of news cards to filter
+ preferences: User preferences dictionary
+
+ Returns:
+ Filtered list of cards
+ """
+ filtered = cards
+
+ # Filter by categories if specified
+ if (
+ "liked_categories" in preferences
+ and preferences["liked_categories"]
+ ):
+ # Boost liked categories rather than filtering out others
+ for card in filtered:
+ if card.category in preferences["liked_categories"]:
+ card.metadata["preference_boost"] = 1.2
+
+ # Filter by impact threshold
+ if "impact_threshold" in preferences:
+ threshold = preferences["impact_threshold"]
+ filtered = [
+ card for card in filtered if card.impact_score >= threshold
+ ]
+
+ # Apply disliked topics
+ if "disliked_topics" in preferences and preferences["disliked_topics"]:
+ filtered = [
+ card
+ for card in filtered
+ if not any(
+ topic in card.topic.lower()
+ for topic in preferences["disliked_topics"]
+ )
+ ]
+
+ return filtered
+
+ def _sort_by_relevance(
+ self, cards: List[NewsCard], user_id: str
+ ) -> List[NewsCard]:
+ """
+ Sort cards by relevance to the user.
+ Default implementation uses impact score and preference boost.
+
+ Args:
+ cards: List of cards to sort
+ user_id: User ID for personalization
+
+ Returns:
+ Sorted list of cards
+ """
+
+ def calculate_score(card: NewsCard) -> float:
+ # Base score from impact
+ score = card.impact_score / 10.0
+
+ # Apply preference boost if exists
+ boost = card.metadata.get("preference_boost", 1.0)
+ score *= boost
+
+ # Could add more factors here (recency, etc.)
+ return score
+
+ # Sort by calculated score (highest first)
+ return sorted(cards, key=calculate_score, reverse=True)
+
+ def get_strategy_info(self) -> Dict[str, Any]:
+ """Get information about this recommendation strategy."""
+ return {
+ "name": self.strategy_name,
+ "has_preference_manager": self.preference_manager is not None,
+ "has_rating_system": self.rating_system is not None,
+ "has_search_system": self.search_system is not None,
+ "description": self.__doc__ or "No description available",
+ }
diff --git a/src/local_deep_research/news/recommender/simple_feed.py b/src/local_deep_research/news/recommender/simple_feed.py
new file mode 100644
index 0000000000..e6fc0558f5
--- /dev/null
+++ b/src/local_deep_research/news/recommender/simple_feed.py
@@ -0,0 +1,300 @@
+"""
+Simple news feed generator that doesn't require search operations.
+Used for quick feed generation and testing.
+"""
+
+from loguru import logger
+from typing import Dict, Any, List, Optional
+from datetime import datetime, timezone
+import uuid
+
+from ..core.base_card import NewsCard
+
+
+def generate_simple_news_feed(
+ user_id: str = "anonymous", limit: int = 10, focus: Optional[str] = None
+) -> List[Dict[str, Any]]:
+ """
+ Generate a simple news feed without performing searches.
+ Returns mock/cached news items for quick display.
+
+ Args:
+ user_id: User identifier
+ limit: Number of items to return
+ focus: Optional focus area
+
+ Returns:
+ List of news item dictionaries
+ """
+ # Default news categories and templates
+ news_templates = [
+ {
+ "category": "Technology",
+ "headlines": [
+ "AI Model Achieves Breakthrough in Natural Language Understanding",
+ "Major Tech Company Announces Revolutionary Quantum Computing Advance",
+ "New Cybersecurity Threat Discovered Affecting Millions",
+ "Open Source Project Transforms Software Development",
+ "Breakthrough in Battery Technology Promises Longer Device Life",
+ ],
+ "impact_scores": [8, 9, 7, 6, 7],
+ },
+ {
+ "category": "Science",
+ "headlines": [
+ "Scientists Discover New Method for Carbon Capture",
+ "Medical Researchers Announce Progress in Cancer Treatment",
+ "Space Telescope Reveals Unexpected Cosmic Phenomenon",
+ "Climate Study Shows Accelerating Environmental Changes",
+ "New Material Discovery Could Revolutionize Electronics",
+ ],
+ "impact_scores": [8, 9, 7, 8, 6],
+ },
+ {
+ "category": "Business",
+ "headlines": [
+ "Global Markets React to New Economic Policy Changes",
+ "Major Corporation Announces Strategic Merger",
+ "Startup Ecosystem Shows Record Growth in Key Sectors",
+ "Supply Chain Innovations Transform Global Trade",
+ "Financial Technology Breakthrough Disrupts Traditional Banking",
+ ],
+ "impact_scores": [7, 8, 6, 7, 8],
+ },
+ ]
+
+ # Generate news items
+ news_items = []
+ item_count = 0
+
+ for template in news_templates:
+ if item_count >= limit:
+ break
+
+ # Apply focus filter if specified
+ if focus and focus.lower() not in template["category"].lower():
+ continue
+
+ for i, headline in enumerate(template["headlines"]):
+ if item_count >= limit:
+ break
+
+ # Create news item with findings in markdown format
+ findings_markdown = f"""## {headline}
+
+### Key Findings
+
+Recent developments in the **{template["category"].lower()}** sector demonstrate significant progress:
+
+- **Primary Impact**: {headline} represents a major advancement affecting multiple stakeholders
+- **Industry Implications**: This development could reshape how organizations approach {template["category"].lower()} challenges
+- **Timeline**: Changes expected to roll out over the coming months
+
+### Analysis
+
+This breakthrough addresses several critical areas:
+
+1. **Innovation Factor**: Breaking new ground in established practices
+2. **Market Response**: Early indicators show positive reception from key players
+3. **Future Outlook**: Experts predict continued evolution in this space
+
+### What This Means
+
+> "{headline}" - This development signals a shift in how we understand and interact with {template["category"].lower()} innovations.
+
+**Impact Assessment**: Rated {template["impact_scores"][i]}/10 based on potential industry transformation and stakeholder benefits.
+
+### Next Steps
+
+- Monitor implementation progress
+- Track industry adoption rates
+- Assess competitive responses
+"""
+
+ news_item = {
+ "id": f"news-{uuid.uuid4().hex[:8]}",
+ "headline": headline,
+ "category": template["category"],
+ "summary": f"Recent developments in {template['category'].lower()} "
+ f"sector show significant progress. {headline} represents "
+ f"a major advancement that could impact various industries "
+ f"and stakeholders. Experts are closely monitoring the situation "
+ f"for further developments.",
+ "findings": findings_markdown,
+ "impact_score": template["impact_scores"][i],
+ "time_ago": f"{(i + 1) * 2} hours ago",
+ "upvotes": 0,
+ "downvotes": 0,
+ "source_url": None,
+ "topics": [
+ template["category"],
+ "Breaking News",
+ "Latest Updates",
+ ],
+ }
+
+ news_items.append(news_item)
+ item_count += 1
+
+ # If no items match focus, provide general feed
+ if not news_items and focus:
+ logger.info(f"No items for focus '{focus}', providing general feed")
+ return generate_simple_news_feed(user_id, limit, None)
+
+ return news_items
+
+
+def create_placeholder_card(
+ headline: str, category: str, summary: str, impact_score: int = 5
+) -> NewsCard:
+ """
+ Create a placeholder news card for testing.
+
+ Args:
+ headline: News headline
+ category: News category
+ summary: Brief summary
+ impact_score: Impact rating (1-10)
+
+ Returns:
+ NewsCard instance
+ """
+ card = NewsCard(headline=headline, summary=summary, card_type="news")
+
+ # Set additional attributes
+ card.category = category
+ card.impact_score = impact_score
+ card.created_at = datetime.now(timezone.utc)
+ card.source = "placeholder"
+
+ # Initialize interaction data
+ if not hasattr(card, "interaction"):
+ card.interaction = {
+ "votes_up": 0,
+ "votes_down": 0,
+ "views": 0,
+ "shares": 0,
+ }
+
+ return card
+
+
+def get_cached_news_feed(
+ storage_manager, user_id: str, limit: int
+) -> List[NewsCard]:
+ """
+ Get cached news feed from storage.
+
+ Args:
+ storage_manager: Storage manager instance
+ user_id: User identifier
+ limit: Maximum items to return
+
+ Returns:
+ List of NewsCard instances
+ """
+ try:
+ # Try to get cached cards
+ cached_cards = storage_manager.get_user_feed(
+ user_id=user_id, limit=limit, card_types=["news"]
+ )
+
+ if cached_cards:
+ logger.info(
+ f"Found {len(cached_cards)} cached news items for user {user_id}"
+ )
+ return cached_cards
+
+ except Exception as e:
+ logger.error(f"Error getting cached feed: {e}")
+
+ return []
+
+
+def generate_welcome_feed() -> List[Dict[str, Any]]:
+ """
+ Generate a welcome feed for new users.
+
+ Returns:
+ List of welcome news items
+ """
+ welcome_items = [
+ {
+ "id": "welcome-1",
+ "headline": "Welcome to LDR News - Your AI-Powered Research Feed",
+ "category": "Introduction",
+ "summary": "LDR News aggregates and analyzes breaking news from across "
+ "the web, providing you with personalized, real-time updates "
+ "on topics that matter to you. Get started by searching for "
+ "topics or creating subscriptions.",
+ "findings": """## Welcome to LDR News
+
+### What is LDR News?
+
+LDR News is your **personalized AI-powered research assistant** that transforms how you consume and understand news:
+
+- **Smart Curation**: Automatically finds and analyzes breaking news based on your interests
+- **Deep Insights**: Goes beyond headlines to provide comprehensive analysis with markdown-formatted findings
+- **Learning System**: Adapts to your preferences through votes and interactions
+- **Research Integration**: Seamlessly connects with LDR's powerful research capabilities
+
+### Getting Started
+
+1. **Search for Topics**: Use the search bar to find news on any topic
+2. **Subscribe**: Click subscribe on interesting topics for automatic updates
+3. **Vote**: Use thumbs up/down to train the system
+4. **Research**: Click "Research" on any item for deeper analysis
+
+### Key Features
+
+- **Real-time Updates**: Fresh news from trusted sources
+- **Markdown Rendering**: Beautiful formatting for easy reading (just like research results)
+- **Impact Scoring**: Understand the significance of each story
+- **Category Filtering**: Focus on what matters to you
+
+> "Turn information overload into actionable insights with LDR News"
+
+### Try It Now!
+
+Search for any topic in the search bar above to see LDR News in action. Each news card displays findings in a clean, readable format similar to research results pages.
+""",
+ "impact_score": 10,
+ "time_ago": "Just now",
+ "upvotes": 0,
+ "downvotes": 0,
+ "source_url": None,
+ "topics": ["Getting Started", "LDR News", "Tutorial"],
+ },
+ {
+ "id": "welcome-2",
+ "headline": "Create Personalized News Subscriptions",
+ "category": "Features",
+ "summary": "Stay updated on your interests by creating custom subscriptions. "
+ "Choose between search-based subscriptions for specific queries "
+ "or topic-based subscriptions for broader areas of interest. "
+ "Click 'Create Subscription' to get started.",
+ "impact_score": 8,
+ "time_ago": "Just now",
+ "upvotes": 0,
+ "downvotes": 0,
+ "source_url": None,
+ "topics": ["Subscriptions", "Personalization", "Features"],
+ },
+ {
+ "id": "welcome-3",
+ "headline": "Search for Breaking News and Analysis",
+ "category": "Features",
+ "summary": "Use the search bar to find the latest news on any topic. "
+ "Our AI analyzes multiple sources to provide comprehensive "
+ "coverage and insights. Try searching for 'technology breakthroughs' "
+ "or click 'Today's Breaking News' for a curated table.",
+ "impact_score": 8,
+ "time_ago": "Just now",
+ "upvotes": 0,
+ "downvotes": 0,
+ "source_url": None,
+ "topics": ["Search", "Analysis", "Features"],
+ },
+ ]
+
+ return welcome_items
diff --git a/src/local_deep_research/news/recommender/topic_based.py b/src/local_deep_research/news/recommender/topic_based.py
new file mode 100644
index 0000000000..c4176dfb22
--- /dev/null
+++ b/src/local_deep_research/news/recommender/topic_based.py
@@ -0,0 +1,354 @@
+"""
+Topic-based recommender that generates recommendations from news topics.
+This is the primary recommender for v1.
+"""
+
+from typing import List, Dict, Any, Optional
+from loguru import logger
+
+from .base_recommender import BaseRecommender
+from ..core.base_card import NewsCard
+from ..core.priority_manager import get_priority_manager
+from ..core.news_analyzer import NewsAnalyzer
+from ..core.card_factory import CardFactory
+from ...search_system import AdvancedSearchSystem
+
+
+class TopicBasedRecommender(BaseRecommender):
+ """
+ Recommends news based on topics extracted from recent news analysis.
+
+ This recommender:
+ 1. Gets recent news topics from the topic registry
+ 2. Filters based on user preferences
+ 3. Generates search queries for interesting topics
+ 4. Creates NewsCards from the results
+ """
+
+ def __init__(self, **kwargs):
+ """Initialize the topic-based recommender."""
+ super().__init__(**kwargs)
+ self.max_recommendations = 5 # Default limit
+
+ def generate_recommendations(
+ self, user_id: str, context: Optional[Dict[str, Any]] = None
+ ) -> List[NewsCard]:
+ """
+ Generate recommendations based on trending topics.
+
+ Args:
+ user_id: User to generate recommendations for
+ context: Optional context like current news being viewed
+
+ Returns:
+ List of NewsCard recommendations
+ """
+ logger.info(
+ f"Generating topic-based recommendations for user {user_id}"
+ )
+
+ # Check if we can run (priority system)
+ priority_manager = get_priority_manager()
+ if not priority_manager.can_start_news_search():
+ logger.warning(
+ "Cannot generate recommendations - user search in progress"
+ )
+ return []
+
+ recommendations = []
+
+ try:
+ # Update progress
+ self._update_progress("Getting trending topics", 10)
+
+ # Get trending topics
+ trending_topics = self._get_trending_topics(context)
+
+ # Filter by user preferences
+ self._update_progress("Applying user preferences", 30)
+ preferences = self._get_user_preferences(user_id)
+ filtered_topics = self._filter_topics_by_preferences(
+ trending_topics, preferences
+ )
+
+ # Generate recommendations for top topics
+ self._update_progress("Generating news searches", 50)
+
+ for i, topic in enumerate(
+ filtered_topics[: self.max_recommendations]
+ ):
+ progress = 50 + (
+ 40 * i / len(filtered_topics[: self.max_recommendations])
+ )
+ self._update_progress(f"Searching for: {topic}", int(progress))
+
+ # Create search query
+ query = self._generate_topic_query(topic)
+
+ # Register with priority manager
+ try:
+ # Generate unique search ID
+ import uuid
+
+ search_id = f"news-{uuid.uuid4().hex[:8]}-{i}"
+
+ # Register the search
+ can_proceed = priority_manager.register_news_search(
+ search_id
+ )
+
+ # Execute search if allowed
+ if can_proceed:
+ card = self._create_recommendation_card(
+ topic, query, user_id
+ )
+ if card:
+ recommendations.append(card)
+
+ # Unregister search
+ priority_manager.unregister_news_search(search_id)
+
+ except Exception as e:
+ logger.error(
+ f"Error creating recommendation for topic '{topic}': {e}"
+ )
+ continue
+
+ self._update_progress("Recommendations complete", 100)
+
+ # Sort by relevance
+ recommendations = self._sort_by_relevance(recommendations, user_id)
+
+ logger.info(
+ f"Generated {len(recommendations)} recommendations for user {user_id}"
+ )
+
+ except Exception as e:
+ logger.error(f"Error generating recommendations: {e}")
+ self._update_progress(f"Error: {str(e)}", 100)
+
+ return recommendations
+
+ def _get_trending_topics(
+ self, context: Optional[Dict[str, Any]]
+ ) -> List[str]:
+ """
+ Get trending topics to recommend.
+
+ Args:
+ context: Optional context
+
+ Returns:
+ List of trending topic strings
+ """
+ topics = []
+
+ # Get from topic registry if available
+ if self.topic_registry:
+ topics.extend(
+ self.topic_registry.get_trending_topics(hours=24, limit=20)
+ )
+
+ # Add context-based topics if provided
+ if context:
+ if "current_news_topics" in context:
+ topics.extend(context["current_news_topics"])
+ if "current_category" in context:
+ # Could fetch related topics based on category
+ pass
+
+ # Fallback topics if none found
+ if not topics:
+ logger.warning("No trending topics found, using defaults")
+ topics = [
+ "artificial intelligence developments",
+ "cybersecurity threats",
+ "climate change",
+ "economic policy",
+ "technology innovation",
+ ]
+
+ return topics
+
+ def _filter_topics_by_preferences(
+ self, topics: List[str], preferences: Dict[str, Any]
+ ) -> List[str]:
+ """
+ Filter topics based on user preferences.
+
+ Args:
+ topics: List of topics to filter
+ preferences: User preferences
+
+ Returns:
+ Filtered list of topics
+ """
+ filtered = []
+
+ # Get preference lists
+ disliked_topics = [
+ t.lower() for t in preferences.get("disliked_topics", [])
+ ]
+ interests = preferences.get("interests", {})
+
+ for topic in topics:
+ topic_lower = topic.lower()
+
+ # Skip disliked topics
+ if any(disliked in topic_lower for disliked in disliked_topics):
+ continue
+
+ # Boost topics matching interests
+ boost = 1.0
+ for interest, weight in interests.items():
+ if interest.lower() in topic_lower:
+ boost = weight
+ break
+
+ # Add with boost information
+ filtered.append((topic, boost))
+
+ # Sort by boost (highest first)
+ filtered.sort(key=lambda x: x[1], reverse=True)
+
+ # Return just the topics
+ return [topic for topic, _ in filtered]
+
+ def _generate_topic_query(self, topic: str) -> str:
+ """
+ Generate a search query for a topic.
+
+ Args:
+ topic: The topic to search for
+
+ Returns:
+ Search query string
+ """
+ # Add news-specific context
+ return f"{topic} latest news today breaking developments"
+
+ def _create_recommendation_card(
+ self, topic: str, query: str, user_id: str
+ ) -> Optional[NewsCard]:
+ """
+ Create a news card from a topic recommendation.
+
+ Args:
+ topic: The topic
+ query: The search query used
+ user_id: The user ID
+
+ Returns:
+ NewsCard or None if search fails
+ """
+ try:
+ # Use news search strategy
+ search_system = AdvancedSearchSystem(strategy_name="news")
+
+ # Mark as news search to use priority system
+ results = search_system.analyze_topic(query, is_news_search=True)
+
+ if "error" in results:
+ logger.error(
+ f"Search failed for topic '{topic}': {results['error']}"
+ )
+ return None
+
+ # Check if we have news items directly from the search
+ news_items = results.get("news_items", [])
+
+ if not news_items:
+ # Fallback: Analyze results with NewsAnalyzer
+ analyzer = NewsAnalyzer()
+ news_data = analyzer.analyze_news(results.get("findings", []))
+ news_items = news_data.get("items", [])
+ else:
+ # Use the news items from search results
+ news_data = {
+ "items": news_items,
+ "item_count": len(news_items),
+ "big_picture": results.get("formatted_findings", ""),
+ "topics": [],
+ }
+
+ if not news_items:
+ logger.warning(f"No news items found for topic '{topic}'")
+ return None
+
+ # Create card using factory
+ # Use the most impactful news item as the main content
+ main_item = max(news_items, key=lambda x: x.get("impact_score", 0))
+
+ card = CardFactory.create_news_card_from_analysis(
+ news_item=main_item,
+ source_search_id=results.get("search_id"),
+ user_id=user_id,
+ additional_metadata={
+ "recommender": self.strategy_name,
+ "original_topic": topic,
+ "query_used": query,
+ "total_items_found": len(news_items),
+ "big_picture": news_data.get("big_picture", ""),
+ "topics_extracted": news_data.get("topics", []),
+ },
+ )
+
+ # Add the full analysis as the first version
+ if card:
+ card.add_version(
+ research_results={
+ "search_results": results,
+ "news_analysis": news_data,
+ "query": query,
+ "strategy": "news_aggregation",
+ },
+ query=query,
+ strategy="news_aggregation",
+ )
+
+ return card
+
+ except Exception as e:
+ import traceback
+
+ logger.error(
+ f"Error creating recommendation card for topic '{topic}': {e}"
+ )
+ logger.error(f"Traceback: {traceback.format_exc()}")
+ return None
+
+
+class SearchBasedRecommender(BaseRecommender):
+ """
+ Recommends news based on user's recent searches.
+ Only works if search tracking is enabled.
+ """
+
+ def generate_recommendations(
+ self, user_id: str, context: Optional[Dict[str, Any]] = None
+ ) -> List[NewsCard]:
+ """
+ Generate recommendations from user's search history.
+
+ Args:
+ user_id: User to generate recommendations for
+ context: Optional context
+
+ Returns:
+ List of NewsCard recommendations
+ """
+ logger.info(
+ f"Generating search-based recommendations for user {user_id}"
+ )
+
+ # This would need access to search history
+ # For now, return empty since search tracking is OFF by default
+ logger.warning(
+ "Search-based recommendations not available - search tracking is disabled"
+ )
+ return []
+
+ # Future implementation would:
+ # 1. Get user's recent searches
+ # 2. Transform them to news queries
+ # 3. Create recommendation cards
diff --git a/src/local_deep_research/news/subscription_manager/__init__.py b/src/local_deep_research/news/subscription_manager/__init__.py
new file mode 100644
index 0000000000..080e81dce2
--- /dev/null
+++ b/src/local_deep_research/news/subscription_manager/__init__.py
@@ -0,0 +1,15 @@
+"""News subscription manager module."""
+
+from .search_subscription import SearchSubscription, SearchSubscriptionFactory
+from .topic_subscription import TopicSubscription, TopicSubscriptionFactory
+from .base_subscription import BaseSubscription
+from .storage import SubscriptionStorage
+
+__all__ = [
+ "SearchSubscription",
+ "SearchSubscriptionFactory",
+ "TopicSubscription",
+ "TopicSubscriptionFactory",
+ "BaseSubscription",
+ "SubscriptionStorage",
+]
diff --git a/src/local_deep_research/news/subscription_manager/base_subscription.py b/src/local_deep_research/news/subscription_manager/base_subscription.py
new file mode 100644
index 0000000000..1334288994
--- /dev/null
+++ b/src/local_deep_research/news/subscription_manager/base_subscription.py
@@ -0,0 +1,248 @@
+"""
+Base class for all subscription types.
+Following LDR's pattern from BaseSearchStrategy.
+"""
+
+from abc import ABC, abstractmethod
+from datetime import datetime, timedelta
+from typing import Dict, Any, Optional
+from loguru import logger
+
+from ..core.utils import generate_subscription_id, utc_now
+from ..core.base_card import CardSource
+from .storage import SQLSubscriptionStorage
+
+
+class BaseSubscription(ABC):
+ """Abstract base class for all subscription types."""
+
+ def __init__(
+ self,
+ user_id: str,
+ source: CardSource,
+ query_or_topic: str,
+ refresh_interval_hours: int = 4,
+ subscription_id: Optional[str] = None,
+ ):
+ """
+ Initialize base subscription.
+
+ Args:
+ user_id: ID of the user who owns this subscription
+ source: Source information for tracking origin
+ query_or_topic: The query or topic to subscribe to
+ refresh_interval_hours: How often to check for updates
+ subscription_id: Optional ID, will generate if not provided
+ """
+ self.storage = SQLSubscriptionStorage()
+ self.id = subscription_id or generate_subscription_id()
+ self.user_id = user_id
+ self.source = source
+ self.query_or_topic = query_or_topic
+ self.refresh_interval_hours = refresh_interval_hours
+
+ # Timestamps
+ self.created_at = utc_now()
+ self.last_refreshed = None
+ self.next_refresh = self._calculate_next_refresh()
+
+ # Status
+ self.is_active = True
+ self.refresh_count = 0
+ self.error_count = 0
+ self.last_error = None
+
+ # Metadata
+ self.metadata: Dict[str, Any] = {}
+
+ # Subscription type (to be set by subclasses)
+ self.subscription_type = None
+
+ def _calculate_next_refresh(self) -> datetime:
+ """Calculate when this subscription should next be refreshed."""
+ if self.last_refreshed is None:
+ # For new subscriptions, next refresh is created_at + interval
+ return self.created_at + timedelta(
+ hours=self.refresh_interval_hours
+ )
+ return self.last_refreshed + timedelta(
+ hours=self.refresh_interval_hours
+ )
+
+ def should_refresh(self) -> bool:
+ """
+ Check if this subscription needs to be refreshed.
+
+ Returns:
+ bool: True if refresh is needed
+ """
+ if not self.is_active:
+ return False
+
+ return utc_now() >= self.next_refresh
+
+ def is_due_for_refresh(self) -> bool:
+ """Alias for should_refresh for backward compatibility."""
+ return self.should_refresh()
+
+ @abstractmethod
+ def generate_search_query(self) -> str:
+ """
+ Generate the search query for this subscription.
+ Must be implemented by subclasses.
+
+ Returns:
+ str: The search query to execute
+ """
+ pass
+
+ @abstractmethod
+ def get_subscription_type(self) -> str:
+ """
+ Get the type of this subscription.
+
+ Returns:
+ str: Subscription type identifier
+ """
+ pass
+
+ def on_refresh_start(self) -> None:
+ """Called when a refresh begins."""
+ logger.debug(f"Starting refresh for subscription {self.id}")
+ self.last_refreshed = utc_now()
+
+ def on_refresh_success(self, results: Any) -> None:
+ """
+ Called when a refresh completes successfully.
+
+ Args:
+ results: The results from the refresh
+ """
+ self.refresh_count += 1
+ self.next_refresh = self._calculate_next_refresh()
+ self.error_count = 0 # Reset error count on success
+ logger.debug(f"Subscription {self.id} refreshed successfully")
+
+ def on_refresh_error(self, error: Exception) -> None:
+ """
+ Called when a refresh fails.
+
+ Args:
+ error: The exception that occurred
+ """
+ self.error_count += 1
+ self.last_error = str(error)
+
+ # Exponential backoff for errors
+ backoff_hours = min(
+ self.refresh_interval_hours * (2**self.error_count),
+ 24 * 7, # Max 1 week
+ )
+ self.next_refresh = utc_now() + timedelta(hours=backoff_hours)
+
+ logger.error(f"Subscription {self.id} refresh failed: {error}")
+
+ # Disable after too many errors
+ if self.error_count >= 10:
+ self.is_active = False
+ logger.warning(f"Subscription {self.id} disabled after 10 errors")
+
+ def pause(self) -> None:
+ """Pause this subscription."""
+ self.is_active = False
+ logger.info(f"Subscription {self.id} paused")
+
+ def resume(self) -> None:
+ """Resume this subscription."""
+ self.is_active = True
+ self.error_count = 0 # Reset errors on resume
+ self.next_refresh = self._calculate_next_refresh()
+ logger.info(f"Subscription {self.id} resumed")
+
+ def update_interval(self, new_interval_hours: int) -> None:
+ """
+ Update the refresh interval.
+
+ Args:
+ new_interval_hours: New interval in hours
+ """
+ if new_interval_hours < 1:
+ raise ValueError("Refresh interval must be at least 1 hour")
+ if new_interval_hours > 24 * 30:
+ raise ValueError("Refresh interval cannot exceed 30 days")
+
+ self.refresh_interval_hours = new_interval_hours
+ self.next_refresh = self._calculate_next_refresh()
+
+ logger.info(
+ f"Subscription {self.id} interval updated to {new_interval_hours} hours"
+ )
+
+ def save(self) -> str:
+ """
+ Save subscription to database.
+
+ Returns:
+ str: The subscription ID
+ """
+ data = {
+ "id": self.id,
+ "user_id": self.user_id,
+ "subscription_type": self.get_subscription_type(),
+ "query_or_topic": self.query_or_topic,
+ "refresh_interval_hours": self.refresh_interval_hours,
+ "source_type": self.source.type,
+ "source_id": self.source.source_id,
+ "created_from": self.source.created_from,
+ "is_active": self.is_active,
+ "metadata": self.metadata,
+ "next_refresh": self.next_refresh,
+ "created_at": self.created_at,
+ }
+ return self.storage.create(data)
+
+ def mark_refreshed(self, results_count: int) -> None:
+ """
+ Update subscription after successful refresh.
+
+ Args:
+ results_count: Number of results found in this refresh
+ """
+ now = utc_now()
+ self.last_refreshed = now
+ self.next_refresh = self._calculate_next_refresh()
+ self.refresh_count += 1
+
+ # Update in database
+ self.storage.update_refresh_time(self.id, now, self.next_refresh)
+ self.storage.increment_stats(self.id, results_count)
+
+ logger.debug(
+ f"Subscription {self.id} marked as refreshed with {results_count} results"
+ )
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert subscription to dictionary representation."""
+ return {
+ "id": self.id,
+ "type": self.get_subscription_type(),
+ "user_id": self.user_id,
+ "query_or_topic": self.query_or_topic,
+ "source": {
+ "type": self.source.type,
+ "source_id": self.source.source_id,
+ "created_from": self.source.created_from,
+ "metadata": self.source.metadata,
+ },
+ "created_at": self.created_at.isoformat(),
+ "last_refreshed": self.last_refreshed.isoformat()
+ if self.last_refreshed
+ else None,
+ "next_refresh": self.next_refresh.isoformat(),
+ "refresh_interval_hours": self.refresh_interval_hours,
+ "is_active": self.is_active,
+ "refresh_count": self.refresh_count,
+ "error_count": self.error_count,
+ "last_error": self.last_error,
+ "metadata": self.metadata,
+ }
diff --git a/src/local_deep_research/news/subscription_manager/scheduler.py b/src/local_deep_research/news/subscription_manager/scheduler.py
new file mode 100644
index 0000000000..c0f9563153
--- /dev/null
+++ b/src/local_deep_research/news/subscription_manager/scheduler.py
@@ -0,0 +1,686 @@
+"""
+Subscription scheduler that manages automatic refresh of news subscriptions.
+Integrates with the priority manager to ensure user searches take precedence.
+"""
+
+import asyncio
+from datetime import datetime, timedelta
+from typing import List, Dict, Any, Optional
+from loguru import logger
+
+from ..core.storage_manager import StorageManager
+
+try:
+ from apscheduler.schedulers.background import BackgroundScheduler
+ from apscheduler.triggers.interval import IntervalTrigger
+
+ SCHEDULER_AVAILABLE = True
+except ImportError:
+ logger.warning(
+ "APScheduler not installed. Background subscription updates will not be available."
+ )
+ SCHEDULER_AVAILABLE = False
+ BackgroundScheduler = None
+
+from ..core.priority_manager import get_priority_manager
+from ..core.base_card import CardSource
+from ..core.card_factory import CardFactory
+from ..recommender.topic_based import TopicBasedRecommender
+from .base_subscription import BaseSubscription
+
+
+class SubscriptionScheduler:
+ """
+ Manages scheduled refresh of news subscriptions.
+
+ Features:
+ - Respects priority system (pauses for user searches)
+ - Handles multiple subscription types
+ - Batches updates for efficiency
+ - Error handling with backoff
+ """
+
+ def __init__(
+ self,
+ subscription_store: Optional[Any] = None,
+ search_system: Optional[Any] = None,
+ news_analyzer: Optional[Any] = None,
+ ):
+ """
+ Initialize the subscription scheduler.
+
+ Args:
+ subscription_store: Storage backend for subscriptions
+ search_system: LDR search system
+ news_analyzer: News analyzer for processing results
+ """
+ if not SCHEDULER_AVAILABLE:
+ raise ImportError(
+ "APScheduler is required for subscription scheduling. "
+ "Install with: pip install apscheduler"
+ )
+
+ # Use BackgroundScheduler for Flask app
+ from apscheduler.schedulers.background import BackgroundScheduler
+
+ self.scheduler = BackgroundScheduler()
+
+ # Create an event loop for async operations
+ self.loop = asyncio.new_event_loop()
+ self.async_thread = None
+ self.subscription_store = subscription_store
+ self.search_system = search_system
+ self.news_analyzer = news_analyzer
+
+ # State tracking
+ self.is_running = False
+ self.is_paused = False
+ self.active_refreshes: Dict[str, Any] = {}
+
+ # Configuration
+ self.batch_size = 5 # Process subscriptions in batches
+ self.check_interval_minutes = (
+ 5 # How often to check for due subscriptions
+ )
+
+ # Register with priority manager if method exists
+ try:
+ priority_manager = get_priority_manager()
+ if hasattr(priority_manager, "register_news_scheduler"):
+ priority_manager.register_news_scheduler(self)
+ else:
+ logger.warning(
+ "PriorityManager doesn't have register_news_scheduler method - scheduler won't pause for user searches"
+ )
+ except Exception as e:
+ logger.warning(f"Could not register with priority manager: {e}")
+
+ logger.info("Subscription scheduler initialized")
+
+ def start(self):
+ """Start the scheduler."""
+ if self.is_running:
+ logger.warning("Scheduler is already running")
+ return
+
+ # Schedule periodic subscription checks
+ self.scheduler.add_job(
+ self._check_subscriptions,
+ trigger=IntervalTrigger(minutes=self.check_interval_minutes),
+ id="subscription_checker",
+ replace_existing=True,
+ max_instances=1,
+ )
+
+ # Schedule cleanup of stale subscriptions
+ self.scheduler.add_job(
+ self._cleanup_stale_subscriptions,
+ trigger="cron",
+ hour=2, # Run at 2 AM daily
+ id="subscription_cleanup",
+ replace_existing=True,
+ )
+
+ # Start the async event loop in a separate thread
+ import threading
+
+ def run_event_loop():
+ asyncio.set_event_loop(self.loop)
+ self.loop.run_forever()
+
+ self.async_thread = threading.Thread(target=run_event_loop, daemon=True)
+ self.async_thread.start()
+
+ # Start the scheduler
+ self.scheduler.start()
+ self.is_running = True
+
+ # Schedule initial check after a short delay
+ self.scheduler.add_job(
+ self._check_subscriptions,
+ "date",
+ run_date=datetime.now() + timedelta(seconds=5),
+ id="initial_check",
+ )
+
+ logger.info(
+ f"Subscription scheduler started "
+ f"(checking every {self.check_interval_minutes} minutes)"
+ )
+
+ def stop(self):
+ """Stop the scheduler."""
+ if self.is_running:
+ self.scheduler.shutdown()
+ self.is_running = False
+
+ # Stop the event loop
+ if hasattr(self, "loop") and self.loop:
+ self.loop.call_soon_threadsafe(self.loop.stop)
+
+ # Wait for thread to finish
+ if hasattr(self, "async_thread") and self.async_thread:
+ self.async_thread.join(timeout=2)
+
+ logger.info("Subscription scheduler stopped")
+
+ def pause_all_activities(self):
+ """
+ Pause all subscription activities.
+ Called by priority manager when user search starts.
+ """
+ self.is_paused = True
+
+ # Cancel any active refreshes
+ for sub_id, task in self.active_refreshes.items():
+ if not task.done():
+ task.cancel()
+ logger.debug(f"Cancelled refresh for subscription {sub_id}")
+
+ self.active_refreshes.clear()
+ logger.info("All subscription activities paused")
+
+ def resume_all_activities(self, restart: bool = True):
+ """
+ Resume subscription activities.
+ Called by priority manager when user search completes.
+
+ Args:
+ restart: If True, restart checks from beginning
+ """
+ self.is_paused = False
+
+ if restart and self.is_running:
+ # Schedule immediate check
+ asyncio.create_task(self._check_subscriptions())
+
+ logger.info("Subscription activities resumed")
+
+ def _check_subscriptions(self):
+ """Periodic task to check and refresh due subscriptions."""
+ if self.is_paused:
+ logger.debug("Subscription check skipped - scheduler is paused")
+ return
+
+ try:
+ from ..core.priority_manager import get_priority_manager
+
+ priority_manager = get_priority_manager()
+ if (
+ hasattr(priority_manager, "can_start_news_search")
+ and not priority_manager.can_start_news_search()
+ ):
+ logger.debug(
+ "Subscription check skipped - user search in progress"
+ )
+ return
+ except Exception as e:
+ logger.warning(f"Could not check priority manager: {e}")
+
+ try:
+ logger.info("Checking subscriptions for refresh")
+
+ # Run the async method in the event loop
+ if hasattr(self, "loop") and self.loop:
+ # Run async code in the loop
+ future = asyncio.run_coroutine_threadsafe(
+ self._check_subscriptions_async(), self.loop
+ )
+ # Wait for completion with timeout
+ future.result(timeout=300) # 5 minute timeout
+ else:
+ # Fallback to simple database check
+ self._check_subscriptions_sync()
+
+ except Exception as e:
+ logger.error(f"Error in subscription check: {e}")
+
+ def _check_subscriptions_sync(self):
+ """Synchronous fallback for subscription checking."""
+ from ...web.models.database import get_db_connection
+
+ conn = get_db_connection()
+ cursor = conn.cursor()
+ cursor.execute("""
+ SELECT COUNT(*)
+ FROM news_subscriptions
+ WHERE status = 'active'
+ AND (next_refresh IS NULL OR next_refresh <= datetime('now'))
+ """)
+ count = cursor.fetchone()[0]
+ conn.close()
+
+ if count > 0:
+ logger.info(f"Found {count} subscriptions due for refresh")
+ # TODO: Implement actual refresh logic
+ else:
+ logger.debug("No subscriptions due for refresh")
+
+ async def _check_subscriptions_async(self):
+ """Async implementation of subscription checking."""
+ logger.debug("Running async subscription check")
+
+ try:
+ # Get due subscriptions
+ due_subscriptions = await self._get_due_subscriptions()
+
+ logger.info(
+ f"Found {len(due_subscriptions)} subscriptions due for refresh"
+ )
+
+ # Process in batches
+ for i in range(0, len(due_subscriptions), self.batch_size):
+ if self.is_paused:
+ break
+
+ batch = due_subscriptions[i : i + self.batch_size]
+ await self._process_subscription_batch(batch)
+
+ # Small delay between batches
+ await asyncio.sleep(1)
+
+ except Exception as e:
+ logger.error(f"Error in subscription check: {e}")
+
+ async def _get_due_subscriptions(self) -> List[Dict[str, Any]]:
+ """
+ Get subscriptions that are due for refresh.
+
+ Returns:
+ List of subscriptions needing refresh
+ """
+ # Query database directly for due subscriptions
+ from ...web.models.database import get_db_connection
+
+ try:
+ conn = get_db_connection()
+ conn.row_factory = lambda cursor, row: {
+ column[0]: row[idx]
+ for idx, column in enumerate(cursor.description)
+ }
+ cursor = conn.cursor()
+
+ query = """
+ SELECT * FROM news_subscriptions
+ WHERE status = 'active'
+ AND (next_refresh IS NULL OR next_refresh <= datetime('now'))
+ ORDER BY next_refresh ASC
+ """
+ cursor.execute(query)
+ subscriptions = cursor.fetchall()
+ conn.close()
+
+ return subscriptions
+
+ except Exception as e:
+ logger.error(f"Error getting due subscriptions: {e}")
+ return []
+
+ async def _process_subscription_batch(
+ self, subscriptions: List[Dict[str, Any]]
+ ):
+ """
+ Process a batch of subscriptions.
+
+ Args:
+ subscriptions: Subscriptions to refresh
+ """
+ for subscription in subscriptions:
+ if self.is_paused:
+ break
+
+ sub_id = subscription.get("id")
+ query = subscription.get("query_or_topic", "")
+
+ logger.info(f"Refreshing subscription {sub_id}: {query}")
+
+ try:
+ # Trigger research using the same endpoint as manual runs
+ await self._trigger_subscription_research(subscription)
+
+ # Update the next refresh time
+ await self._update_next_refresh(sub_id)
+
+ except Exception as e:
+ logger.error(f"Error refreshing subscription {sub_id}: {e}")
+
+ async def _refresh_subscription(self, subscription: BaseSubscription):
+ """
+ Refresh a single subscription.
+
+ Args:
+ subscription: The subscription to refresh
+ """
+ logger.info(
+ f"Refreshing subscription {subscription.id} ({subscription.get_subscription_type()})"
+ )
+
+ try:
+ # Mark refresh started
+ subscription.on_refresh_start()
+
+ # Generate search query
+ query = subscription.generate_search_query()
+
+ # Check if we can proceed
+ priority_manager = get_priority_manager()
+ search_id = priority_manager.register_news_search(
+ {
+ "query": query,
+ "subscription_id": subscription.id,
+ "user_id": subscription.user_id,
+ "type": "subscription_refresh",
+ }
+ )
+
+ try:
+ # Execute search if not cancelled
+ if not priority_manager.is_news_search_cancelled(search_id):
+ results = await self._execute_subscription_search(
+ subscription, query
+ )
+
+ # Process results
+ if results:
+ await self._process_subscription_results(
+ subscription, results
+ )
+
+ # Mark success
+ subscription.on_refresh_success(results)
+ else:
+ raise Exception("No results from search")
+ else:
+ logger.info(
+ f"Subscription refresh cancelled for {subscription.id}"
+ )
+
+ finally:
+ # Always unregister
+ priority_manager.unregister_news_search(search_id)
+
+ except Exception as e:
+ logger.error(
+ f"Error refreshing subscription {subscription.id}: {e}"
+ )
+ subscription.on_refresh_error(e)
+
+ finally:
+ # Remove from active refreshes
+ self.active_refreshes.pop(subscription.id, None)
+
+ async def _execute_subscription_search(
+ self, subscription: BaseSubscription, query: str
+ ) -> Optional[Dict[str, Any]]:
+ """
+ Execute search for a subscription.
+
+ Args:
+ subscription: The subscription
+ query: Search query
+
+ Returns:
+ Search results or None
+ """
+ if not self.search_system:
+ logger.error("No search system configured")
+ return None
+
+ try:
+ # Track this search with subscription metadata
+ from ...web.models.database import get_db_connection
+
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ # Create a research history entry with subscription metadata
+ import json
+ from datetime import datetime, timezone
+ import uuid
+
+ research_id = str(uuid.uuid4())
+ metadata = {
+ "subscription_id": subscription.id,
+ "triggered_by": "subscription",
+ "subscription_type": subscription.get_subscription_type(),
+ "is_news_search": True,
+ }
+
+ cursor.execute(
+ """
+ INSERT INTO research_history (uuid_id, query, mode, status, created_at, research_meta)
+ VALUES (?, ?, ?, ?, ?, ?)
+ """,
+ (
+ research_id,
+ query,
+ "quick",
+ "in_progress",
+ datetime.now(timezone.utc).isoformat(),
+ json.dumps(metadata),
+ ),
+ )
+ conn.commit()
+ conn.close()
+
+ # Use news aggregation strategy by default
+ results = self.search_system.analyze_topic(query)
+
+ # Update the research entry status
+ # (In production, this would be done by the search system)
+
+ return results
+
+ except Exception as e:
+ logger.error(
+ f"Search failed for subscription {subscription.id}: {e}"
+ )
+ return None
+
+ async def _process_subscription_results(
+ self, subscription: BaseSubscription, results: Dict[str, Any]
+ ):
+ """
+ Process search results for a subscription.
+
+ Args:
+ subscription: The subscription
+ results: Search results
+ """
+ logger.debug(f"Processing results for subscription {subscription.id}")
+
+ # Use TopicBasedRecommender to process results
+ if not hasattr(self, "recommender"):
+ self.recommender = TopicBasedRecommender()
+
+ # Generate recommendations from search results
+ context = {
+ "subscription_id": subscription.id,
+ "subscription_type": subscription.get_subscription_type(),
+ "search_results": results,
+ }
+
+ cards = self.recommender.generate_recommendations(
+ user_id=subscription.user_id, context=context
+ )
+
+ # Store cards using storage manager
+ storage = StorageManager()
+ card_factory = CardFactory()
+
+ for card_data in cards:
+ # Create card with proper source tracking
+ card = card_factory.create_card(
+ card_type="news",
+ content=card_data,
+ source=CardSource(
+ type="subscription",
+ source_id=subscription.id,
+ created_from=f"Subscription refresh: {subscription.get_display_name()}",
+ ),
+ )
+
+ # Store the card
+ storage.store_card(card)
+
+ # Update subscription activity
+ if hasattr(subscription, "update_activity"):
+ news_count = len(cards)
+ subscription.update_activity(news_count)
+
+ logger.info(
+ f"Stored {len(cards)} news items for subscription {subscription.id}"
+ )
+
+ async def _cleanup_stale_subscriptions(self):
+ """Periodic cleanup of inactive subscriptions."""
+ if self.is_paused:
+ return
+
+ logger.info("Running subscription cleanup")
+
+ try:
+ # This would query for stale subscriptions and:
+ # 1. Auto-expire inactive topic subscriptions
+ # 2. Disable subscriptions with too many errors
+ # 3. Clean up old data
+ pass
+
+ except Exception as e:
+ logger.error(f"Error in subscription cleanup: {e}")
+
+ async def force_refresh(self, subscription_id: str) -> Dict[str, Any]:
+ """
+ Force immediate refresh of a subscription.
+
+ Args:
+ subscription_id: ID of subscription to refresh
+
+ Returns:
+ Result of refresh attempt
+ """
+ # This would load the subscription and refresh it immediately
+ logger.info(
+ f"Force refresh requested for subscription {subscription_id}"
+ )
+
+ # Check if already being refreshed
+ if subscription_id in self.active_refreshes:
+ return {
+ "status": "already_refreshing",
+ "message": "Subscription is already being refreshed",
+ }
+
+ # Would load subscription and call _refresh_subscription
+ return {
+ "status": "not_implemented",
+ "message": "Force refresh not yet implemented",
+ }
+
+ async def _trigger_subscription_research(
+ self, subscription: Dict[str, Any]
+ ):
+ """Trigger a research process for a subscription."""
+ import aiohttp
+ from datetime import datetime
+
+ sub_id = subscription.get("id")
+ query = subscription.get("query_or_topic", "")
+
+ # Update any date placeholders with current date
+ current_date = datetime.now().strftime("%Y-%m-%d")
+
+ # Replace YYYY-MM-DD placeholder ONLY (not all dates)
+ query = query.replace("YYYY-MM-DD", current_date)
+
+ # Prepare the research request
+ research_data = {
+ "query": query,
+ "mode": "quick",
+ "metadata": {
+ "is_news_search": True,
+ "search_type": "news_analysis",
+ "display_in": "news_feed",
+ "subscription_id": sub_id,
+ "triggered_by": "scheduled_refresh",
+ "subscription_name": subscription.get("name", query[:50]),
+ "scheduled_at": datetime.utcnow().isoformat(),
+ "original_query": subscription.get(
+ "query_or_topic", ""
+ ), # Store original with placeholder
+ "processed_query": query, # Store processed query with replaced date
+ "news_date": current_date, # Store the actual date used
+ },
+ }
+
+ # Make the request to start research
+ # Since we're in a background thread, we need to make an HTTP request
+ async with aiohttp.ClientSession() as session:
+ try:
+ # Get configured host and port
+ from ....utilities.db_utils import get_db_setting
+ host = get_db_setting("web.host", "127.0.0.1")
+ port = get_db_setting("web.port", 5000)
+
+ async with session.post(
+ f"http://{host}:{port}/api/start_research",
+ json=research_data,
+ headers={"Content-Type": "application/json"},
+ ) as response:
+ if response.status == 200:
+ result = await response.json()
+ research_id = result.get("research_id")
+ logger.info(
+ f"Started research {research_id} for subscription {sub_id}"
+ )
+ else:
+ error_text = await response.text()
+ logger.error(
+ f"Failed to start research for subscription {sub_id}: {error_text}"
+ )
+ except Exception as e:
+ logger.error(
+ f"Error making research request for subscription {sub_id}: {e}"
+ )
+ raise
+
+ async def _update_next_refresh(self, subscription_id: str):
+ """Update the next refresh time for a subscription."""
+ from datetime import datetime, timedelta
+ from ...web.models.database import get_db_connection
+
+ try:
+ # Calculate next refresh time based on frequency
+ # Default to 24 hours for now
+ next_refresh = datetime.utcnow() + timedelta(hours=24)
+
+ conn = get_db_connection()
+ cursor = conn.cursor()
+ cursor.execute(
+ "UPDATE news_subscriptions SET next_refresh = ? WHERE id = ?",
+ (next_refresh.isoformat(), subscription_id),
+ )
+ conn.commit()
+ conn.close()
+
+ logger.debug(
+ f"Updated next refresh for subscription {subscription_id} to {next_refresh}"
+ )
+
+ except Exception as e:
+ logger.error(
+ f"Error updating next refresh for subscription {subscription_id}: {e}"
+ )
+
+ def get_status(self) -> Dict[str, Any]:
+ """Get scheduler status information."""
+ return {
+ "is_running": self.is_running,
+ "is_paused": self.is_paused,
+ "active_refreshes": len(self.active_refreshes),
+ "check_interval_minutes": self.check_interval_minutes,
+ "batch_size": self.batch_size,
+ "scheduler_jobs": [job.id for job in self.scheduler.get_jobs()]
+ if self.is_running
+ else [],
+ }
diff --git a/src/local_deep_research/news/subscription_manager/search_subscription.py b/src/local_deep_research/news/subscription_manager/search_subscription.py
new file mode 100644
index 0000000000..ce366e1a23
--- /dev/null
+++ b/src/local_deep_research/news/subscription_manager/search_subscription.py
@@ -0,0 +1,253 @@
+"""
+Search subscription - allows users to subscribe to their LDR searches for news updates.
+This is the killer feature: turning searches into living news feeds.
+"""
+
+from typing import Optional, Dict, Any
+from datetime import datetime
+from loguru import logger
+
+from .base_subscription import BaseSubscription
+from ..core.base_card import CardSource
+
+
+class SearchSubscription(BaseSubscription):
+ """
+ Subscription based on a user's search query.
+ Transforms the original search into news-focused queries.
+ """
+
+ def __init__(
+ self,
+ user_id: str,
+ query: str,
+ source: Optional[CardSource] = None,
+ refresh_interval_hours: int = 6,
+ transform_to_news_query: bool = True,
+ subscription_id: Optional[str] = None,
+ ):
+ """
+ Initialize a search subscription.
+
+ Args:
+ user_id: ID of the user
+ query: The original search query
+ source: Source information (auto-created if not provided)
+ refresh_interval_hours: How often to check for news
+ transform_to_news_query: Whether to add news context to query
+ subscription_id: Optional ID
+ """
+ # Create source if not provided
+ if source is None:
+ source = CardSource(
+ type="user_search", created_from=f"Search subscription: {query}"
+ )
+
+ super().__init__(
+ user_id, source, query, refresh_interval_hours, subscription_id
+ )
+
+ self.original_query = query
+ self.transform_to_news_query = transform_to_news_query
+
+ # Track query evolution over time
+ self.query_history = [query]
+ self.current_query = query
+
+ # Set subscription type
+ self.subscription_type = "search"
+
+ # Metadata specific to search subscriptions
+ self.metadata.update(
+ {
+ "subscription_type": "search",
+ "original_query": query,
+ "transform_enabled": transform_to_news_query,
+ }
+ )
+
+ logger.info(f"Created search subscription for query: {query}")
+
+ @property
+ def query(self) -> str:
+ """Get the original query for backward compatibility."""
+ return self.original_query
+
+ def get_subscription_type(self) -> str:
+ """Return the subscription type identifier."""
+ return "search_subscription"
+
+ def generate_search_query(self) -> str:
+ """
+ Generate the news search query from the original search.
+
+ Returns:
+ str: The transformed search query
+ """
+ # Update any date placeholders with current date
+ current_date = datetime.now().strftime("%Y-%m-%d")
+ updated_query = self.current_query
+
+ # Replace YYYY-MM-DD placeholder ONLY (not all dates)
+ updated_query = updated_query.replace("YYYY-MM-DD", current_date)
+
+ if self.transform_to_news_query:
+ # Add news context to the updated query
+ news_query = self._transform_to_news_query(updated_query)
+ else:
+ news_query = updated_query
+
+ logger.debug(f"Generated news query: {news_query}")
+ return news_query
+
+ def _transform_to_news_query(self, query: str) -> str:
+ """
+ Transform a regular search query into a news-focused query.
+
+ Args:
+ query: The original query
+
+ Returns:
+ str: News-focused version of the query
+ """
+ # Don't double-add news terms
+ query_lower = query.lower()
+ if any(
+ term in query_lower
+ for term in ["news", "latest", "recent", "today"]
+ ):
+ return query
+
+ # Add temporal and news context
+ # This could be more sophisticated with LLM in the future
+
+ # Choose appropriate term based on query type
+ if any(term in query_lower for term in ["how to", "tutorial", "guide"]):
+ # Technical queries - look for updates
+ return f"{query} latest updates developments"
+ elif any(
+ term in query_lower
+ for term in ["vulnerability", "security", "breach"]
+ ):
+ # Security queries - urgent news
+ return f"{query} breaking news alerts today"
+ else:
+ # General queries - latest news
+ return f"{query} latest news developments"
+
+ def evolve_query(self, new_terms: Optional[str] = None) -> None:
+ """
+ Evolve the query based on emerging trends.
+ Future feature: LLM-based query evolution.
+
+ Args:
+ new_terms: New terms to incorporate
+ """
+ if new_terms:
+ # Simple evolution for now
+ evolved_query = f"{self.original_query} {new_terms}"
+ self.current_query = evolved_query
+ self.query_history.append(evolved_query)
+
+ logger.info(f"Evolved search query to: {evolved_query}")
+
+ def get_statistics(self) -> Dict[str, Any]:
+ """Get statistics about this subscription."""
+ stats = {
+ "original_query": self.original_query,
+ "current_query": self.current_query,
+ "query_evolution_count": len(self.query_history) - 1,
+ "total_refreshes": self.refresh_count,
+ "success_rate": (
+ self.refresh_count / (self.refresh_count + self.error_count)
+ if (self.refresh_count + self.error_count) > 0
+ else 0
+ ),
+ }
+ return stats
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert to dictionary representation."""
+ data = super().to_dict()
+ data.update(
+ {
+ "original_query": self.original_query,
+ "current_query": self.current_query,
+ "transform_to_news_query": self.transform_to_news_query,
+ "query_history": self.query_history,
+ "statistics": self.get_statistics(),
+ }
+ )
+ return data
+
+
+class SearchSubscriptionFactory:
+ """
+ Factory for creating search subscriptions from various sources.
+ """
+
+ @staticmethod
+ def from_user_search(
+ user_id: str,
+ search_query: str,
+ search_result_id: Optional[str] = None,
+ **kwargs,
+ ) -> SearchSubscription:
+ """
+ Create a subscription from a user's search.
+
+ Args:
+ user_id: The user who performed the search
+ search_query: The original search query
+ search_result_id: Optional ID of the search result
+ **kwargs: Additional arguments for SearchSubscription
+
+ Returns:
+ SearchSubscription instance
+ """
+ source = CardSource(
+ type="user_search",
+ source_id=search_result_id,
+ created_from=f"Your search: '{search_query}'",
+ metadata={
+ "search_timestamp": kwargs.get("search_timestamp"),
+ "search_strategy": kwargs.get("search_strategy"),
+ },
+ )
+
+ return SearchSubscription(
+ user_id=user_id, query=search_query, source=source, **kwargs
+ )
+
+ @staticmethod
+ def from_recommendation(
+ user_id: str,
+ recommended_query: str,
+ recommendation_source: str,
+ **kwargs,
+ ) -> SearchSubscription:
+ """
+ Create a subscription from a system recommendation.
+
+ Args:
+ user_id: The user to create subscription for
+ recommended_query: The recommended search query
+ recommendation_source: What generated this recommendation
+ **kwargs: Additional arguments
+
+ Returns:
+ SearchSubscription instance
+ """
+ source = CardSource(
+ type="recommendation",
+ created_from=f"Recommended based on: {recommendation_source}",
+ metadata={
+ "recommendation_type": kwargs.get(
+ "recommendation_type", "topic_based"
+ )
+ },
+ )
+
+ return SearchSubscription(
+ user_id=user_id, query=recommended_query, source=source, **kwargs
+ )
diff --git a/src/local_deep_research/news/subscription_manager/storage.py b/src/local_deep_research/news/subscription_manager/storage.py
new file mode 100644
index 0000000000..ade5156807
--- /dev/null
+++ b/src/local_deep_research/news/subscription_manager/storage.py
@@ -0,0 +1,310 @@
+"""
+SQLAlchemy storage implementation for subscriptions.
+"""
+
+from typing import List, Optional, Dict, Any
+from datetime import datetime, timedelta, timezone
+from sqlalchemy.orm import Session
+from loguru import logger
+
+from ..core.storage import SubscriptionStorage
+from ..models import BaseSubscription, SubscriptionType, SubscriptionStatus
+from ..cache import NewsCache
+
+
+class SQLSubscriptionStorage(SubscriptionStorage):
+ """SQLAlchemy implementation of subscription storage"""
+
+ def __init__(self, session: Optional[Session] = None):
+ self.cache = NewsCache()
+ self._session = session
+
+ @property
+ def session(self):
+ """Get database session"""
+ if self._session:
+ return self._session
+ # Use cache's session if no explicit session provided
+ return self.cache.get_session()
+
+ def create(self, data: Dict[str, Any]) -> str:
+ """Create a new subscription"""
+ subscription_id = data.get("id") or self.generate_id()
+
+ with self.session as session:
+ subscription = BaseSubscription(
+ id=subscription_id,
+ user_id=data["user_id"],
+ name=data.get("name"),
+ subscription_type=data["subscription_type"],
+ query_or_topic=data["query_or_topic"],
+ refresh_interval_hours=data.get("refresh_interval_hours", 6),
+ refresh_hours=data.get(
+ "refresh_hours", data.get("refresh_interval_hours", 6)
+ ),
+ frequency=data.get("frequency", "daily"),
+ source_type=data.get("source_type"),
+ source_id=data.get("source_id"),
+ created_from=data.get("created_from"),
+ folder=data.get("folder"),
+ folder_id=data.get("folder_id"),
+ notes=data.get("notes"),
+ status=data.get("status", "active"),
+ is_active=data.get("is_active", True),
+ next_refresh=datetime.now(timezone.utc)
+ + timedelta(hours=data.get("refresh_interval_hours", 6)),
+ )
+
+ session.add(subscription)
+ session.commit()
+
+ logger.info(
+ f"Created subscription {subscription_id} for user {data['user_id']}"
+ )
+ return subscription_id
+
+ def get(self, id: str) -> Optional[Dict[str, Any]]:
+ """Get a subscription by ID"""
+ with self.session as session:
+ subscription = (
+ session.query(BaseSubscription).filter_by(id=id).first()
+ )
+ if not subscription:
+ return None
+
+ # Convert to dict manually
+ return {
+ "id": subscription.id,
+ "user_id": subscription.user_id,
+ "name": subscription.name,
+ "subscription_type": subscription.subscription_type,
+ "query_or_topic": subscription.query_or_topic,
+ "refresh_interval_hours": subscription.refresh_interval_hours,
+ "created_at": subscription.created_at,
+ "updated_at": subscription.updated_at,
+ "last_refresh": subscription.last_refresh,
+ "next_refresh": subscription.next_refresh,
+ "expires_at": subscription.expires_at,
+ "source_type": subscription.source_type,
+ "source_id": subscription.source_id,
+ "created_from": subscription.created_from,
+ "folder": subscription.folder,
+ "notes": subscription.notes,
+ "status": subscription.status,
+ "refresh_count": subscription.refresh_count,
+ "results_count": subscription.results_count,
+ "last_error": subscription.last_error,
+ "error_count": subscription.error_count,
+ }
+
+ def update(self, id: str, data: Dict[str, Any]) -> bool:
+ """Update a subscription"""
+ with self.session as session:
+ subscription = (
+ session.query(BaseSubscription).filter_by(id=id).first()
+ )
+ if not subscription:
+ return False
+
+ # Update allowed fields
+ updateable_fields = [
+ "refresh_interval_hours",
+ "status",
+ "expires_at",
+ ]
+ for field in updateable_fields:
+ if field in data:
+ setattr(subscription, field, data[field])
+
+ # Recalculate next refresh if interval changed
+ if "refresh_interval_hours" in data:
+ subscription.next_refresh = datetime.now(
+ timezone.utc
+ ) + timedelta(hours=data["refresh_interval_hours"])
+
+ session.commit()
+ return True
+
+ def delete(self, id: str) -> bool:
+ """Delete a subscription"""
+ with self.session as session:
+ subscription = (
+ session.query(BaseSubscription).filter_by(id=id).first()
+ )
+ if not subscription:
+ return False
+
+ session.delete(subscription)
+ session.commit()
+ return True
+
+ def list(
+ self,
+ filters: Optional[Dict[str, Any]] = None,
+ limit: int = 100,
+ offset: int = 0,
+ ) -> List[Dict[str, Any]]:
+ """List subscriptions with optional filtering"""
+ with self.session as session:
+ query = session.query(BaseSubscription)
+
+ if filters:
+ if "user_id" in filters:
+ query = query.filter_by(user_id=filters["user_id"])
+ if "status" in filters:
+ query = query.filter_by(
+ status=SubscriptionStatus(filters["status"])
+ )
+ if "subscription_type" in filters:
+ query = query.filter_by(
+ subscription_type=SubscriptionType(
+ filters["subscription_type"]
+ )
+ )
+
+ subscriptions = query.limit(limit).offset(offset).all()
+ # Detach from session and convert to dicts
+ result = []
+ for sub in subscriptions:
+ session.expunge(sub)
+ result.append(
+ {
+ "id": sub.id,
+ "user_id": sub.user_id,
+ "name": sub.name,
+ "subscription_type": sub.subscription_type,
+ "query_or_topic": sub.query_or_topic,
+ "refresh_interval_hours": sub.refresh_interval_hours,
+ "created_at": sub.created_at,
+ "updated_at": sub.updated_at,
+ "last_refresh": sub.last_refresh,
+ "next_refresh": sub.next_refresh,
+ "status": sub.status,
+ "folder": sub.folder,
+ "notes": sub.notes,
+ }
+ )
+ return result
+
+ def get_active_subscriptions(
+ self, user_id: Optional[str] = None
+ ) -> List[Dict[str, Any]]:
+ """Get all active subscriptions"""
+ with self.session as session:
+ query = session.query(BaseSubscription).filter_by(
+ status=SubscriptionStatus.ACTIVE
+ )
+
+ if user_id:
+ query = query.filter_by(user_id=user_id)
+
+ subscriptions = query.all()
+ return [sub.to_dict() for sub in subscriptions]
+
+ def get_due_subscriptions(self, limit: int = 100) -> List[Dict[str, Any]]:
+ """Get subscriptions that are due for refresh"""
+ with self.session as session:
+ now = datetime.now(timezone.utc)
+
+ subscriptions = (
+ session.query(BaseSubscription)
+ .filter(
+ BaseSubscription.status == SubscriptionStatus.ACTIVE,
+ BaseSubscription.next_refresh <= now,
+ )
+ .limit(limit)
+ .all()
+ )
+
+ return [sub.to_dict() for sub in subscriptions]
+
+ def update_refresh_time(
+ self,
+ subscription_id: str,
+ last_refresh: datetime,
+ next_refresh: datetime,
+ ) -> bool:
+ """Update refresh timestamps after processing"""
+ with self.session as session:
+ subscription = (
+ session.query(BaseSubscription)
+ .filter_by(id=subscription_id)
+ .first()
+ )
+ if not subscription:
+ return False
+
+ subscription.last_refresh = last_refresh
+ subscription.next_refresh = next_refresh
+ session.commit()
+ return True
+
+ def increment_stats(self, subscription_id: str, results_count: int) -> bool:
+ """Increment refresh count and update results count"""
+ with self.session as session:
+ subscription = (
+ session.query(BaseSubscription)
+ .filter_by(id=subscription_id)
+ .first()
+ )
+ if not subscription:
+ return False
+
+ subscription.refresh_count += 1
+ subscription.total_runs = subscription.refresh_count # Keep in sync
+ subscription.results_count = results_count
+ session.commit()
+ return True
+
+ def pause_subscription(self, subscription_id: str) -> bool:
+ """Pause a subscription"""
+ with self.session as session:
+ subscription = (
+ session.query(BaseSubscription)
+ .filter_by(id=subscription_id)
+ .first()
+ )
+ if not subscription:
+ return False
+
+ subscription.status = SubscriptionStatus.PAUSED
+ session.commit()
+ return True
+
+ def resume_subscription(self, subscription_id: str) -> bool:
+ """Resume a paused subscription"""
+ with self.session as session:
+ subscription = (
+ session.query(BaseSubscription)
+ .filter_by(id=subscription_id)
+ .first()
+ )
+ if (
+ not subscription
+ or subscription.status != SubscriptionStatus.PAUSED
+ ):
+ return False
+
+ subscription.status = SubscriptionStatus.ACTIVE
+ # Reset next refresh time
+ subscription.next_refresh = datetime.now(timezone.utc) + timedelta(
+ hours=subscription.refresh_interval_hours
+ )
+ session.commit()
+ return True
+
+ def expire_subscription(self, subscription_id: str) -> bool:
+ """Mark a subscription as expired"""
+ with self.session as session:
+ subscription = (
+ session.query(BaseSubscription)
+ .filter_by(id=subscription_id)
+ .first()
+ )
+ if not subscription:
+ return False
+
+ subscription.status = SubscriptionStatus.EXPIRED
+ subscription.expires_at = datetime.now(timezone.utc)
+ session.commit()
+ return True
diff --git a/src/local_deep_research/news/subscription_manager/topic_subscription.py b/src/local_deep_research/news/subscription_manager/topic_subscription.py
new file mode 100644
index 0000000000..0014cc43d5
--- /dev/null
+++ b/src/local_deep_research/news/subscription_manager/topic_subscription.py
@@ -0,0 +1,312 @@
+"""
+Topic subscription - allows users to subscribe to specific news topics.
+Topics are extracted from news analysis and can evolve over time.
+"""
+
+from typing import Optional, Dict, Any, List
+from datetime import datetime
+from loguru import logger
+
+from .base_subscription import BaseSubscription
+from ..core.base_card import CardSource
+from ..core.utils import utc_now
+
+
+class TopicSubscription(BaseSubscription):
+ """
+ Subscription to a specific news topic.
+ Topics can be extracted from news or manually created.
+ """
+
+ def __init__(
+ self,
+ topic: str,
+ user_id: str,
+ refresh_interval_hours: int = 4,
+ source: Optional[CardSource] = None,
+ related_topics: Optional[List[str]] = None,
+ subscription_id: Optional[str] = None,
+ ):
+ """
+ Initialize a topic subscription.
+
+ Args:
+ user_id: ID of the user
+ topic: The topic to follow
+ source: Source information (auto-created if not provided)
+ refresh_interval_hours: How often to check for updates
+ related_topics: Other topics related to this one
+ subscription_id: Optional ID
+ """
+ # Create source if not provided
+ if source is None:
+ source = CardSource(
+ type="news_topic", created_from=f"Topic subscription: {topic}"
+ )
+
+ super().__init__(
+ user_id, source, topic, refresh_interval_hours, subscription_id
+ )
+
+ self.topic = topic
+ self.related_topics = related_topics or []
+
+ # Set subscription type
+ self.subscription_type = "topic"
+
+ # Track topic evolution
+ self.topic_history = [topic]
+ self.current_topic = topic
+
+ # Track when topic was last significantly active
+ self.last_significant_activity = utc_now()
+ self.activity_threshold = 3 # Min news items to be "active"
+
+ # Metadata specific to topic subscriptions
+ self.metadata.update(
+ {
+ "subscription_type": "topic",
+ "original_topic": topic,
+ "is_trending": False,
+ "topic_category": None, # Will be set by analyzer
+ }
+ )
+
+ logger.info(f"Created topic subscription for: {topic}")
+
+ def get_subscription_type(self) -> str:
+ """Return the subscription type identifier."""
+ return "topic_subscription"
+
+ def generate_search_query(self) -> str:
+ """
+ Generate a search query for this topic.
+
+ Returns:
+ str: The search query for finding news about this topic
+ """
+ # Build query with main topic and related topics
+ query_parts = [self.current_topic]
+
+ # Add some related topics for broader coverage
+ if self.related_topics:
+ # Add up to 2 related topics
+ query_parts.extend(self.related_topics[:2])
+
+ # Combine with news-specific terms
+ base_query = " OR ".join(f'"{part}"' for part in query_parts)
+ news_query = f"{base_query} latest news today developments breaking"
+
+ # Update any date placeholders with current date
+ current_date = datetime.now().strftime("%Y-%m-%d")
+
+ # Replace YYYY-MM-DD placeholder ONLY (not all dates)
+ news_query = news_query.replace("YYYY-MM-DD", current_date)
+
+ logger.debug(f"Generated topic query: {news_query}")
+ return news_query
+
+ def update_activity(
+ self, news_count: int, significant_news: bool = False
+ ) -> None:
+ """
+ Update activity tracking for this topic.
+
+ Args:
+ news_count: Number of news items found
+ significant_news: Whether any news was particularly significant
+ """
+ if news_count >= self.activity_threshold or significant_news:
+ self.last_significant_activity = utc_now()
+ self.metadata["is_trending"] = True
+ else:
+ # Check if topic is becoming stale
+ hours_since_activity = (
+ utc_now() - self.last_significant_activity
+ ).total_seconds() / 3600
+
+ if hours_since_activity > 72: # 3 days
+ self.metadata["is_trending"] = False
+
+ def evolve_topic(
+ self, new_form: str, reason: str = "natural evolution"
+ ) -> None:
+ """
+ Evolve the topic to a new form.
+
+ Args:
+ new_form: The new form of the topic
+ reason: Why the topic evolved
+ """
+ if new_form != self.current_topic:
+ self.topic_history.append(new_form)
+ self.current_topic = new_form
+
+ self.metadata["last_evolution"] = {
+ "from": self.topic_history[-2],
+ "to": new_form,
+ "reason": reason,
+ "timestamp": utc_now().isoformat(),
+ }
+
+ logger.info(
+ f"Topic evolved from '{self.topic_history[-2]}' to '{new_form}' - {reason}"
+ )
+
+ def add_related_topic(self, topic: str) -> None:
+ """
+ Add a related topic.
+
+ Args:
+ topic: Related topic to add
+ """
+ if topic not in self.related_topics and topic != self.current_topic:
+ self.related_topics.append(topic)
+ logger.debug(
+ f"Added related topic '{topic}' to '{self.current_topic}'"
+ )
+
+ def merge_with(self, other_subscription: "TopicSubscription") -> None:
+ """
+ Merge another topic subscription into this one.
+ Useful when topics converge.
+
+ Args:
+ other_subscription: The subscription to merge
+ """
+ # Add the other topic as related
+ self.add_related_topic(other_subscription.current_topic)
+
+ # Merge related topics
+ for topic in other_subscription.related_topics:
+ self.add_related_topic(topic)
+
+ # Update metadata
+ self.metadata["merged_from"] = {
+ "topic": other_subscription.current_topic,
+ "subscription_id": other_subscription.id,
+ "timestamp": utc_now().isoformat(),
+ }
+
+ logger.info(
+ f"Merged topic '{other_subscription.current_topic}' into '{self.current_topic}'"
+ )
+
+ def should_auto_expire(self) -> bool:
+ """
+ Check if this subscription should auto-expire due to inactivity.
+
+ Returns:
+ bool: True if subscription should expire
+ """
+ # Don't expire if actively refreshing successfully
+ if self.error_count == 0 and self.refresh_count > 0:
+ # Check activity
+ days_inactive = (
+ utc_now() - self.last_significant_activity
+ ).total_seconds() / (24 * 3600)
+
+ # Expire after 30 days of no significant activity
+ return days_inactive > 30
+
+ return False
+
+ def get_statistics(self) -> Dict[str, Any]:
+ """Get statistics about this topic subscription."""
+ return {
+ "original_topic": self.topic,
+ "current_topic": self.current_topic,
+ "evolution_count": len(self.topic_history) - 1,
+ "related_topics_count": len(self.related_topics),
+ "is_trending": self.metadata.get("is_trending", False),
+ "days_since_activity": (
+ utc_now() - self.last_significant_activity
+ ).total_seconds()
+ / (24 * 3600),
+ "total_refreshes": self.refresh_count,
+ }
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert to dictionary representation."""
+ data = super().to_dict()
+ data.update(
+ {
+ "topic": self.topic,
+ "current_topic": self.current_topic,
+ "related_topics": self.related_topics,
+ "topic_history": self.topic_history,
+ "last_significant_activity": self.last_significant_activity.isoformat(),
+ "statistics": self.get_statistics(),
+ }
+ )
+ return data
+
+
+class TopicSubscriptionFactory:
+ """
+ Factory for creating topic subscriptions from various sources.
+ """
+
+ @staticmethod
+ def from_news_extraction(
+ user_id: str,
+ topic: str,
+ source_news_id: str,
+ related_topics: Optional[List[str]] = None,
+ **kwargs,
+ ) -> TopicSubscription:
+ """
+ Create a subscription from an extracted news topic.
+
+ Args:
+ user_id: The user creating the subscription
+ topic: The extracted topic
+ source_news_id: ID of the news item it came from
+ related_topics: Other related topics
+ **kwargs: Additional arguments
+
+ Returns:
+ TopicSubscription instance
+ """
+ source = CardSource(
+ type="news_topic",
+ source_id=source_news_id,
+ created_from=f"Topic from news analysis: {topic}",
+ metadata={
+ "extraction_timestamp": utc_now().isoformat(),
+ "extraction_method": kwargs.get("extraction_method", "llm"),
+ },
+ )
+
+ return TopicSubscription(
+ user_id=user_id,
+ topic=topic,
+ source=source,
+ related_topics=related_topics,
+ **kwargs,
+ )
+
+ @staticmethod
+ def from_user_interest(
+ user_id: str, topic: str, **kwargs
+ ) -> TopicSubscription:
+ """
+ Create a subscription from direct user interest.
+
+ Args:
+ user_id: The user
+ topic: Topic they're interested in
+ **kwargs: Additional arguments
+
+ Returns:
+ TopicSubscription instance
+ """
+ source = CardSource(
+ type="user_interest",
+ created_from=f"Your interest: {topic}",
+ metadata={"created_via": kwargs.get("created_via", "manual")},
+ )
+
+ return TopicSubscription(
+ user_id=user_id, topic=topic, source=source, **kwargs
+ )
diff --git a/src/local_deep_research/news/utils/__init__.py b/src/local_deep_research/news/utils/__init__.py
new file mode 100644
index 0000000000..b7faa0e958
--- /dev/null
+++ b/src/local_deep_research/news/utils/__init__.py
@@ -0,0 +1 @@
+"""News utilities package."""
diff --git a/src/local_deep_research/news/utils/headline_generator.py b/src/local_deep_research/news/utils/headline_generator.py
new file mode 100644
index 0000000000..beed97ece6
--- /dev/null
+++ b/src/local_deep_research/news/utils/headline_generator.py
@@ -0,0 +1,177 @@
+"""
+Headline generation utilities for news items.
+Uses LLM to generate concise, meaningful headlines from long queries and findings.
+"""
+
+from typing import Optional
+from loguru import logger
+
+
+def generate_headline(
+ query: str, findings: str = "", max_length: int = 100
+) -> str:
+ """
+ Generate a concise headline from a query and optional findings.
+
+ Args:
+ query: The search query or research question
+ findings: Optional findings/content to help generate better headline
+ max_length: Maximum length for the headline
+
+ Returns:
+ A concise headline string
+ """
+ # Always try LLM generation first for dynamic headlines based on actual content
+ llm_headline = _generate_with_llm(query, findings, max_length)
+ if llm_headline:
+ return llm_headline
+
+ # If query is already short enough, use it as fallback
+ if len(query) <= max_length:
+ return query.strip()
+
+ # If all else fails, truncate intelligently
+ return _truncate_intelligently(query, max_length)
+
+
+def _extract_simple_headline(query: str) -> Optional[str]:
+ """Extract headline from common query patterns."""
+ query_lower = query.lower()
+
+ # News table queries
+ if "CREATE TABLE" in query and "breaking news" in query_lower:
+ return "Today's Breaking News Analysis"
+
+ # Common news search patterns
+ patterns = {
+ "breaking news today": "Today's Breaking News",
+ "latest news stories": "Latest News Stories",
+ "news analysis": "News Analysis Report",
+ "find news about": "News Update",
+ "research news on": "News Research Report",
+ "analyze news": "News Analysis",
+ "top stories": "Top Stories Today",
+ "current events": "Current Events Analysis",
+ }
+
+ for pattern, headline in patterns.items():
+ if pattern in query_lower:
+ # Extract topic if possible
+ topic = _extract_topic(query, pattern)
+ if topic:
+ return f"{headline}: {topic}"
+ return headline
+
+ return None
+
+
+def _extract_topic(query: str, pattern: str) -> Optional[str]:
+ """Extract the main topic from a query after a pattern."""
+ query_lower = query.lower()
+ idx = query_lower.find(pattern)
+ if idx != -1:
+ # Get text after the pattern
+ remaining = query[idx + len(pattern) :].strip()
+ # Take first few words as topic
+ words = remaining.split()[:3]
+ if words:
+ topic = " ".join(words)
+ # Clean up common words
+ topic = (
+ topic.replace("about", "")
+ .replace("on", "")
+ .replace("the", "")
+ .strip()
+ )
+ if topic and len(topic) < 30:
+ return topic.title()
+ return None
+
+
+def _generate_with_llm(
+ query: str, findings: str, max_length: int
+) -> Optional[str]:
+ """Generate headline using LLM."""
+ try:
+ from ...config.llm_config import get_llm
+
+ # Use the configured model for headline generation
+ llm = get_llm(temperature=0.3)
+
+ # Focus only on the findings/report content, not the query
+ if not findings:
+ return None
+
+ # Use the COMPLETE findings - no character limit
+ findings_preview = findings
+
+ prompt = f"""Generate a comprehensive news headline that captures the key events from the research report below.
+
+Research Findings:
+{findings_preview}
+
+Requirements:
+- Include MULTIPLE major events if several important things happened (e.g., "Earthquake Strikes California While Wildfires Rage; Global Markets Tumble Amid Political Tensions")
+- Capture as much important information as possible in the headline
+- Be specific about locations, impacts, and key details
+- Professional news headline style but can be longer to include more information
+- Focus on the most impactful findings from the report
+- Use semicolons or commas to separate multiple major events
+- No quotes or punctuation at start/end
+- Base the headline ONLY on the actual findings in the report
+
+Generate only the headline text, nothing else."""
+
+ response = llm.invoke(prompt)
+ headline = response.content.strip()
+
+ # Clean up the generated headline
+ headline = headline.strip("\"'.,!?")
+
+ # Validate the headline
+ if headline:
+ logger.debug(f"Generated headline: {headline}")
+ return headline
+
+ except Exception as e:
+ logger.debug(f"LLM headline generation failed: {e}")
+
+ return None
+
+
+def _truncate_intelligently(query: str, max_length: int) -> str:
+ """Intelligently truncate a query to make a headline."""
+ # Remove common prefixes
+ prefixes_to_remove = [
+ "Find up to",
+ "Search for",
+ "Get information about",
+ "Research on",
+ "Analysis of",
+ "SEARCH STRATEGY:",
+ "CREATE TABLE:",
+ ]
+
+ truncated = query
+ for prefix in prefixes_to_remove:
+ if truncated.upper().startswith(prefix.upper()):
+ truncated = truncated[len(prefix) :].strip()
+
+ # Take first sentence or clause
+ for delimiter in [".", "?", "!", "\n", ":", ";", " - "]:
+ parts = truncated.split(delimiter)
+ if parts and parts[0].strip():
+ truncated = parts[0].strip()
+ if len(truncated) <= max_length:
+ return truncated
+
+ # If still too long, truncate at word boundary
+ if len(truncated) > max_length:
+ truncated = truncated[:max_length]
+ # Find last complete word
+ last_space = truncated.rfind(" ")
+ if last_space > max_length * 0.7: # Keep at least 70% of the length
+ truncated = truncated[:last_space]
+ return truncated.strip() + "..."
+
+ return truncated
diff --git a/src/local_deep_research/news/utils/topic_generator.py b/src/local_deep_research/news/utils/topic_generator.py
new file mode 100644
index 0000000000..f5bf7fe61b
--- /dev/null
+++ b/src/local_deep_research/news/utils/topic_generator.py
@@ -0,0 +1,245 @@
+"""
+Topic generation utilities for news items.
+Uses LLM to extract relevant topics/tags from news content.
+"""
+
+from loguru import logger
+from typing import List, Dict, Any
+import json
+
+
+def generate_topics(
+ query: str, findings: str = "", category: str = "", max_topics: int = 5
+) -> List[str]:
+ """
+ Generate relevant topics/tags from news content.
+
+ Args:
+ query: The search query or research question
+ findings: The research findings/content
+ category: The news category (if available)
+ max_topics: Maximum number of topics to generate
+
+ Returns:
+ List of topic strings
+ """
+ # Try LLM generation first
+ topics = _generate_with_llm(query, findings, category, max_topics)
+
+ # No fallback - if LLM fails, mark as missing
+ if not topics:
+ topics = ["[Topic generation failed]"]
+
+ # Ensure we have valid topics
+ return _validate_topics(topics, max_topics)
+
+
+def _generate_with_llm(
+ query: str, findings: str, category: str, max_topics: int
+) -> List[str]:
+ """Generate topics using LLM."""
+ try:
+ from ...config.llm_config import get_llm
+
+ # Use the configured model for topic generation
+ llm = get_llm(temperature=0.5)
+
+ # Prepare context
+ query_preview = query[:500] if len(query) > 500 else query
+ findings_preview = (
+ findings[:1000] if findings and len(findings) > 1000 else findings
+ )
+
+ prompt = f"""Extract relevant topics/tags from this news content.
+
+Query: {query_preview}
+{f"Content: {findings_preview}" if findings_preview else ""}
+{f"Category: {category}" if category else ""}
+
+Generate {max_topics} specific, relevant topics that would help categorize and filter this news item.
+
+Requirements:
+- Each topic should be 1-3 words
+- Topics should be specific and meaningful
+- Include geographic regions if mentioned
+- Include key entities (countries, organizations, people)
+- Include event types (conflict, economy, disaster, etc.)
+- Topics should be diverse and cover different aspects
+
+Return ONLY a JSON array of topic strings, like: ["Topic 1", "Topic 2", "Topic 3"]"""
+
+ response = llm.invoke(prompt)
+ content = response.content.strip()
+
+ # Try to parse the JSON response
+ try:
+ # Clean up common LLM response patterns
+ if content.startswith("```json"):
+ content = content[7:]
+ if content.endswith("```"):
+ content = content[:-3]
+ content = content.strip()
+
+ topics = json.loads(content)
+
+ if isinstance(topics, list):
+ # Clean and validate each topic
+ cleaned_topics = []
+ for topic in topics:
+ if isinstance(topic, str):
+ cleaned = topic.strip()
+ if cleaned and len(cleaned) <= 30: # Max topic length
+ cleaned_topics.append(cleaned)
+
+ logger.debug(f"Generated topics: {cleaned_topics}")
+ return cleaned_topics[:max_topics]
+
+ except json.JSONDecodeError:
+ logger.debug(f"Failed to parse LLM topics as JSON: {content}")
+ # Try to extract topics from plain text response
+ if "," in content:
+ topics = [t.strip().strip("\"'") for t in content.split(",")]
+ return [t for t in topics if t and len(t) <= 30][:max_topics]
+
+ except Exception as e:
+ logger.debug(f"LLM topic generation failed: {e}")
+
+ return []
+
+
+def _extract_fallback_topics(
+ query: str, findings: str, category: str
+) -> List[str]:
+ """Extract topics using pattern matching as fallback."""
+ topics = []
+
+ # Add category if provided
+ if category and category not in ["News", "General"]:
+ topics.append(category)
+
+ # Common news topics to look for
+ topic_patterns = {
+ # Geopolitical
+ "ukraine": "Ukraine",
+ "russia": "Russia",
+ "china": "China",
+ "united states": "United States",
+ "israel": "Israel",
+ "gaza": "Gaza",
+ "palestine": "Palestine",
+ "iran": "Iran",
+ # Event types
+ "conflict": "Conflict",
+ "war": "War",
+ "election": "Election",
+ "economy": "Economy",
+ "market": "Markets",
+ "disaster": "Disaster",
+ "earthquake": "Earthquake",
+ "flood": "Flooding",
+ "hurricane": "Hurricane",
+ "pandemic": "Pandemic",
+ "covid": "COVID-19",
+ # Sectors
+ "technology": "Technology",
+ "ai": "AI",
+ "climate": "Climate",
+ "energy": "Energy",
+ "health": "Healthcare",
+ "finance": "Finance",
+ "crypto": "Cryptocurrency",
+ # Organizations
+ "nato": "NATO",
+ "un": "United Nations",
+ "eu": "European Union",
+ "who": "WHO",
+ }
+
+ # Combine query and findings for analysis
+ text_to_analyze = (query + " " + findings).lower()
+
+ # Extract matching topics
+ for pattern, topic in topic_patterns.items():
+ if pattern in text_to_analyze and topic not in topics:
+ topics.append(topic)
+
+ # Extract year if mentioned
+ import re
+
+ years = re.findall(r"\b20\d{2}\b", text_to_analyze)
+ if years:
+ latest_year = max(years)
+ if latest_year not in topics:
+ topics.append(latest_year)
+
+ # Add "Breaking News" if it's a breaking news query
+ if "breaking" in text_to_analyze and "Breaking News" not in topics:
+ topics.append("Breaking News")
+
+ return topics
+
+
+def _validate_topics(topics: List[str], max_topics: int) -> List[str]:
+ """Validate and clean topics."""
+ valid_topics = []
+ seen = set()
+
+ for topic in topics:
+ if not topic:
+ continue
+
+ # Clean the topic
+ cleaned = topic.strip()
+
+ # Skip if too short or too long
+ if len(cleaned) < 2 or len(cleaned) > 30:
+ continue
+
+ # Skip duplicates (case-insensitive)
+ normalized = cleaned.lower()
+ if normalized in seen:
+ continue
+ seen.add(normalized)
+
+ valid_topics.append(cleaned)
+
+ if len(valid_topics) >= max_topics:
+ break
+
+ # Don't add default topics - show what actually happened
+ if not valid_topics:
+ valid_topics = ["[No valid topics]"]
+
+ return valid_topics
+
+
+def batch_generate_topics(
+ news_items: List[Dict[str, Any]], max_topics_per_item: int = 5
+) -> Dict[str, List[str]]:
+ """
+ Generate topics for multiple news items in batch.
+
+ Args:
+ news_items: List of news item dictionaries
+ max_topics_per_item: Maximum topics per news item
+
+ Returns:
+ Dictionary mapping news item IDs to topic lists
+ """
+ results = {}
+
+ for item in news_items:
+ item_id = item.get("id", "")
+ if not item_id:
+ continue
+
+ topics = generate_topics(
+ query=item.get("headline", ""),
+ findings=item.get("findings", ""),
+ category=item.get("category", ""),
+ max_topics=max_topics_per_item,
+ )
+
+ results[item_id] = topics
+
+ return results
diff --git a/src/local_deep_research/news/web.py b/src/local_deep_research/news/web.py
new file mode 100644
index 0000000000..80919ffe57
--- /dev/null
+++ b/src/local_deep_research/news/web.py
@@ -0,0 +1,87 @@
+"""
+Flask blueprint for news system web routes.
+"""
+
+from flask import Blueprint, jsonify, render_template
+from loguru import logger
+
+from ..utilities.db_utils import get_db_setting
+
+
+def create_news_blueprint():
+ """
+ Create Flask blueprint for news routes.
+
+ Returns:
+ Flask Blueprint instance with both page routes and API routes
+ """
+ bp = Blueprint("news", __name__)
+
+ # Import the Flask API blueprint
+ from .flask_api import news_api_bp
+
+ # Register the API blueprint as sub-blueprint
+ bp.register_blueprint(news_api_bp)
+
+ # Page routes
+ @bp.route("/")
+ def news_page():
+ """Render the main news page."""
+ # Get available strategies for dropdown
+ strategies = [
+ "topic_based",
+ "news_aggregation",
+ "source_based",
+ "focused_iteration",
+ ]
+
+ default_strategy = get_db_setting(
+ "news.recommender_strategy", "topic_based"
+ )
+
+ return render_template(
+ "pages/news.html",
+ strategies=strategies,
+ default_strategy=default_strategy,
+ )
+
+ @bp.route("/insights")
+ def insights_page():
+ """Render the news insights/transparency page."""
+ return render_template("pages/news_insights.html")
+
+ @bp.route("/preferences")
+ def preferences_page():
+ """Render the user preferences page."""
+ return render_template("pages/news_preferences.html")
+
+ @bp.route("/subscriptions")
+ def subscriptions_page():
+ """Render the subscriptions management page."""
+ return render_template("pages/subscriptions.html")
+
+ # Health check
+ @bp.route("/health")
+ def health_check():
+ """Check if news system is healthy."""
+ try:
+ # Check if database is accessible
+ from .core.storage_manager import StorageManager
+
+ storage = StorageManager()
+
+ # Try a simple query
+ storage.get_user_feed("health_check", limit=1)
+
+ return jsonify(
+ {
+ "status": "healthy",
+ "enabled": get_db_setting("news.enabled", True),
+ "database": "connected",
+ }
+ )
+ except Exception as e:
+ logger.error(f"Health check failed: {e}")
+ return jsonify({"status": "unhealthy", "error": str(e)}), 500
+
+ return bp
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index ed0e73f581..dd28f6de8f 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -50,6 +50,9 @@ from .advanced_search_system.strategies.source_based_strategy import (
from .advanced_search_system.strategies.standard_strategy import (
StandardSearchStrategy,
)
+from .advanced_search_system.strategies.news_strategy import (
+ NewsAggregationStrategy,
+)
from .citation_handler import CitationHandler
from .config.llm_config import get_llm
from .config.search_config import get_search
@@ -488,6 +491,13 @@ class AdvancedSearchSystem:
search=self.search,
all_links_of_system=self.all_links_of_system,
)
+ elif strategy_name.lower() in [
+ "news",
+ "news_aggregation",
+ "news-aggregation",
+ ]:
+ logger.info("Creating NewsAggregationStrategy instance")
+ self.strategy = NewsAggregationStrategy()
else:
logger.info("Creating StandardSearchStrategy instance")
self.strategy = StandardSearchStrategy(
@@ -519,13 +529,59 @@ class AdvancedSearchSystem:
if hasattr(self, "strategy"):
self.strategy.set_progress_callback(callback)
- def analyze_topic(self, query: str) -> Dict:
+ def analyze_topic(self, query: str, **kwargs) -> Dict:
"""Analyze a topic using the current strategy.
Args:
query: The research query to analyze
+ **kwargs: Additional arguments (is_user_search, is_news_search, user_id)
"""
+ # Import news integration if available
+ try:
+ from .news.core.priority_manager import (
+ get_priority_manager,
+ UserSearchContext,
+ )
+ from .news.core.search_integration import NewsSearchCallback
+
+ news_enabled = True
+ except ImportError:
+ news_enabled = False
+
+ # Determine search type
+ is_user_search = kwargs.get("is_user_search", True)
+ is_news_search = kwargs.get("is_news_search", False)
+ user_id = kwargs.get("user_id", "anonymous")
+ search_id = kwargs.get("search_id", None)
+
+ # Generate search ID if not provided
+ if search_id is None:
+ import uuid
+
+ search_id = str(uuid.uuid4())
+
+ # Handle priority if news system is enabled
+ if news_enabled and is_user_search and not is_news_search:
+ with UserSearchContext(search_id):
+ result = self._perform_search(
+ query, search_id, is_user_search, is_news_search, user_id
+ )
+ else:
+ result = self._perform_search(
+ query, search_id, is_user_search, is_news_search, user_id
+ )
+ return result
+
+ def _perform_search(
+ self,
+ query: str,
+ search_id: str,
+ is_user_search: bool,
+ is_news_search: bool,
+ user_id: str,
+ ) -> Dict:
+ """Perform the actual search."""
# Send progress message with LLM info
self.progress_callback(
f"Using {get_db_setting('llm.provider')} model: {get_db_setting('llm.model')}",
@@ -578,4 +634,23 @@ class AdvancedSearchSystem:
if "query" not in result:
result["query"] = query
result["questions_by_iteration"] = self.questions_by_iteration
+
+ # Call news callback if enabled
+ try:
+ from .news.core.search_integration import NewsSearchCallback
+
+ callback = NewsSearchCallback()
+ if callback.enabled:
+ context = {
+ "is_user_search": is_user_search,
+ "is_news_search": is_news_search,
+ "user_id": user_id,
+ "search_id": search_id,
+ }
+ callback(query, result, context)
+ except ImportError:
+ pass
+ except Exception as e:
+ logger.error(f"Error in news callback: {e}")
+
return result
diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.py
index 7423c04556..a88fff2969 100644
--- a/src/local_deep_research/web/app.py
+++ b/src/local_deep_research/web/app.py
@@ -96,6 +96,19 @@ def main():
host = get_db_setting("web.host", "0.0.0.0")
debug = get_db_setting("web.debug", True)
+ # Register shutdown handler for scheduler
+ import atexit
+
+ def shutdown_scheduler():
+ if hasattr(app, "news_scheduler") and app.news_scheduler:
+ try:
+ app.news_scheduler.stop()
+ logger.info("News subscription scheduler stopped gracefully")
+ except Exception as e:
+ logger.error(f"Error stopping scheduler: {e}")
+
+ atexit.register(shutdown_scheduler)
+
with app.app_context():
socketio.run(host, port, debug=debug)
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index e927b890d3..eff6726922 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -82,6 +82,46 @@ def create_app():
# Register socket service
socket_service = SocketIOService(app=app)
+ # Initialize news subscription scheduler if news is enabled
+ try:
+ from ..utilities.db_utils import get_db_setting
+
+ if get_db_setting("news.enabled", True):
+ # Initialize news database tables
+ from ..news.database import init_news_tables
+
+ if init_news_tables(db_path):
+ logger.info("News database tables initialized successfully")
+ else:
+ logger.warning("Failed to initialize news database tables")
+
+ from ..news.subscription_manager.scheduler import (
+ SubscriptionScheduler,
+ SCHEDULER_AVAILABLE,
+ )
+
+ if SCHEDULER_AVAILABLE:
+ # Create scheduler instance
+ scheduler = SubscriptionScheduler()
+ # Store in app context for later access
+ app.news_scheduler = scheduler
+ # Start the scheduler
+ scheduler.start()
+ logger.info("News subscription scheduler started successfully")
+ else:
+ logger.warning(
+ "APScheduler not available - subscription auto-refresh disabled. Install with: pip install apscheduler"
+ )
+ app.news_scheduler = None
+ else:
+ logger.info(
+ "News module disabled - subscription scheduler not started"
+ )
+ app.news_scheduler = None
+ except Exception as e:
+ logger.error(f"Failed to initialize news scheduler: {e}")
+ app.news_scheduler = None
+
# Apply middleware
apply_middleware(app)
@@ -175,6 +215,15 @@ def register_blueprints(app):
from .routes.settings_routes import settings_bp
from ..benchmarks.web_api.benchmark_routes import benchmark_bp
+ # Try to import news blueprint
+ try:
+ from ..news.web import create_news_blueprint
+ from ..utilities.db_utils import get_db_setting
+
+ news_available = True
+ except ImportError:
+ news_available = False
+
# Add root route
@app.route("/")
def index():
@@ -193,6 +242,11 @@ def register_blueprints(app):
) # Register API blueprint with prefix
app.register_blueprint(benchmark_bp) # Register benchmark blueprint
+ # Register news blueprint if available and enabled
+ if news_available and get_db_setting("news.enabled", True):
+ news_bp = create_news_blueprint()
+ app.register_blueprint(news_bp, url_prefix="/news")
+
# Register API v1 blueprint
app.register_blueprint(api_blueprint) # Already has url_prefix='/api/v1'
diff --git a/src/local_deep_research/web/database/migrations.py b/src/local_deep_research/web/database/migrations.py
index 4c1758512a..eddffac7e4 100644
--- a/src/local_deep_research/web/database/migrations.py
+++ b/src/local_deep_research/web/database/migrations.py
@@ -11,6 +11,24 @@ from .models import (
ResearchHistory,
)
+# Import news models for table creation
+try:
+ from ...news.models import (
+ BaseSubscription,
+ SubscriptionFolder,
+ UserPreference,
+ Rating,
+ NewsCard,
+ CardVersion,
+ )
+
+ NEWS_MODELS_AVAILABLE = True
+except ImportError:
+ NEWS_MODELS_AVAILABLE = False
+ logger.warning(
+ "News models not available - news tables will not be created"
+ )
+
def import_default_settings_file(db_session):
"""
@@ -67,6 +85,60 @@ def run_migrations(engine, db_session=None):
logger.info("Creating research table.")
Base.metadata.create_all(engine, tables=[ResearchHistory.__table__])
+ # Create news tables if available
+ if NEWS_MODELS_AVAILABLE:
+ from ...utilities.db_utils import get_db_setting
+
+ # Check if news is enabled (default to True)
+ news_enabled = True
+ if db_session:
+ try:
+ news_enabled = get_db_setting(
+ "news.enabled", True, db_session=db_session
+ )
+ except Exception:
+ # If we can't check the setting, default to enabled
+ news_enabled = True
+
+ if news_enabled:
+ # Import the news Base to ensure proper metadata
+ from ...news.models import Base as NewsBase
+
+ # Create news tables if they don't exist
+ if not inspector.has_table("news_subscriptions"):
+ logger.info("Creating news_subscriptions table")
+ NewsBase.metadata.create_all(
+ engine, tables=[BaseSubscription.__table__]
+ )
+
+ if not inspector.has_table("news_subscription_folders"):
+ logger.info("Creating news_subscription_folders table")
+ NewsBase.metadata.create_all(
+ engine, tables=[SubscriptionFolder.__table__]
+ )
+
+ if not inspector.has_table("news_user_preferences"):
+ logger.info("Creating news_user_preferences table")
+ NewsBase.metadata.create_all(
+ engine, tables=[UserPreference.__table__]
+ )
+
+ if not inspector.has_table("news_ratings"):
+ logger.info("Creating news_ratings table")
+ NewsBase.metadata.create_all(engine, tables=[Rating.__table__])
+
+ if not inspector.has_table("news_cards"):
+ logger.info("Creating news_cards table")
+ NewsBase.metadata.create_all(
+ engine, tables=[NewsCard.__table__]
+ )
+
+ if not inspector.has_table("news_card_versions"):
+ logger.info("Creating news_card_versions table")
+ NewsBase.metadata.create_all(
+ engine, tables=[CardVersion.__table__]
+ )
+
# Import existing settings from files
if db_session:
import_default_settings_file(db_session)
diff --git a/src/local_deep_research/web/routes/history_routes.py b/src/local_deep_research/web/routes/history_routes.py
index afda076b3b..5ac8a16c67 100644
--- a/src/local_deep_research/web/routes/history_routes.py
+++ b/src/local_deep_research/web/routes/history_routes.py
@@ -85,6 +85,13 @@ def get_history():
if "progress_log" not in item:
item["progress_log"] = "[]"
+ # Parse research_meta as metadata for the frontend
+ try:
+ metadata = json.loads(item["research_meta"])
+ item["metadata"] = metadata
+ except:
+ item["metadata"] = {}
+
# Ensure timestamps are in ISO format
if item["created_at"] and "T" not in item["created_at"]:
try:
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index 98d148f946..0412a9fc10 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -115,21 +115,96 @@ def llm_config_page():
@research_bp.route("/api/start_research", methods=["POST"])
def start_research():
data = request.json
+ logger.debug(f"Received research request: {json.dumps(data, indent=2)}")
+
+ # Check if this is a news search
+ metadata = data.get("metadata", {})
+ if metadata.get("is_news_search"):
+ logger.info(
+ f"News search request received: triggered_by={metadata.get('triggered_by', 'unknown')}"
+ )
+
query = data.get("query")
mode = data.get("mode", "quick")
- # Get model provider and model selections
- model_provider = data.get("model_provider", "OLLAMA")
+ # Replace date placeholders if they exist
+ if query and "YYYY-MM-DD" in query:
+ from datetime import datetime
+
+ # Use local system time
+ current_date = datetime.now().strftime("%Y-%m-%d")
+
+ original_query = query
+ query = query.replace("YYYY-MM-DD", current_date)
+ logger.info(
+ f"Replaced date placeholder in query: {original_query[:100]}... -> {query[:100]}..."
+ )
+ logger.info(f"Using date: {current_date}")
+
+ # Update metadata to track the replacement
+ if not metadata:
+ metadata = {}
+ metadata["original_query"] = original_query
+ metadata["processed_query"] = query
+ metadata["date_replaced"] = current_date
+ data["metadata"] = metadata
+
+ # Get parameters from request or use database settings
+ from ..services.settings_manager import SettingsManager
+
+ session = get_db_session()
+ settings_manager = SettingsManager(db_session=session)
+
+ # Get model provider and model selections - use database settings if not provided
+ model_provider = data.get("model_provider")
+ if not model_provider:
+ model_provider = settings_manager.get_setting("llm.provider", "OLLAMA")
+ logger.debug(
+ f"No model_provider in request, using database setting: {model_provider}"
+ )
+ else:
+ logger.debug(f"Using model_provider from request: {model_provider}")
+
model = data.get("model")
+ if not model:
+ model = settings_manager.get_setting("llm.model", None)
+ logger.debug(f"No model in request, using database setting: {model}")
+ else:
+ logger.debug(f"Using model from request: {model}")
+
custom_endpoint = data.get("custom_endpoint")
+ if not custom_endpoint and model_provider == "OPENAI_ENDPOINT":
+ custom_endpoint = settings_manager.get_setting(
+ "llm.openai_endpoint.url", None
+ )
+ logger.debug(
+ f"No custom_endpoint in request, using database setting: {custom_endpoint}"
+ )
search_engine = data.get("search_engine") or data.get("search_tool")
+ if not search_engine:
+ search_engine = settings_manager.get_setting("search.tool", "searxng")
+
max_results = data.get("max_results")
time_period = data.get("time_period")
+
iterations = data.get("iterations")
+ if iterations is None:
+ iterations = settings_manager.get_setting("search.iterations", 5)
+
questions_per_iteration = data.get("questions_per_iteration")
+ if questions_per_iteration is None:
+ questions_per_iteration = settings_manager.get_setting(
+ "search.questions_per_iteration", 5
+ )
+
+ # Get strategy from request or database
+ strategy = data.get("strategy")
+ if not strategy:
+ strategy = settings_manager.get_setting(
+ "search.search_strategy", "source-based"
+ )
- # Add strategy parameter with default value
- strategy = data.get("strategy", "source-based")
+ session.close()
# Log the selections for troubleshooting
logger.info(
@@ -155,7 +230,15 @@ def start_research():
)
if not model:
- return jsonify({"status": "error", "message": "Model is required"}), 400
+ logger.error(
+ f"No model specified or configured. Provider: {model_provider}"
+ )
+ return jsonify(
+ {
+ "status": "error",
+ "message": "Model is required. Please configure a model in the settings.",
+ }
+ ), 400
# Check if there's any active research that's actually still running
if active_research:
@@ -219,6 +302,11 @@ def start_research():
"questions_per_iteration": questions_per_iteration,
}
+ # Add any additional metadata from request
+ additional_metadata = data.get("metadata", {})
+ if additional_metadata:
+ research_settings.update(additional_metadata)
+
db_session = get_db_session()
with db_session:
research = ResearchHistory(
@@ -546,6 +634,7 @@ def get_history():
"created_at",
"completed_at",
"report_path",
+ "research_meta", # Include metadata
]
# Optionally include title if it exists
@@ -569,10 +658,21 @@ def get_history():
created_at = row_data["created_at"]
completed_at = row_data["completed_at"]
report_path = row_data["report_path"]
+ metadata_str = row_data.get("research_meta")
title = row_data.get(
"title", None
) # Use get to handle title not being present
+ # Parse metadata
+ metadata = {}
+ if metadata_str:
+ try:
+ metadata = json.loads(metadata_str)
+ except json.JSONDecodeError:
+ logger.warning(
+ f"Invalid metadata JSON for research {research_id}"
+ )
+
# Calculate duration if completed
duration_seconds = None
if completed_at and created_at:
@@ -593,6 +693,7 @@ def get_history():
"completed_at": completed_at,
"duration_seconds": duration_seconds,
"report_path": report_path,
+ "metadata": metadata, # Include parsed metadata
}
# Add title if not None
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 944813efca..ae357a0ac5 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -1,4 +1,5 @@
import hashlib
+import json
import threading
from datetime import datetime
from pathlib import Path
@@ -727,8 +728,6 @@ def run_research_process(
logger.info("Writing report to: %s", report_path)
with report_path.open("w", encoding="utf-8") as f:
- f.write("# Quick Research Summary\n\n")
- f.write(f"Query: {query}\n\n")
f.write(clean_markdown)
f.write("\n\n## Research Metrics\n")
f.write(
@@ -738,12 +737,6 @@ def run_research_process(
f"- Generated at: {datetime.utcnow().isoformat()}\n"
)
- # Update database
- metadata = {
- "iterations": results["iterations"],
- "generated_at": datetime.utcnow().isoformat(),
- }
-
# Calculate duration in seconds - using UTC consistently
now = datetime.utcnow()
completed_at = now.isoformat()
@@ -760,6 +753,37 @@ def run_research_process(
.first()
)
+ # Preserve existing metadata and update with new values
+ logger.info(
+ f"Existing research_meta type: {type(research.research_meta)}"
+ )
+ logger.info(
+ f"Existing research_meta value: {research.research_meta}"
+ )
+
+ # Handle both dict and string types for research_meta
+ if isinstance(research.research_meta, dict):
+ metadata = dict(research.research_meta)
+ elif isinstance(research.research_meta, str):
+ try:
+ metadata = json.loads(research.research_meta)
+ except json.JSONDecodeError:
+ logger.error(
+ f"Failed to parse research_meta as JSON: {research.research_meta}"
+ )
+ metadata = {}
+ else:
+ metadata = {}
+
+ logger.info(f"Metadata after loading: {metadata}")
+ metadata.update(
+ {
+ "iterations": results["iterations"],
+ "generated_at": datetime.utcnow().isoformat(),
+ }
+ )
+ logger.info(f"Metadata after update: {metadata}")
+
# Use the helper function for consistent duration calculation
duration_seconds = calculate_duration(
research.created_at, research.completed_at
@@ -769,9 +793,116 @@ def run_research_process(
research.completed_at = completed_at
research.duration_seconds = duration_seconds
research.report_path = str(report_path)
+
+ # Generate headline and topics only for news searches
+ if (
+ metadata.get("is_news_search")
+ or metadata.get("search_type") == "news_analysis"
+ ):
+ try:
+ from ...news.utils.headline_generator import (
+ generate_headline,
+ )
+ from ...news.utils.topic_generator import (
+ generate_topics,
+ )
+
+ # Read the report content for better headline/topic generation
+ report_content = ""
+ if report_path.exists():
+ report_content = report_path.read_text(
+ encoding="utf-8"
+ ) # Read FULL report, no truncation
+ logger.info(
+ f"Read {len(report_content)} chars from report for headline generation"
+ )
+ else:
+ logger.warning(
+ f"Report path does not exist: {report_path}"
+ )
+
+ # Generate headline
+ logger.info(
+ f"Generating headline for query: {query[:100]}"
+ )
+ headline = generate_headline(
+ query, report_content
+ )
+ metadata["generated_headline"] = headline
+
+ # Generate topics
+ logger.info(
+ f"Generating topics with category: {metadata.get('category', 'News')}"
+ )
+ topics = generate_topics(
+ query=query,
+ findings=report_content,
+ category=metadata.get("category", "News"),
+ max_topics=6,
+ )
+ metadata["generated_topics"] = topics
+
+ logger.info(f"Generated headline: {headline}")
+ logger.info(f"Generated topics: {topics}")
+
+ except Exception as e:
+ logger.warning(
+ f"Could not generate headline/topics: {e}"
+ )
+
+ logger.info(f"Final metadata being saved: {metadata}")
research.research_meta = metadata
db_session.commit()
+ logger.info(
+ f"Database commit completed for research_id: {research_id}"
+ )
+
+ # Update subscription if this was triggered by a subscription
+ if metadata.get("subscription_id"):
+ try:
+ from ...news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+ from datetime import (
+ datetime as dt,
+ timezone,
+ timedelta,
+ )
+
+ sub_storage = SQLSubscriptionStorage()
+ subscription_id = metadata["subscription_id"]
+
+ # Get subscription to find refresh interval
+ subscription = sub_storage.get(subscription_id)
+ if subscription:
+ refresh_hours = subscription.get(
+ "refresh_hours", 4
+ )
+ now = dt.now(timezone.utc)
+ next_refresh = now + timedelta(
+ hours=refresh_hours
+ )
+
+ # Update refresh times
+ sub_storage.update_refresh_time(
+ subscription_id=subscription_id,
+ last_refresh=now,
+ next_refresh=next_refresh,
+ )
+
+ # Increment stats
+ sub_storage.increment_stats(
+ subscription_id, 1
+ )
+
+ logger.info(
+ f"Updated subscription {subscription_id} refresh times"
+ )
+ except Exception as e:
+ logger.warning(
+ f"Could not update subscription refresh time: {e}"
+ )
logger.info(
f"Database updated successfully for research_id: {research_id}"
@@ -833,10 +964,6 @@ def run_research_process(
with report_path.open("w", encoding="utf-8") as f:
f.write(final_report["content"])
- # Update database
- metadata = final_report["metadata"]
- metadata["iterations"] = results["iterations"]
-
# Calculate duration in seconds - using UTC consistently
now = datetime.utcnow()
completed_at = now.isoformat()
@@ -849,6 +976,32 @@ def run_research_process(
.first()
)
+ # Preserve existing metadata and merge with report metadata
+ logger.info(
+ f"Full report - Existing research_meta type: {type(research.research_meta)}"
+ )
+ logger.info(
+ f"Full report - Existing research_meta value: {research.research_meta}"
+ )
+
+ # Handle both dict and string types for research_meta
+ if isinstance(research.research_meta, dict):
+ metadata = dict(research.research_meta)
+ elif isinstance(research.research_meta, str):
+ try:
+ metadata = json.loads(research.research_meta)
+ except json.JSONDecodeError:
+ logger.error(
+ f"Failed to parse research_meta as JSON: {research.research_meta}"
+ )
+ metadata = {}
+ else:
+ metadata = {}
+
+ logger.info(f"Full report - Metadata after loading: {metadata}")
+ metadata.update(final_report["metadata"])
+ metadata["iterations"] = results["iterations"]
+
# Use the helper function for consistent duration calculation
duration_seconds = calculate_duration(
research.created_at, research.completed_at
@@ -858,10 +1011,88 @@ def run_research_process(
research.completed_at = completed_at
research.duration_seconds = duration_seconds
research.report_path = str(report_path)
+
+ # Generate headline and topics only for news searches
+ if (
+ metadata.get("is_news_search")
+ or metadata.get("search_type") == "news_analysis"
+ ):
+ try:
+ from ..news.utils.headline_generator import (
+ generate_headline,
+ )
+ from ..news.utils.topic_generator import (
+ generate_topics,
+ )
+
+ # Read the report content for better headline/topic generation
+ report_content = ""
+ if report_path.exists():
+ report_content = report_path.read_text(
+ encoding="utf-8"
+ ) # Read FULL report, no truncation
+
+ # Generate headline
+ headline = generate_headline(query, report_content)
+ metadata["generated_headline"] = headline
+
+ # Generate topics
+ topics = generate_topics(
+ query=query,
+ findings=report_content,
+ category=metadata.get("category", "News"),
+ max_topics=6,
+ )
+ metadata["generated_topics"] = topics
+
+ logger.info(f"Generated headline: {headline}")
+ logger.info(f"Generated topics: {topics}")
+
+ except Exception as e:
+ logger.warning(
+ f"Could not generate headline/topics: {e}"
+ )
+
research.research_meta = metadata
db_session.commit()
+ # Update subscription if this was triggered by a subscription
+ if metadata.get("subscription_id"):
+ try:
+ from ...news.subscription_manager.storage import (
+ SQLSubscriptionStorage,
+ )
+ from datetime import datetime as dt, timezone, timedelta
+
+ sub_storage = SQLSubscriptionStorage()
+ subscription_id = metadata["subscription_id"]
+
+ # Get subscription to find refresh interval
+ subscription = sub_storage.get(subscription_id)
+ if subscription:
+ refresh_hours = subscription.get("refresh_hours", 4)
+ now = dt.now(timezone.utc)
+ next_refresh = now + timedelta(hours=refresh_hours)
+
+ # Update refresh times
+ sub_storage.update_refresh_time(
+ subscription_id=subscription_id,
+ last_refresh=now,
+ next_refresh=next_refresh,
+ )
+
+ # Increment stats
+ sub_storage.increment_stats(subscription_id, 1)
+
+ logger.info(
+ f"Updated subscription {subscription_id} refresh times"
+ )
+ except Exception as e:
+ logger.warning(
+ f"Could not update subscription refresh time: {e}"
+ )
+
progress_callback(
"Research completed successfully",
100,
@@ -969,8 +1200,24 @@ def run_research_process(
enhanced_report_content = None
report_path_to_save = None
- # Update metadata with more context about the error
- metadata = {"phase": "error", "error": user_friendly_error}
+ # Get existing metadata from database first
+ existing_metadata = {}
+ try:
+ db_session = get_db_session()
+ with db_session:
+ research = (
+ db_session.query(ResearchHistory)
+ .filter_by(id=research_id)
+ .first()
+ )
+ if research and research.research_meta:
+ existing_metadata = dict(research.research_meta)
+ except Exception:
+ logger.exception("Failed to get existing metadata")
+
+ # Update metadata with more context about the error while preserving existing values
+ metadata = existing_metadata
+ metadata.update({"phase": "error", "error": user_friendly_error})
if error_context:
metadata.update(error_context)
if enhanced_report_content:
diff --git a/src/local_deep_research/web/static/css/news-enhanced.css b/src/local_deep_research/web/static/css/news-enhanced.css
new file mode 100644
index 0000000000..1978e01678
--- /dev/null
+++ b/src/local_deep_research/web/static/css/news-enhanced.css
@@ -0,0 +1,434 @@
+/* Enhanced News Page Styles - Modern Design Update */
+
+/* Import base news styles */
+@import 'news.css';
+
+/* Enhanced Color Variables */
+:root {
+ --news-gradient-1: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
+ --news-gradient-2: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
+ --news-gradient-3: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
+ --news-gradient-4: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
+ --news-card-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
+ --news-card-hover-shadow: 0 15px 40px rgba(0, 0, 0, 0.15);
+ --news-border-radius: 16px;
+}
+
+/* Enhanced News Container */
+.news-container {
+ padding: 1.5rem;
+ background: linear-gradient(135deg, var(--bg-primary) 0%, rgba(100, 108, 255, 0.02) 100%);
+}
+
+/* Enhanced News Cards */
+.news-item {
+ background: var(--bg-secondary);
+ border-radius: var(--news-border-radius);
+ padding: 1.5rem;
+ margin-bottom: 1.5rem;
+ border: 1px solid transparent;
+ box-shadow: var(--news-card-shadow);
+ transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
+ position: relative;
+ overflow: hidden;
+}
+
+.news-item::before {
+ content: '';
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 3px;
+ background: var(--news-gradient-1);
+ opacity: 0;
+ transition: opacity 0.3s ease;
+}
+
+.news-item:hover::before {
+ opacity: 1;
+}
+
+.news-item:hover {
+ transform: translateY(-4px);
+ box-shadow: var(--news-card-hover-shadow);
+ border-color: rgba(100, 108, 255, 0.2);
+}
+
+/* Enhanced Headlines */
+.news-headline {
+ font-size: 1.4rem;
+ font-weight: 700;
+ margin-bottom: 1rem;
+ background: linear-gradient(135deg, var(--text-primary) 0%, rgba(100, 108, 255, 0.9) 100%);
+ -webkit-background-clip: text;
+ -webkit-text-fill-color: transparent;
+ background-clip: text;
+ line-height: 1.5;
+ transition: all 0.3s ease;
+}
+
+.news-item:hover .news-headline {
+ background: var(--news-gradient-1);
+ -webkit-background-clip: text;
+ -webkit-text-fill-color: transparent;
+ background-clip: text;
+}
+
+/* Enhanced Meta Information */
+.news-meta {
+ display: flex;
+ align-items: center;
+ gap: 1.5rem;
+ margin-bottom: 1rem;
+ padding-bottom: 1rem;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.1);
+}
+
+.news-category {
+ background: var(--news-gradient-1);
+ color: white;
+ padding: 0.4rem 1rem;
+ border-radius: 20px;
+ font-size: 0.85rem;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
+}
+
+.news-impact {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ font-size: 0.9rem;
+ color: var(--text-secondary);
+}
+
+.impact-bar {
+ width: 60px;
+ height: 6px;
+ background: rgba(255, 255, 255, 0.1);
+ border-radius: 3px;
+ overflow: hidden;
+ position: relative;
+}
+
+.impact-fill {
+ height: 100%;
+ background: var(--news-gradient-2);
+ border-radius: 3px;
+ transition: width 0.6s ease;
+}
+
+/* Enhanced News Content */
+.news-content {
+ background: rgba(255, 255, 255, 0.02);
+ border-radius: 12px;
+ padding: 1.25rem;
+ margin: 1rem 0;
+ border: 1px solid rgba(255, 255, 255, 0.05);
+}
+
+.news-table {
+ width: 100%;
+ border-collapse: separate;
+ border-spacing: 0;
+ overflow: hidden;
+ border-radius: 8px;
+}
+
+.news-table th {
+ background: linear-gradient(135deg, rgba(100, 108, 255, 0.1) 0%, rgba(100, 108, 255, 0.05) 100%);
+ padding: 0.75rem 1rem;
+ text-align: left;
+ font-weight: 600;
+ color: var(--text-primary);
+ border-bottom: 2px solid rgba(100, 108, 255, 0.2);
+}
+
+.news-table td {
+ padding: 0.75rem 1rem;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.05);
+}
+
+.news-table tr:hover td {
+ background: rgba(100, 108, 255, 0.05);
+}
+
+/* Enhanced Source Links */
+.news-sources {
+ background: rgba(100, 108, 255, 0.05);
+ border-radius: 12px;
+ padding: 1rem;
+ margin: 1rem 0;
+ border: 1px solid rgba(100, 108, 255, 0.1);
+}
+
+.news-sources h6 {
+ color: var(--accent-primary);
+ font-weight: 600;
+ margin-bottom: 0.5rem;
+ font-size: 0.9rem;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+}
+
+.source-link {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ padding: 0.5rem 0;
+ color: var(--text-secondary);
+ text-decoration: none;
+ transition: all 0.3s ease;
+}
+
+.source-link:hover {
+ color: var(--accent-primary);
+ transform: translateX(4px);
+}
+
+.source-link i {
+ font-size: 0.85rem;
+ opacity: 0.7;
+}
+
+/* Enhanced Action Buttons */
+.news-actions {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-top: 1.5rem;
+ padding-top: 1.5rem;
+ border-top: 1px solid rgba(255, 255, 255, 0.1);
+}
+
+.vote-buttons {
+ display: flex;
+ gap: 1rem;
+}
+
+.vote-btn {
+ background: rgba(255, 255, 255, 0.05);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ color: var(--text-secondary);
+ padding: 0.5rem 1rem;
+ border-radius: 8px;
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ cursor: pointer;
+ transition: all 0.3s ease;
+ font-size: 0.9rem;
+}
+
+.vote-btn:hover {
+ background: rgba(100, 108, 255, 0.1);
+ border-color: rgba(100, 108, 255, 0.3);
+ color: var(--accent-primary);
+ transform: translateY(-2px);
+}
+
+.vote-btn.active {
+ background: var(--accent-primary);
+ color: white;
+ border-color: var(--accent-primary);
+}
+
+.vote-count {
+ font-weight: 600;
+ margin-left: 0.25rem;
+}
+
+/* Enhanced View Report Button */
+.btn-primary {
+ background: var(--news-gradient-1);
+ border: none;
+ color: white;
+ padding: 0.75rem 1.5rem;
+ border-radius: 8px;
+ font-weight: 600;
+ text-decoration: none;
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5rem;
+ transition: all 0.3s ease;
+ box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
+}
+
+.btn-primary:hover {
+ transform: translateY(-2px);
+ box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
+ color: white;
+ text-decoration: none;
+}
+
+/* Enhanced Sidebar */
+.subscriptions-card {
+ background: var(--bg-secondary);
+ border-radius: var(--news-border-radius);
+ padding: 1.5rem;
+ box-shadow: var(--news-card-shadow);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+}
+
+.subscription-item {
+ background: rgba(100, 108, 255, 0.05);
+ border: 1px solid rgba(100, 108, 255, 0.1);
+ border-radius: 8px;
+ padding: 0.75rem 1rem;
+ margin-bottom: 0.5rem;
+ cursor: pointer;
+ transition: all 0.3s ease;
+}
+
+.subscription-item:hover {
+ background: rgba(100, 108, 255, 0.1);
+ border-color: rgba(100, 108, 255, 0.3);
+ transform: translateX(4px);
+}
+
+.subscription-item.active {
+ background: var(--accent-primary);
+ color: white;
+ border-color: var(--accent-primary);
+}
+
+/* Enhanced Search Box */
+.news-search-box {
+ background: var(--bg-secondary);
+ border-radius: var(--news-border-radius);
+ padding: 1.5rem;
+ margin-bottom: 1.5rem;
+ box-shadow: var(--news-card-shadow);
+}
+
+.search-input-group {
+ background: rgba(255, 255, 255, 0.05);
+ border: 2px solid transparent;
+ border-radius: 12px;
+ padding: 0.5rem;
+ transition: all 0.3s ease;
+}
+
+.search-input-group:focus-within {
+ background: rgba(100, 108, 255, 0.05);
+ border-color: var(--accent-primary);
+ box-shadow: 0 0 0 4px rgba(100, 108, 255, 0.1);
+}
+
+/* Enhanced Topic Pills */
+.topic-pill {
+ background: linear-gradient(135deg, rgba(100, 108, 255, 0.1) 0%, rgba(100, 108, 255, 0.05) 100%);
+ color: var(--accent-primary);
+ padding: 0.4rem 1rem;
+ border-radius: 20px;
+ font-size: 0.85rem;
+ font-weight: 600;
+ border: 1px solid rgba(100, 108, 255, 0.2);
+ cursor: pointer;
+ transition: all 0.3s ease;
+ white-space: nowrap;
+}
+
+.topic-pill:hover {
+ background: var(--accent-primary);
+ color: white;
+ transform: scale(1.05);
+ box-shadow: 0 4px 15px rgba(100, 108, 255, 0.3);
+}
+
+/* Enhanced Loading States */
+.skeleton-loader {
+ background: linear-gradient(90deg,
+ rgba(255, 255, 255, 0.05) 0%,
+ rgba(255, 255, 255, 0.1) 50%,
+ rgba(255, 255, 255, 0.05) 100%);
+ background-size: 200% 100%;
+ animation: skeleton-loading 1.5s ease-in-out infinite;
+}
+
+@keyframes skeleton-loading {
+ 0% {
+ background-position: 200% 0;
+ }
+ 100% {
+ background-position: -200% 0;
+ }
+}
+
+/* Enhanced Priority Indicators */
+.news-item.priority-high {
+ border-left: 4px solid transparent;
+ background: linear-gradient(90deg, rgba(250, 112, 154, 0.1) 0%, var(--bg-secondary) 10%);
+}
+
+.news-item.priority-high::after {
+ content: '⚡';
+ position: absolute;
+ top: 1rem;
+ right: 1rem;
+ font-size: 1.2rem;
+ opacity: 0.8;
+}
+
+.news-item.priority-medium {
+ border-left: 4px solid transparent;
+ background: linear-gradient(90deg, rgba(254, 225, 64, 0.1) 0%, var(--bg-secondary) 10%);
+}
+
+.news-item.priority-low {
+ border-left: 4px solid transparent;
+ background: linear-gradient(90deg, rgba(0, 242, 254, 0.1) 0%, var(--bg-secondary) 10%);
+}
+
+/* Enhanced Animations */
+.news-item {
+ animation: fadeInUp 0.6s ease-out forwards;
+ opacity: 0;
+}
+
+.news-item:nth-child(1) { animation-delay: 0.1s; }
+.news-item:nth-child(2) { animation-delay: 0.2s; }
+.news-item:nth-child(3) { animation-delay: 0.3s; }
+.news-item:nth-child(4) { animation-delay: 0.4s; }
+.news-item:nth-child(5) { animation-delay: 0.5s; }
+
+@keyframes fadeInUp {
+ from {
+ opacity: 0;
+ transform: translateY(20px);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
+/* Enhanced Responsive Design */
+@media (max-width: 768px) {
+ .news-item {
+ padding: 1rem;
+ margin-bottom: 1rem;
+ }
+
+ .news-headline {
+ font-size: 1.2rem;
+ }
+
+ .news-meta {
+ flex-wrap: wrap;
+ gap: 0.75rem;
+ }
+
+ .news-actions {
+ flex-direction: column;
+ gap: 1rem;
+ }
+
+ .vote-buttons {
+ width: 100%;
+ justify-content: space-around;
+ }
+}
diff --git a/src/local_deep_research/web/static/css/news.css b/src/local_deep_research/web/static/css/news.css
new file mode 100644
index 0000000000..14af1ca111
--- /dev/null
+++ b/src/local_deep_research/web/static/css/news.css
@@ -0,0 +1,1825 @@
+/* News Page Styles - Following LDR Design System */
+
+/* Import LDR color variables */
+:root {
+ --bg-primary: #121212;
+ --bg-secondary: #1e1e2d;
+ --bg-tertiary: #2a2a3a;
+ --accent-primary: #6e4ff6;
+ --accent-secondary: #9179f0;
+ --accent-tertiary: #40bfff;
+ --text-primary: #f5f5f5;
+ --text-secondary: #c0c0cc;
+ --text-muted: #8a8aa0;
+ --border-color: #343452;
+}
+
+/* Alert Container */
+.settings-alert-container {
+ display: none;
+ position: fixed;
+ top: 20px;
+ right: 20px;
+ z-index: 1000;
+}
+
+/* Page wrapper */
+.news-page-wrapper {
+ width: 100%;
+ padding: 0;
+ box-sizing: border-box;
+ background-color: var(--bg-primary);
+ min-height: 100vh;
+}
+
+/* Override Bootstrap white backgrounds */
+.modal-content {
+ background-color: var(--bg-secondary) !important;
+ color: var(--text-primary) !important;
+}
+
+.dropdown-menu {
+ background-color: var(--bg-secondary) !important;
+ border-color: var(--border-color) !important;
+}
+
+.dropdown-item {
+ color: var(--text-primary) !important;
+}
+
+.dropdown-item:hover {
+ background-color: var(--bg-tertiary) !important;
+}
+
+.form-control, .form-select {
+ background-color: var(--bg-tertiary) !important;
+ border-color: var(--border-color) !important;
+ color: var(--text-primary) !important;
+}
+
+.form-control:focus, .form-select:focus {
+ background-color: var(--bg-tertiary) !important;
+ border-color: var(--accent-primary) !important;
+ color: var(--text-primary) !important;
+ box-shadow: 0 0 0 0.2rem rgba(110, 79, 246, 0.25) !important;
+}
+
+/* Layout - Two column without left sidebar */
+.news-container {
+ display: grid;
+ grid-template-columns: 1fr 320px;
+ gap: 1.5rem;
+ height: calc(100vh - 140px);
+ margin-top: 1rem;
+ width: calc(100% - 2rem);
+ max-width: calc(100vw - 2rem);
+ box-sizing: border-box;
+ margin-left: 1rem;
+ margin-right: 1rem;
+}
+
+@media (max-width: 1400px) {
+ .news-container {
+ grid-template-columns: 1fr 280px;
+ gap: 1rem;
+ }
+}
+
+@media (max-width: 1200px) {
+ .news-container {
+ grid-template-columns: 1fr;
+ }
+
+ .subscriptions-card {
+ display: none;
+ }
+}
+
+/* Integrated Search Section */
+.integrated-search-section {
+ background: var(--bg-secondary);
+ border-radius: 12px;
+ padding: 1.5rem;
+ margin-bottom: 1.5rem;
+ border: 1px solid var(--border-color);
+}
+
+.search-input-group {
+ display: flex;
+ align-items: center;
+ background: var(--bg-tertiary);
+ border: 1px solid var(--border-color);
+ border-radius: 8px;
+ padding: 0.25rem;
+ transition: all 0.3s ease;
+}
+
+.search-input-group:focus-within {
+ border-color: var(--accent-primary);
+ box-shadow: 0 0 0 3px rgba(100, 108, 255, 0.1);
+}
+
+.search-icon {
+ padding: 0 0.75rem;
+ color: var(--text-secondary);
+}
+
+.search-input {
+ flex: 1;
+ background: transparent !important;
+ border: none !important;
+ padding: 0.5rem 0;
+ color: var(--text-primary);
+}
+
+.search-input:focus {
+ box-shadow: none !important;
+ outline: none;
+}
+
+.search-controls {
+ display: flex;
+ gap: 0.25rem;
+ padding-right: 0.25rem;
+}
+
+/* Removed search-type-select styles as dropdown was removed */
+
+.quick-actions-row {
+ display: flex;
+ gap: 0.75rem;
+ flex-wrap: wrap;
+}
+
+.quick-actions-row .btn {
+ min-width: 140px;
+ font-size: 0.9rem;
+}
+
+/* Query Template */
+.query-template {
+ margin-top: 1rem;
+ padding: 1rem;
+ background: var(--bg-tertiary);
+ border-radius: 6px;
+ border: 1px solid var(--border-color);
+}
+
+.template-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 0.5rem;
+}
+
+.template-header h3 {
+ font-size: 0.9rem;
+ margin: 0;
+}
+
+.template-content {
+ font-size: 0.75rem;
+ max-height: 200px;
+ overflow-y: auto;
+ margin: 0.5rem 0;
+ padding: 0.5rem;
+ background: var(--bg-primary);
+ border-radius: 4px;
+}
+
+.template-actions {
+ display: flex;
+ gap: 0.5rem;
+}
+
+/* View Options */
+.view-options {
+ margin-top: 1.5rem;
+ padding-top: 1.5rem;
+ border-top: 1px solid var(--border-color);
+}
+
+.view-options h3 {
+ font-size: 0.9rem;
+ margin-bottom: 1rem;
+ color: var(--text-secondary);
+}
+
+.option-group {
+ margin-bottom: 1rem;
+}
+
+.option-group label {
+ display: block;
+ margin-bottom: 0.5rem;
+ font-size: 0.85rem;
+ color: var(--text-secondary);
+}
+
+/* Toggle Switch */
+.toggle-switch {
+ display: flex;
+ align-items: center;
+ cursor: pointer;
+}
+
+.toggle-switch input {
+ display: none;
+}
+
+.toggle-slider {
+ width: 40px;
+ height: 20px;
+ background: var(--bg-tertiary);
+ border-radius: 20px;
+ position: relative;
+ transition: background 0.3s;
+ margin-right: 0.5rem;
+}
+
+.toggle-slider::after {
+ content: '';
+ position: absolute;
+ width: 16px;
+ height: 16px;
+ background: var(--text-secondary);
+ border-radius: 50%;
+ top: 2px;
+ left: 2px;
+ transition: transform 0.3s;
+}
+
+.toggle-switch input:checked + .toggle-slider {
+ background: var(--accent-primary);
+}
+
+.toggle-switch input:checked + .toggle-slider::after {
+ transform: translateX(20px);
+ background: var(--text-primary);
+}
+
+/* Feed Section */
+.news-feed-section {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ height: 100%;
+ overflow: hidden;
+}
+
+.feed-header-section {
+ background: var(--bg-secondary);
+ border-radius: 12px;
+ padding: 1.5rem;
+ margin-bottom: 1.5rem;
+ border: 1px solid var(--border-color);
+}
+
+.feed-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 1rem;
+}
+
+.feed-header h1 {
+ margin: 0;
+ font-size: 1.5rem;
+ color: var(--text-primary);
+}
+
+/* Search Container */
+.news-search-container {
+ display: flex;
+ gap: 1rem;
+ margin-bottom: 1.5rem;
+}
+
+.news-search-box {
+ flex: 1;
+ position: relative;
+ display: flex;
+ align-items: center;
+ background: var(--bg-tertiary);
+ border-radius: 8px;
+ border: 1px solid var(--border-color);
+ transition: all 0.3s ease;
+}
+
+.news-search-box:focus-within {
+ border-color: var(--accent-primary);
+ box-shadow: 0 0 0 3px rgba(110, 79, 246, 0.1);
+}
+
+.news-search-box .search-icon {
+ position: absolute;
+ left: 1rem;
+ color: var(--text-muted);
+ pointer-events: none;
+}
+
+.news-search-box input {
+ flex: 1;
+ background: transparent;
+ border: none;
+ padding: 0.75rem 1rem 0.75rem 2.5rem;
+ color: var(--text-primary);
+ font-size: 0.95rem;
+}
+
+.news-search-box input:focus {
+ outline: none;
+ box-shadow: none;
+}
+
+.news-search-box input::placeholder {
+ color: var(--text-muted);
+}
+
+#search-btn {
+ background: var(--accent-primary);
+ border: none;
+ padding: 0.75rem 1.5rem;
+ border-radius: 0 8px 8px 0;
+ font-weight: 500;
+ transition: all 0.3s ease;
+}
+
+#search-btn:hover {
+ background: var(--accent-secondary);
+}
+
+.search-type-select {
+ width: auto;
+ min-width: 150px;
+ background: var(--bg-tertiary);
+ border: 1px solid var(--border-color);
+ color: var(--text-primary);
+}
+
+.feed-controls {
+ display: flex;
+ gap: 0.5rem;
+}
+
+/* Horizontal Filters Bar */
+.filters-bar {
+ background: var(--bg-tertiary);
+ border-radius: 8px;
+ padding: 1rem;
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+}
+
+.filter-section {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ flex-wrap: wrap;
+}
+
+.subscriptions-section {
+ flex: 1;
+}
+
+/* Horizontal subscriptions */
+.subscriptions-horizontal {
+ display: flex;
+ gap: 0.5rem;
+ overflow-x: auto;
+ padding: 0.25rem 0;
+ flex: 1;
+ scrollbar-width: thin;
+ scrollbar-color: var(--accent-primary) var(--bg-secondary);
+}
+
+.subscriptions-horizontal::-webkit-scrollbar {
+ height: 6px;
+}
+
+.subscriptions-horizontal::-webkit-scrollbar-track {
+ background: var(--bg-secondary);
+ border-radius: 3px;
+}
+
+.subscriptions-horizontal::-webkit-scrollbar-thumb {
+ background: var(--accent-primary);
+ border-radius: 3px;
+}
+
+.subscriptions-horizontal .subscription-item {
+ padding: 0.375rem 0.75rem;
+ background: var(--bg-secondary);
+ border: 1px solid var(--border-color);
+ border-radius: 20px;
+ font-size: 0.85rem;
+ cursor: pointer;
+ transition: all 0.2s;
+ white-space: nowrap;
+ flex-shrink: 0;
+}
+
+.subscriptions-horizontal .subscription-item:hover {
+ background: var(--bg-tertiary);
+ border-color: var(--accent-primary);
+ transform: translateY(-1px);
+}
+
+.subscriptions-horizontal .subscription-item.active {
+ background: var(--accent-primary);
+ color: white;
+ border-color: var(--accent-primary);
+}
+
+/* Time and impact filters inline */
+.time-filter-group,
+.impact-filter-group {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+}
+
+.impact-slider {
+ width: 120px;
+}
+
+/* Query template integrated */
+.query-template-integrated {
+ margin-top: 1rem;
+ padding: 1rem;
+ background: var(--bg-tertiary);
+ border: 1px solid var(--accent-primary);
+ border-radius: 8px;
+ animation: slideDown 0.3s ease-out;
+}
+
+@keyframes slideDown {
+ from {
+ opacity: 0;
+ transform: translateY(-10px);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
+/* Priority Alert */
+.priority-alert {
+ padding: 1rem;
+ background: var(--warning-color);
+ color: #000; /* Black text on warning background */
+ border-radius: 6px;
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ font-weight: 500;
+}
+
+/* News Items */
+.news-items-card {
+ flex: 1;
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+}
+
+.news-items-card .card-content {
+ flex: 1;
+ overflow-y: auto;
+}
+
+.news-items {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+}
+
+/* Active research card */
+.active-research-card {
+ background: linear-gradient(135deg, var(--bg-secondary) 0%, rgba(110, 79, 246, 0.1) 100%);
+ border: 2px solid var(--accent-primary);
+ box-shadow: 0 0 20px rgba(110, 79, 246, 0.2);
+ position: relative;
+ overflow: hidden;
+}
+
+.active-research-card::before {
+ content: '';
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 3px;
+ background: linear-gradient(90deg,
+ var(--accent-primary) 0%,
+ var(--accent-secondary) 50%,
+ var(--accent-primary) 100%);
+ animation: shimmer 2s infinite;
+}
+
+@keyframes shimmer {
+ 0% { transform: translateX(-100%); }
+ 100% { transform: translateX(100%); }
+}
+
+.active-research-card .progress {
+ margin: 1rem 0;
+ height: 8px;
+ background: var(--bg-tertiary);
+ border-radius: 4px;
+ overflow: hidden;
+}
+
+.active-research-card .progress-bar {
+ height: 100%;
+ background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary));
+ transition: width 0.5s ease;
+}
+
+.spinning {
+ animation: spin 2s linear infinite;
+}
+
+@keyframes spin {
+ from { transform: rotate(0deg); }
+ to { transform: rotate(360deg); }
+}
+
+/* News Card */
+.news-item {
+ padding: 2.5rem;
+ background: var(--bg-tertiary);
+ border-radius: 12px;
+ border: 1px solid var(--border-color);
+ transition: all 0.2s;
+ position: relative;
+ cursor: pointer;
+ min-height: 350px;
+}
+
+/* Read/Unread states */
+.news-item.is-unread {
+ border-left: 4px solid var(--accent-primary);
+}
+
+.news-item.is-read {
+ opacity: 0.85;
+}
+
+.news-item.is-read .news-headline {
+ color: var(--text-secondary);
+}
+
+/* News item header */
+.news-item-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: flex-start;
+ margin-bottom: 0.75rem;
+}
+
+.news-actions-menu {
+ display: flex;
+ gap: 0.25rem;
+ align-items: center;
+}
+
+.news-actions-menu .dropdown {
+ position: relative;
+}
+
+.news-actions-menu .dropdown-menu {
+ background: var(--bg-secondary);
+ border: 1px solid var(--border-color);
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
+ min-width: 180px;
+}
+
+.news-actions-menu .dropdown-item {
+ color: var(--text-primary);
+ padding: 0.5rem 1rem;
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ transition: all 0.2s;
+}
+
+.news-actions-menu .dropdown-item:hover {
+ background: var(--bg-tertiary);
+ color: var(--text-primary);
+}
+
+.news-actions-menu .dropdown-item i {
+ width: 1.2rem;
+ text-align: center;
+}
+
+.news-actions-menu .dropdown-divider {
+ border-color: var(--border-color);
+ margin: 0.5rem 0;
+}
+
+.btn-ghost {
+ background: transparent;
+ border: none;
+ color: var(--text-secondary);
+ padding: 0.25rem 0.5rem;
+ cursor: pointer;
+ transition: all 0.2s;
+ border-radius: 4px;
+}
+
+.btn-ghost:hover {
+ background: var(--bg-secondary);
+ color: var(--text-primary);
+}
+
+/* Saved items indicator */
+.save-btn i.bi-bookmark-fill {
+ color: var(--warning-color);
+}
+
+.subscription-item .subscription-type {
+ font-size: 0.75rem;
+ font-weight: 600;
+ letter-spacing: 0.5px;
+ opacity: 0.7;
+}
+
+.expand-icon {
+ transition: transform 0.3s;
+}
+
+.news-item:hover {
+ border-color: var(--accent-primary);
+ box-shadow: var(--glow-effect);
+ transform: translateY(-2px);
+}
+
+/* New item styling */
+.news-item.is-new {
+ background: linear-gradient(135deg, var(--bg-tertiary) 0%, rgba(100, 108, 255, 0.05) 100%);
+ border-color: rgba(100, 108, 255, 0.3);
+ position: relative;
+ overflow: hidden;
+}
+
+.news-item.is-new::before {
+ content: '';
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 4px;
+ height: 100%;
+ background: linear-gradient(to bottom, var(--accent-primary), rgba(100, 108, 255, 0.3));
+ animation: newItemPulse 2s ease-in-out infinite;
+}
+
+.news-item.is-new .new-indicator {
+ position: absolute;
+ top: 1rem;
+ right: 1rem;
+ font-size: 0.75rem;
+ color: var(--accent-primary);
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ opacity: 0.8;
+ display: flex;
+ align-items: center;
+ gap: 0.25rem;
+}
+
+.news-item.is-new .new-indicator::before {
+ content: '•';
+ font-size: 1.2rem;
+ animation: pulseDot 1.5s ease-in-out infinite;
+}
+
+@keyframes newItemPulse {
+ 0%, 100% {
+ opacity: 1;
+ transform: scaleY(1);
+ }
+ 50% {
+ opacity: 0.7;
+ transform: scaleY(0.98);
+ }
+}
+
+@keyframes pulseDot {
+ 0%, 100% {
+ opacity: 1;
+ transform: scale(1);
+ }
+ 50% {
+ opacity: 0.5;
+ transform: scale(0.8);
+ }
+}
+
+/* Subtle animation when new items appear */
+.news-item.fade-in-new {
+ animation: fadeInNew 0.6s ease-out forwards;
+}
+
+@keyframes fadeInNew {
+ from {
+ opacity: 0;
+ transform: translateY(10px) scale(0.98);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0) scale(1);
+ }
+}
+
+.news-item.priority-high {
+ border-left: 4px solid var(--error-color);
+}
+
+.news-item.priority-medium {
+ border-left: 4px solid var(--warning-color);
+}
+
+.news-item.priority-low {
+ border-left: 4px solid var(--success-color);
+}
+
+.news-headline {
+ font-size: 1.6rem;
+ font-weight: 600;
+ margin-bottom: 1rem;
+ color: var(--text-primary);
+ line-height: 1.5;
+}
+
+.news-meta {
+ display: flex;
+ gap: 1rem;
+ margin-bottom: 1rem;
+ font-size: 0.95rem;
+ color: var(--text-secondary);
+}
+
+/* News content styles */
+.news-findings {
+ color: var(--text-primary);
+ line-height: 1.8;
+ margin: 1.5rem 0;
+ max-height: 600px;
+ overflow: hidden;
+ position: relative;
+ font-size: 1.1rem;
+ transition: max-height 0.5s ease;
+}
+
+/* News card styles for JavaScript-generated content */
+.news-card {
+ background: var(--bg-secondary);
+ color: var(--text-primary);
+ border: 1px solid var(--border-color);
+ padding: 2rem;
+ border-radius: 12px;
+ margin-bottom: 1.25rem;
+ position: relative;
+ min-height: 450px;
+}
+
+.news-title {
+ font-size: 1.6rem;
+ font-weight: 600;
+ margin-bottom: 1rem;
+ color: var(--text-primary);
+ line-height: 1.5;
+}
+
+.news-summary {
+ color: var(--text-primary);
+ line-height: 1.7;
+ margin: 1rem 0;
+ font-size: 0.95rem;
+}
+
+.news-summary p {
+ color: var(--text-primary);
+ margin: 0;
+}
+
+/* Ensure proper text color inheritance */
+#news-container,
+#news-feed-content {
+ color: var(--text-primary);
+}
+
+.news-card * {
+ color: inherit;
+}
+
+/* Expand/Collapse button */
+.expand-toggle-btn {
+ position: absolute;
+ bottom: 1.5rem;
+ right: 1.5rem;
+ background: var(--bg-tertiary);
+ border: 1px solid var(--border-color);
+ color: var(--accent-primary);
+ padding: 0.5rem 1rem;
+ border-radius: 6px;
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ font-size: 0.9rem;
+ transition: all 0.2s;
+ z-index: 10;
+}
+
+.expand-toggle-btn:hover {
+ background: var(--accent-primary);
+ color: white;
+ border-color: var(--accent-primary);
+ transform: translateY(-2px);
+}
+
+.expand-toggle-btn i {
+ transition: transform 0.3s;
+}
+
+.news-item.is-expanded .expand-toggle-btn i,
+.news-card.is-expanded .expand-toggle-btn i {
+ transform: rotate(180deg);
+}
+
+/* Expanded state styles */
+.news-item.is-expanded,
+.news-card.is-expanded {
+ min-height: auto;
+}
+
+.news-item.is-expanded .news-findings,
+.news-card.is-expanded .news-findings,
+.news-item.is-expanded .news-summary,
+.news-card.is-expanded .news-summary {
+ max-height: none;
+ overflow: visible;
+}
+
+.news-item.is-expanded .news-findings::after,
+.news-card.is-expanded .news-findings::after,
+.news-item.is-expanded .news-summary::after,
+.news-card.is-expanded .news-summary::after {
+ display: none;
+}
+
+.news-header h2 {
+ color: var(--text-primary);
+}
+
+.news-actions {
+ color: var(--text-primary);
+}
+
+/* Subscription Management Styles */
+.subscription-stats {
+ margin-bottom: 2rem;
+}
+
+.stat-card {
+ background: var(--bg-secondary);
+ padding: 1.5rem;
+ border-radius: 12px;
+ border: 1px solid var(--border-color);
+ transition: transform 0.2s ease;
+}
+
+.stat-card:hover {
+ transform: translateY(-2px);
+}
+
+.stat-card h3 {
+ font-size: 2rem;
+ font-weight: 600;
+ color: var(--accent-primary);
+ margin-bottom: 0.5rem;
+}
+
+.stat-card p {
+ margin: 0;
+ color: var(--text-secondary);
+ font-size: 0.9rem;
+}
+
+.subscriptions-container {
+ max-height: 500px;
+ overflow-y: auto;
+ padding: 1rem;
+}
+
+.subscription-card {
+ background: var(--bg-secondary);
+ padding: 1.25rem;
+ border-radius: 8px;
+ border: 1px solid var(--border-color);
+ transition: all 0.2s ease;
+}
+
+.subscription-card:hover {
+ border-color: var(--accent-primary);
+ box-shadow: 0 2px 8px rgba(110, 79, 246, 0.1);
+}
+
+.subscription-actions {
+ display: flex;
+ gap: 0.5rem;
+}
+
+.subscription-actions .btn {
+ padding: 0.25rem 0.5rem;
+ font-size: 0.875rem;
+}
+
+#folderTabs .nav-link {
+ color: var(--text-secondary);
+ border: 1px solid transparent;
+ background: transparent;
+ padding: 0.5rem 1rem;
+ border-radius: 8px 8px 0 0;
+}
+
+#folderTabs .nav-link:hover {
+ color: var(--text-primary);
+ background: var(--bg-tertiary);
+}
+
+#folderTabs .nav-link.active {
+ color: var(--accent-primary);
+ background: var(--bg-secondary);
+ border-color: var(--border-color);
+ border-bottom-color: var(--bg-secondary);
+}
+
+#folderTabs .badge {
+ font-size: 0.75rem;
+ padding: 0.125rem 0.375rem;
+}
+
+.news-findings::after {
+ content: '';
+ position: absolute;
+ bottom: 0;
+ left: 0;
+ width: 100%;
+ height: 60px;
+ background: linear-gradient(to bottom, transparent, var(--bg-tertiary));
+ pointer-events: none;
+ transition: opacity 0.3s;
+}
+
+/* Expanded state */
+.news-item.is-expanded .news-findings {
+ max-height: none;
+}
+
+.news-item.is-expanded .news-findings::after {
+ opacity: 0;
+}
+
+.news-findings p {
+ margin: 0.5rem 0;
+}
+
+.news-findings ul, .news-findings ol {
+ margin: 0.5rem 0;
+ padding-left: 1.5rem;
+}
+
+.news-findings strong {
+ font-weight: 600;
+ color: var(--text-primary);
+}
+
+.news-summary {
+ color: var(--text-secondary);
+ line-height: 1.8;
+ margin: 1.25rem 0;
+ font-size: 1.05rem;
+ max-height: 180px;
+ overflow: hidden;
+ position: relative;
+}
+
+.news-summary::after {
+ content: '';
+ position: absolute;
+ bottom: 0;
+ left: 0;
+ width: 100%;
+ height: 40px;
+ background: linear-gradient(to bottom, transparent, var(--bg-tertiary));
+ pointer-events: none;
+}
+
+.news-category {
+ padding: 0.25rem 0.5rem;
+ background: var(--bg-secondary);
+ border-radius: 4px;
+ font-weight: 500;
+}
+
+.impact-indicator {
+ display: flex;
+ align-items: center;
+ gap: 0.25rem;
+}
+
+.impact-bar {
+ width: 60px;
+ height: 4px;
+ background: var(--bg-secondary);
+ border-radius: 2px;
+ overflow: hidden;
+}
+
+.impact-fill {
+ height: 100%;
+ background: linear-gradient(to right, var(--success-color), var(--warning-color), var(--error-color));
+}
+
+.news-summary {
+ color: var(--text-secondary);
+ line-height: 1.5;
+ margin-bottom: 1rem;
+}
+
+.news-actions {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-top: 1.5rem;
+ padding-top: 1rem;
+ border-top: 1px solid var(--border-color);
+}
+
+.vote-buttons {
+ display: flex;
+ gap: 0.5rem;
+}
+
+.vote-btn {
+ padding: 0.4rem 1rem;
+ background: var(--bg-secondary) !important;
+ border: 1px solid var(--border-color);
+ border-radius: 6px;
+ color: var(--text-primary) !important; /* Changed from text-secondary for better contrast */
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ gap: 0.25rem;
+ transition: all 0.2s;
+ position: relative;
+ z-index: 2;
+}
+
+.vote-btn:hover {
+ background: var(--bg-tertiary);
+ color: var(--text-primary);
+}
+
+.vote-btn.voted {
+ background: var(--accent-primary);
+ color: white;
+ border-color: var(--accent-primary);
+}
+
+.action-buttons {
+ display: flex;
+ gap: 0.5rem;
+}
+
+.action-buttons .btn,
+.action-buttons a,
+.action-buttons button {
+ position: relative;
+ z-index: 2;
+}
+
+/* Search History */
+.recent-search-item {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ padding: 0.75rem;
+ background: var(--bg-secondary);
+ border-radius: 8px;
+ margin-bottom: 0.5rem;
+ cursor: pointer;
+ transition: all 0.2s;
+ border: 1px solid transparent;
+}
+
+.recent-search-item:hover {
+ background: var(--bg-tertiary);
+ border-color: var(--accent-primary);
+ transform: translateX(4px);
+}
+
+.recent-search-item i:first-child {
+ color: var(--accent-primary);
+ font-size: 1.1rem;
+}
+
+.recent-search-item i:last-child {
+ color: var(--text-secondary);
+ opacity: 0;
+ transition: opacity 0.2s;
+}
+
+.recent-search-item:hover i:last-child {
+ opacity: 1;
+}
+
+.recent-search-item .search-query {
+ font-weight: 500;
+ color: var(--text-primary);
+ margin-bottom: 0.25rem;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.recent-search-item .search-meta {
+ font-size: 0.75rem;
+ color: var(--text-secondary);
+}
+
+/* Table View */
+.news-table-container {
+ overflow-x: auto;
+}
+
+.news-table {
+ width: 100%;
+ border-collapse: collapse;
+}
+
+.news-table th {
+ background: var(--bg-tertiary);
+ padding: 1rem;
+ text-align: left;
+ font-weight: 600;
+ color: var(--text-primary);
+ border-bottom: 2px solid var(--border-color);
+ position: sticky;
+ top: 0;
+ z-index: 10;
+}
+
+.news-table td {
+ padding: 1rem;
+ border-bottom: 1px solid var(--border-color);
+ color: var(--text-secondary);
+ vertical-align: top;
+}
+
+.news-table tr:hover td {
+ background: var(--bg-tertiary);
+}
+
+.impact-badge {
+ display: inline-block;
+ padding: 0.25rem 0.5rem;
+ border-radius: 4px;
+ font-size: 0.85rem;
+ font-weight: 600;
+}
+
+.impact-high {
+ background: var(--error-color);
+ color: white;
+}
+
+.impact-medium {
+ background: var(--warning-color);
+ color: #000; /* Black text on warning background */
+}
+
+.impact-low {
+ background: var(--success-color);
+ color: white;
+}
+
+/* Subscriptions */
+.subscriptions-card {
+ height: fit-content;
+ max-height: calc(100vh - 160px);
+ overflow-y: auto;
+}
+
+.subscriptions-list {
+ margin-bottom: 1rem;
+ max-height: 300px;
+ overflow-y: auto;
+}
+
+.subscription-item {
+ padding: 0.75rem;
+ background: var(--bg-tertiary);
+ border-radius: 6px;
+ margin-bottom: 0.5rem;
+ cursor: pointer;
+ transition: all 0.2s;
+ border: 1px solid transparent;
+}
+
+.subscription-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+}
+
+.subscription-item:hover {
+ border-color: var(--accent-primary);
+}
+
+.subscription-item.active {
+ background: var(--accent-primary);
+ color: white;
+}
+
+.subscription-type {
+ font-size: 0.75rem;
+ opacity: 0.7;
+ text-transform: uppercase;
+}
+
+.subscription-query {
+ font-weight: 500;
+ margin: 0.25rem 0;
+}
+
+.subscription-meta {
+ font-size: 0.8rem;
+ opacity: 0.7;
+}
+
+/* News Topics */
+.news-topics {
+ margin: 0.5rem 0;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5rem;
+}
+
+/* Filter chips */
+.filter-group {
+ margin-bottom: 1.5rem;
+}
+
+.filter-label {
+ font-size: 0.85rem;
+ color: var(--text-secondary);
+ margin-bottom: 0.5rem;
+ font-weight: 500;
+}
+
+.filter-options {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5rem;
+}
+
+.filter-chip {
+ padding: 0.4rem 0.8rem;
+ background: var(--bg-secondary);
+ border: 1px solid var(--border-color);
+ border-radius: 20px;
+ font-size: 0.8rem;
+ cursor: pointer;
+ transition: all 0.2s;
+ color: var(--text-primary);
+}
+
+.filter-chip:hover {
+ background: var(--bg-tertiary);
+ border-color: var(--accent-primary);
+}
+
+.filter-chip.active {
+ background: var(--accent-primary);
+ color: white;
+ border-color: var(--accent-primary);
+}
+
+/* Filter status bar */
+.filter-status-bar {
+ background: var(--bg-secondary);
+ border-radius: 8px;
+ padding: 0.75rem;
+ margin-top: 1rem;
+ border: 1px solid var(--border-color);
+}
+
+.active-filters {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ flex-wrap: wrap;
+}
+
+.active-filters > span:first-child {
+ font-size: 0.85rem;
+ color: var(--text-secondary);
+ margin-right: 0.5rem;
+}
+
+.filter-badge {
+ padding: 0.25rem 0.75rem;
+ background: var(--bg-tertiary);
+ border-radius: 20px;
+ font-size: 0.8rem;
+ color: var(--text-primary);
+ border: 1px solid var(--accent-primary);
+}
+
+.filter-status-bar .btn-link {
+ margin-left: auto;
+ color: var(--accent-primary);
+ text-decoration: none;
+ padding: 0.25rem 0.5rem;
+}
+
+.filter-status-bar .btn-link:hover {
+ color: var(--accent-secondary);
+}
+
+/* Bulk actions bar */
+.bulk-actions-bar {
+ background: var(--bg-secondary);
+ border-radius: 8px;
+ padding: 1rem;
+ margin-bottom: 1rem;
+ border: 1px solid var(--border-color);
+}
+
+.bulk-actions-content {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 1rem;
+}
+
+.news-stats {
+ display: flex;
+ gap: 1.5rem;
+}
+
+.stat-item {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ font-size: 0.9rem;
+ color: var(--text-secondary);
+}
+
+.stat-item i {
+ color: var(--accent-primary);
+}
+
+.bulk-actions {
+ display: flex;
+ gap: 0.5rem;
+ flex-wrap: wrap;
+}
+
+.bulk-actions .btn {
+ font-size: 0.85rem;
+}
+
+/* Auto-refresh indicator */
+.text-warning {
+ color: var(--warning-color) !important;
+ animation: pulse 2s ease-in-out infinite;
+}
+
+@keyframes pulse {
+ 0%, 100% {
+ opacity: 1;
+ }
+ 50% {
+ opacity: 0.6;
+ }
+}
+
+.form-check-label[for="auto-refresh"] {
+ font-size: 0.9rem;
+ transition: color 0.3s;
+}
+
+/* Refresh button animation */
+button[onclick="refreshFeed()"] i {
+ transition: transform 0.3s, color 0.3s;
+}
+
+button[onclick="refreshFeed()"]:hover i {
+ transform: rotate(180deg);
+}
+
+/* Trending Topics */
+.trending-section {
+ margin-top: 2rem;
+ padding-top: 2rem;
+ border-top: 1px solid var(--border-color);
+}
+
+.trending-section h3 {
+ font-size: 0.9rem;
+ margin-bottom: 1rem;
+ color: var(--text-secondary);
+}
+
+#trending-topics {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5rem;
+ margin-bottom: 1rem;
+}
+
+#trending-topics .topic-tag {
+ font-size: 0.8rem;
+ padding: 0.3rem 0.7rem;
+}
+
+.topic-tags {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5rem;
+}
+
+.topic-tag {
+ padding: 0.25rem 0.75rem;
+ background: var(--bg-tertiary) !important;
+ border: 1px solid var(--border-color);
+ border-radius: 20px;
+ font-size: 0.85rem;
+ color: var(--text-primary) !important; /* Ensure text color is set */
+ cursor: pointer;
+ transition: all 0.2s;
+ position: relative;
+ z-index: 2;
+ display: inline-block;
+}
+
+.topic-tag:hover {
+ background: var(--accent-primary);
+ color: white;
+ border-color: var(--accent-primary);
+}
+
+.topic-tag.active {
+ background: var(--accent-primary) !important;
+ color: white !important;
+ border-color: var(--accent-primary) !important;
+}
+
+/* Topic count badge */
+.topic-count {
+ background: rgba(255, 255, 255, 0.2);
+ color: var(--text-primary);
+ padding: 0.1rem 0.4rem;
+ border-radius: 10px;
+ font-size: 0.75rem;
+ font-weight: 600;
+ margin-left: 0.3rem;
+ display: inline-block;
+ min-width: 1.2rem;
+ text-align: center;
+}
+
+.topic-tag:hover .topic-count {
+ background: rgba(255, 255, 255, 0.3);
+ color: white;
+}
+
+.topic-tag.active .topic-count {
+ background: rgba(255, 255, 255, 0.3);
+ color: white;
+}
+
+/* Source links */
+.news-sources {
+ margin: 1rem 0;
+ padding: 0.75rem;
+ background: var(--bg-secondary);
+ border-radius: 8px;
+ border: 1px solid var(--border-color);
+}
+
+.sources-label {
+ font-size: 0.85rem;
+ font-weight: 600;
+ color: var(--text-secondary);
+ margin-bottom: 0.5rem;
+}
+
+.sources-list {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5rem;
+ margin-top: 0.5rem;
+}
+
+.source-link {
+ color: var(--accent-primary) !important;
+ text-decoration: none;
+ font-size: 0.8rem;
+ display: inline-flex;
+ align-items: center;
+ gap: 0.2rem;
+ padding: 0.2rem 0.6rem;
+ border: 1px solid var(--border-color);
+ border-radius: 12px;
+ transition: all 0.2s;
+ white-space: nowrap;
+ max-width: 250px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.source-link:hover {
+ background: var(--accent-primary);
+ color: white !important;
+ border-color: var(--accent-primary);
+ transform: translateY(-1px);
+}
+
+.source-link i {
+ font-size: 0.9rem;
+ opacity: 0.7;
+}
+
+/* Make the entire sources section more compact */
+.news-sources {
+ margin-top: 0.8rem;
+ padding: 0.8rem;
+ background: var(--bg-tertiary);
+ border-radius: 8px;
+ border: 1px solid var(--border-color);
+}
+
+/* Active filter bar */
+.active-filter-bar {
+ background: var(--bg-tertiary);
+ border: 1px solid var(--accent-primary);
+ border-radius: 8px;
+ padding: 1rem;
+ margin-bottom: 1rem;
+}
+
+.filter-info {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ color: var(--text-primary);
+}
+
+.filter-info strong {
+ color: var(--accent-primary);
+}
+
+.filter-info button {
+ margin-left: auto;
+ color: var(--text-secondary);
+ text-decoration: none;
+}
+
+.filter-info button:hover {
+ color: var(--accent-primary);
+}
+
+/* News-specific button styles */
+.news-item .btn-primary {
+ padding: 0.5rem 1rem;
+ background: var(--accent-primary);
+ color: white;
+ border: none;
+ border-radius: 4px;
+ cursor: pointer;
+ text-decoration: none;
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5rem;
+ font-size: 0.85rem;
+ transition: all 0.2s;
+}
+
+.news-item .btn-primary:hover {
+ background: var(--accent-primary-hover, #0056b3);
+ transform: translateY(-1px);
+}
+
+/* Button Extensions */
+.btn-full {
+ width: 100%;
+}
+
+.btn-icon {
+ padding: 0.5rem;
+ background: transparent;
+ border: 1px solid var(--border-color);
+ border-radius: 4px;
+ color: var(--text-secondary);
+ cursor: pointer;
+ transition: all 0.2s;
+}
+
+.btn-icon:hover {
+ background: var(--bg-tertiary);
+ color: var(--text-primary);
+}
+
+/* Loading States */
+.loading-placeholder {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 3rem;
+ color: var(--text-muted);
+}
+
+.loading-spinner {
+ width: 40px;
+ height: 40px;
+ border: 3px solid var(--bg-tertiary);
+ border-top-color: var(--accent-primary);
+ border-radius: 50%;
+ animation: spin 1s linear infinite;
+ margin-bottom: 1rem;
+}
+
+@keyframes spin {
+ to { transform: rotate(360deg); }
+}
+
+/* Subscription History Modal */
+.subscription-stats {
+ display: flex;
+ gap: 1.5rem;
+ padding: 1rem;
+ background: var(--bg-secondary);
+ border-radius: 8px;
+ flex-wrap: wrap;
+}
+
+.stat-item {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ color: var(--text-secondary);
+}
+
+.stat-item i {
+ color: var(--accent-primary);
+}
+
+.history-list {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ max-height: 400px;
+ overflow-y: auto;
+}
+
+.history-item {
+ padding: 1rem;
+ background: var(--bg-tertiary);
+ border-radius: 8px;
+ border: 1px solid var(--border-color);
+}
+
+.history-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 0.5rem;
+}
+
+.history-status {
+ padding: 0.25rem 0.5rem;
+ border-radius: 4px;
+ font-size: 0.75rem;
+ font-weight: 600;
+ text-transform: uppercase;
+}
+
+.history-status.status-completed {
+ background: var(--success-color);
+ color: white;
+}
+
+.history-status.status-in_progress {
+ background: var(--warning-color);
+ color: #000;
+}
+
+.history-status.status-failed,
+.history-status.status-error {
+ background: var(--error-color);
+ color: white;
+}
+
+.history-time {
+ font-size: 0.85rem;
+ color: var(--text-muted);
+}
+
+.history-query {
+ margin: 0.5rem 0;
+ font-weight: 500;
+ color: var(--text-primary);
+}
+
+.history-actions {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ margin-top: 0.5rem;
+}
+
+.history-actions .duration {
+ font-size: 0.85rem;
+ color: var(--text-secondary);
+}
+
+/* Modal overrides for dark theme */
+.modal-content {
+ background: var(--bg-primary);
+ color: var(--text-primary);
+ border: 1px solid var(--border-color);
+}
+
+.modal-header {
+ border-bottom-color: var(--border-color);
+}
+
+.modal-title small {
+ display: block;
+ font-size: 0.85rem;
+ font-weight: normal;
+ margin-top: 0.25rem;
+}
+
+/* News Templates */
+.news-templates {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ margin-bottom: 20px;
+}
+
+.template-btn {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 10px 15px;
+ background: var(--bg-secondary);
+ border: 1px solid var(--border-color);
+ border-radius: 8px;
+ cursor: pointer;
+ transition: all 0.2s;
+ color: var(--text-primary);
+ font-size: 0.9rem;
+ text-align: left;
+}
+
+.template-btn:hover {
+ background: var(--primary-color);
+ color: white;
+ transform: translateX(5px);
+}
+
+.template-btn i {
+ font-size: 1.1rem;
+ flex-shrink: 0;
+}
+
+/* Progress card specific styles */
+.news-card.active-research-card .news-title i {
+ color: var(--accent-primary);
+ margin-right: 0.5rem;
+}
+
+.news-card.active-research-card .btn-outline-primary {
+ border-color: var(--accent-primary);
+ color: var(--accent-primary);
+}
+
+.news-card.active-research-card .btn-outline-primary:hover {
+ background: var(--accent-primary);
+ color: white;
+ border-color: var(--accent-primary);
+}
diff --git a/src/local_deep_research/web/static/css/styles.css b/src/local_deep_research/web/static/css/styles.css
index 7b18c6357b..9adc276b74 100644
--- a/src/local_deep_research/web/static/css/styles.css
+++ b/src/local_deep_research/web/static/css/styles.css
@@ -1924,3 +1924,45 @@ input[type="number"].form-control::-webkit-inner-spin-button {
.metadata-item .star-rating {
margin-left: 0.5rem;
}
+
+/* History Page Enhancements */
+.news-indicator {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.25rem;
+ padding: 0.125rem 0.5rem;
+ background: var(--accent-primary);
+ color: white;
+ border-radius: 12px;
+ font-size: 0.75rem;
+ font-weight: 500;
+ margin-left: 0.5rem;
+}
+
+.news-indicator i {
+ font-size: 0.875rem;
+}
+
+.subscribe-btn {
+ background: transparent;
+ border: 1px solid var(--accent-primary);
+ color: var(--accent-primary);
+ transition: all 0.2s ease;
+}
+
+.subscribe-btn:hover {
+ background: var(--accent-primary);
+ color: white;
+ transform: translateY(-1px);
+}
+
+.subscribe-btn.subscribed {
+ background: var(--success-color);
+ border-color: var(--success-color);
+ color: white;
+ cursor: default;
+}
+
+.subscribe-btn.subscribed:hover {
+ transform: none;
+}
diff --git a/src/local_deep_research/web/static/css/subscriptions.css b/src/local_deep_research/web/static/css/subscriptions.css
new file mode 100644
index 0000000000..cbd6510353
--- /dev/null
+++ b/src/local_deep_research/web/static/css/subscriptions.css
@@ -0,0 +1,554 @@
+/* Subscriptions Management Page Styles */
+
+/* Import LDR color variables */
+:root {
+ --bg-primary: #121212;
+ --bg-secondary: #1e1e2d;
+ --bg-tertiary: #2a2a3a;
+ --accent-primary: #6e4ff6;
+ --accent-secondary: #9179f0;
+ --accent-tertiary: #40bfff;
+ --text-primary: #f5f5f5;
+ --text-secondary: #c0c0cc;
+ --text-muted: #8a8aa0;
+ --border-color: #343452;
+}
+
+.subscriptions-page {
+ padding: 20px;
+ max-width: 1400px;
+ margin: 0 auto;
+ background-color: var(--bg-primary);
+ min-height: 100vh;
+ color: var(--text-primary);
+}
+
+/* Header Section */
+.page-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 30px;
+ padding-bottom: 20px;
+ border-bottom: 1px solid var(--border-color);
+}
+
+.header-content h1 {
+ margin: 0;
+ font-size: 2rem;
+ color: var(--text-primary);
+}
+
+.header-content .subtitle {
+ margin: 5px 0 0 0;
+ color: var(--text-secondary);
+}
+
+.header-actions {
+ display: flex;
+ gap: 10px;
+}
+
+/* Stats Overview */
+.stats-overview {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
+ gap: 20px;
+ margin-bottom: 30px;
+}
+
+.stat-card {
+ background: var(--bg-secondary);
+ border: 1px solid var(--border-color);
+ border-radius: 8px;
+ padding: 20px;
+ text-align: center;
+ transition: transform 0.2s, box-shadow 0.2s;
+}
+
+.stat-card:hover {
+ transform: translateY(-2px);
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
+}
+
+.stat-value {
+ font-size: 2.5rem;
+ font-weight: bold;
+ color: #2c5aa0;
+ margin-bottom: 5px;
+}
+
+.stat-label {
+ color: var(--text-secondary);
+ font-size: 0.9rem;
+}
+
+/* Scheduler Status Bar */
+.scheduler-status-bar {
+ background: var(--bg-secondary);
+ border: 1px solid var(--border-color);
+ border-radius: 8px;
+ padding: 15px 20px;
+ margin-bottom: 20px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+}
+
+.scheduler-info {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ color: var(--text-primary);
+}
+
+.scheduler-label {
+ font-weight: 500;
+}
+
+.scheduler-status {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.status-indicator {
+ width: 10px;
+ height: 10px;
+ border-radius: 50%;
+ background: var(--text-muted);
+ display: inline-block;
+}
+
+.status-indicator.active {
+ background: #4caf50;
+ box-shadow: 0 0 8px rgba(76, 175, 80, 0.6);
+}
+
+.status-indicator.inactive {
+ background: #f44336;
+}
+
+.status-indicator.checking {
+ background: #ff9800;
+ animation: pulse 1.5s infinite;
+}
+
+@keyframes pulse {
+ 0% { opacity: 1; }
+ 50% { opacity: 0.5; }
+ 100% { opacity: 1; }
+}
+
+.scheduler-details {
+ color: var(--text-secondary);
+ font-size: 0.9rem;
+ margin-left: 10px;
+}
+
+.scheduler-actions {
+ display: flex;
+ gap: 10px;
+}
+
+/* Main Container */
+.subscriptions-container {
+ display: flex;
+ gap: 20px;
+}
+
+/* Folders Sidebar */
+.folders-sidebar {
+ width: 250px;
+ background: var(--bg-secondary);
+ border: 1px solid var(--border-color);
+ border-radius: 8px;
+ padding: 20px;
+ height: fit-content;
+}
+
+.folders-sidebar h3 {
+ margin: 0 0 15px 0;
+ font-size: 1.1rem;
+ color: var(--text-primary);
+}
+
+.folder-list {
+ margin: 0 0 15px 0;
+}
+
+.folder-item {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 10px 15px;
+ margin: 0 -15px;
+ cursor: pointer;
+ border-radius: 4px;
+ transition: background-color 0.2s;
+}
+
+.folder-item:hover {
+ background-color: var(--bg-tertiary);
+}
+
+.folder-item.active {
+ background-color: #e3f2fd;
+ color: #2c5aa0;
+}
+
+.folder-count {
+ background: var(--bg-tertiary);
+ color: var(--text-secondary);
+ padding: 2px 8px;
+ border-radius: 12px;
+ font-size: 0.8rem;
+}
+
+.folder-item.active .folder-count {
+ background: #2c5aa0;
+ color: white;
+}
+
+/* Main Content Area */
+.subscriptions-main {
+ flex: 1;
+}
+
+/* Filter Bar */
+.filter-bar {
+ background: var(--bg-secondary);
+ border: 1px solid var(--border-color);
+ border-radius: 8px;
+ padding: 15px;
+ margin-bottom: 20px;
+ display: flex;
+ gap: 15px;
+ align-items: center;
+}
+
+.search-box {
+ flex: 1;
+ position: relative;
+}
+
+.search-box i {
+ position: absolute;
+ left: 12px;
+ top: 50%;
+ transform: translateY(-50%);
+ color: var(--text-secondary);
+}
+
+.search-box input {
+ width: 100%;
+ padding: 8px 15px 8px 35px;
+ border: 1px solid var(--border-color);
+ border-radius: 4px;
+ outline: none;
+}
+
+.search-box input:focus {
+ border-color: #2c5aa0;
+}
+
+.filter-options {
+ display: flex;
+ gap: 10px;
+}
+
+.filter-options select {
+ min-width: 150px;
+}
+
+/* Subscriptions Grid */
+.subscriptions-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
+ gap: 20px;
+}
+
+/* Subscription Card */
+.subscription-card {
+ background: var(--bg-secondary);
+ border: 1px solid var(--border-color);
+ border-radius: 8px;
+ overflow: hidden;
+ transition: box-shadow 0.2s;
+}
+
+.subscription-card:hover {
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
+}
+
+.card-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 15px;
+ background: var(--bg-tertiary);
+ border-bottom: 1px solid var(--border-color);
+ gap: 15px;
+}
+
+.card-header h4 {
+ margin: 0;
+ font-size: 1.1rem;
+ color: var(--text-primary);
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ min-width: 0;
+}
+
+.card-actions {
+ display: flex;
+ gap: 5px;
+ flex-shrink: 0;
+}
+
+.btn-icon {
+ background: none;
+ border: none;
+ padding: 5px 8px;
+ cursor: pointer;
+ color: var(--text-secondary);
+ transition: color 0.2s;
+}
+
+.btn-icon:hover {
+ color: #2c5aa0;
+}
+
+.btn-icon.btn-danger {
+ color: #dc3545;
+}
+
+.btn-icon.btn-danger:hover {
+ color: #c82333;
+ background-color: rgba(220, 53, 69, 0.1);
+ border-radius: 4px;
+}
+
+.card-body {
+ padding: 15px;
+}
+
+.query-text {
+ color: var(--text-secondary);
+ margin-bottom: 15px;
+ font-style: italic;
+}
+
+.subscription-meta {
+ display: flex;
+ gap: 10px;
+ margin-bottom: 15px;
+ flex-wrap: wrap;
+}
+
+.status-badge,
+.frequency-badge,
+.folder-badge {
+ padding: 4px 10px;
+ border-radius: 4px;
+ font-size: 0.85rem;
+}
+
+.status-badge.status-active {
+ background: #d4edda;
+ color: #155724;
+}
+
+.status-badge.status-paused {
+ background: #f8d7da;
+ color: #721c24;
+}
+
+.frequency-badge {
+ background: #e2e3e5;
+ color: #383d41;
+}
+
+.folder-badge {
+ background: #d1ecf1;
+ color: #0c5460;
+}
+
+.subscription-stats {
+ margin: 15px 0;
+ display: flex;
+ gap: 15px;
+ flex-wrap: wrap;
+}
+
+.stat-item {
+ font-size: 0.85rem;
+ color: var(--text-secondary);
+}
+
+.stat-item i {
+ margin-right: 5px;
+}
+
+.source-link {
+ color: #2c5aa0;
+ text-decoration: none;
+}
+
+.source-link:hover {
+ text-decoration: underline;
+}
+
+.last-updated,
+.next-update {
+ font-size: 0.85rem;
+ color: var(--text-secondary);
+ margin-bottom: 5px;
+}
+
+.last-updated i,
+.next-update i {
+ margin-right: 5px;
+}
+
+/* History Modal Styles */
+.history-summary {
+ background: var(--bg-tertiary);
+ padding: 15px;
+ border-radius: 8px;
+ margin-bottom: 20px;
+}
+
+.history-summary p {
+ margin: 5px 0;
+}
+
+.history-list {
+ max-height: 400px;
+ overflow-y: auto;
+}
+
+.history-item {
+ border: 1px solid var(--border-color);
+ border-radius: 4px;
+ padding: 12px;
+ margin-bottom: 10px;
+ transition: background-color 0.2s;
+}
+
+.history-item:hover {
+ background-color: var(--bg-tertiary);
+}
+
+.history-item-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 8px;
+}
+
+.history-item-header a {
+ color: var(--text-primary);
+ text-decoration: none;
+ font-weight: 500;
+}
+
+.history-item-header a:hover {
+ color: #2c5aa0;
+}
+
+.history-date {
+ font-size: 0.85rem;
+ color: var(--text-secondary);
+}
+
+.history-item-meta {
+ display: flex;
+ gap: 10px;
+}
+
+.duration {
+ font-size: 0.85rem;
+ color: var(--text-secondary);
+}
+
+.topics-list {
+ display: flex;
+ gap: 5px;
+ margin-top: 5px;
+ flex-wrap: wrap;
+}
+
+.topic-badge {
+ background: var(--accent-primary);
+ color: white;
+ padding: 2px 8px;
+ border-radius: 12px;
+ font-size: 0.75rem;
+ font-weight: 500;
+}
+
+/* Empty State */
+.empty-state {
+ text-align: center;
+ padding: 60px 20px;
+ color: var(--text-secondary);
+}
+
+.empty-state i {
+ font-size: 4rem;
+ color: var(--text-muted);
+ margin-bottom: 20px;
+}
+
+.empty-state h3 {
+ margin: 0 0 10px 0;
+}
+
+/* Loading State */
+.loading-placeholder {
+ text-align: center;
+ padding: 60px 20px;
+ color: var(--text-secondary);
+}
+
+/* Modal Customizations */
+.modal-body .form-text {
+ font-size: 0.85rem;
+ color: var(--text-secondary);
+}
+
+/* Responsive Design */
+@media (max-width: 768px) {
+ .subscriptions-container {
+ flex-direction: column;
+ }
+
+ .folders-sidebar {
+ width: 100%;
+ margin-bottom: 20px;
+ }
+
+ .stats-overview {
+ grid-template-columns: repeat(2, 1fr);
+ }
+
+ .subscriptions-grid {
+ grid-template-columns: 1fr;
+ }
+
+ .filter-bar {
+ flex-direction: column;
+ }
+
+ .filter-options {
+ width: 100%;
+ flex-direction: column;
+ }
+
+ .filter-options select {
+ width: 100%;
+ }
+}
diff --git a/src/local_deep_research/web/static/js/components/history.js b/src/local_deep_research/web/static/js/components/history.js
index 647de971ef..ba704f3cc9 100644
--- a/src/local_deep_research/web/static/js/components/history.js
+++ b/src/local_deep_research/web/static/js/components/history.js
@@ -326,6 +326,9 @@
// Status class - convert in_progress to in-progress for CSS
const statusClass = item.status ? item.status.replace('_', '-') : '';
+ // Check if this is a news-related research
+ const isNewsItem = item.metadata && item.metadata.is_news_search;
+
// Create the HTML content
itemEl.innerHTML = `
<div class="history-item-header">
@@ -335,12 +338,17 @@
<div class="history-item-meta">
<div class="history-item-date">${formattedDate}</div>
<div class="history-item-mode">${formatMode(item.mode)}</div>
+ ${isNewsItem ? '<span class="news-indicator"><i class="fas fa-newspaper"></i> News</span>' : ''}
</div>
<div class="history-item-actions">
${item.status === 'completed' ?
`<button class="btn btn-sm btn-outline view-btn">
<i class="fas fa-eye"></i> View
</button>` : ''}
+ ${isNewsItem && item.status === 'completed' ?
+ `<button class="btn btn-sm btn-outline subscribe-btn" data-research-id="${item.id}" data-query="${encodeURIComponent(item.query)}">
+ <i class="fas fa-bell"></i> Subscribe
+ </button>` : ''}
<button class="btn btn-sm btn-outline delete-item-btn">
<i class="fas fa-trash-alt"></i>
</button>
@@ -356,6 +364,14 @@
});
}
+ const subscribeBtn = itemEl.querySelector('.subscribe-btn');
+ if (subscribeBtn) {
+ subscribeBtn.addEventListener('click', (e) => {
+ e.stopPropagation(); // Prevent item click
+ handleSubscribe(item);
+ });
+ }
+
const deleteBtn = itemEl.querySelector('.delete-item-btn');
if (deleteBtn) {
deleteBtn.addEventListener('click', (e) => {
@@ -376,6 +392,207 @@
return itemEl;
}
+ /**
+ * Handle subscribe button click
+ * @param {Object} item - The research item
+ */
+ async function handleSubscribe(item) {
+ // Create and show subscription modal
+ showSubscriptionModal(item);
+ }
+
+ /**
+ * Show subscription modal with options
+ * @param {Object} item - The research item
+ */
+ function showSubscriptionModal(item) {
+ // Create modal HTML
+ const modalHtml = `
+ <div class="modal fade" id="subscriptionModal" tabindex="-1">
+ <div class="modal-dialog">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h5 class="modal-title">Subscribe to News Updates</h5>
+ <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
+ </div>
+ <div class="modal-body">
+ <p class="mb-3">Subscribe to updates for: <strong>${item.query}</strong></p>
+
+ <div class="mb-3">
+ <label class="form-label">Update Frequency</label>
+ <select class="form-select" id="subscription-frequency">
+ <option value="1">Every hour</option>
+ <option value="3">Every 3 hours</option>
+ <option value="6">Every 6 hours</option>
+ <option value="12">Every 12 hours</option>
+ <option value="24" selected>Daily</option>
+ <option value="168">Weekly</option>
+ </select>
+ </div>
+
+ <div class="mb-3">
+ <label class="form-label">Folder (Optional)</label>
+ <div class="input-group">
+ <select class="form-select" id="subscription-folder">
+ <option value="">No folder</option>
+ <option value="__new__">Create new folder...</option>
+ </select>
+ <input type="text" class="form-control d-none" id="new-folder-name" placeholder="New folder name">
+ </div>
+ </div>
+
+ <div class="mb-3">
+ <label class="form-label">Notes (Optional)</label>
+ <textarea class="form-control" id="subscription-notes" rows="2" placeholder="Add notes about this subscription..."></textarea>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
+ <button type="button" class="btn btn-primary" id="confirm-subscription">Subscribe</button>
+ </div>
+ </div>
+ </div>
+ </div>
+ `;
+
+ // Remove existing modal if any
+ const existingModal = document.getElementById('subscriptionModal');
+ if (existingModal) {
+ existingModal.remove();
+ }
+
+ // Add modal to page
+ document.body.insertAdjacentHTML('beforeend', modalHtml);
+
+ // Initialize Bootstrap modal
+ const modal = new bootstrap.Modal(document.getElementById('subscriptionModal'));
+
+ // Load existing folders
+ loadSubscriptionFolders();
+
+ // Handle folder selection
+ const folderSelect = document.getElementById('subscription-folder');
+ const newFolderInput = document.getElementById('new-folder-name');
+
+ folderSelect.addEventListener('change', (e) => {
+ if (e.target.value === '__new__') {
+ newFolderInput.classList.remove('d-none');
+ newFolderInput.focus();
+ } else {
+ newFolderInput.classList.add('d-none');
+ }
+ });
+
+ // Handle confirm button
+ document.getElementById('confirm-subscription').addEventListener('click', async () => {
+ const frequency = document.getElementById('subscription-frequency').value;
+ let folder = folderSelect.value;
+
+ // Handle new folder creation
+ if (folder === '__new__') {
+ folder = newFolderInput.value.trim();
+ if (!folder) {
+ alert('Please enter a folder name');
+ return;
+ }
+ }
+
+ const notes = document.getElementById('subscription-notes').value;
+
+ await createNewsSubscription(item, frequency, folder, notes);
+ modal.hide();
+ });
+
+ // Show the modal
+ modal.show();
+ }
+
+ /**
+ * Load existing subscription folders
+ */
+ async function loadSubscriptionFolders() {
+ try {
+ const response = await fetch('/news/api/subscription/folders');
+ if (response.ok) {
+ const folders = await response.json();
+ const folderSelect = document.getElementById('subscription-folder');
+
+ // Clear existing options except default ones
+ while (folderSelect.options.length > 2) {
+ folderSelect.remove(1);
+ }
+
+ // Add existing folders
+ folders.forEach(folder => {
+ const option = document.createElement('option');
+ option.value = folder.name;
+ option.textContent = `${folder.icon || '📁'} ${folder.name}`;
+ folderSelect.insertBefore(option, folderSelect.lastElementChild);
+ });
+ }
+ } catch (error) {
+ console.error('Error loading folders:', error);
+ }
+ }
+
+ /**
+ * Create news subscription
+ */
+ async function createNewsSubscription(item, frequency, folder, notes) {
+ try {
+ // Use the subscription manager to create subscription
+ const response = await fetch('/news/api/subscription/subscribe/research', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': getCSRFToken()
+ },
+ body: JSON.stringify({
+ user_id: localStorage.getItem('ldr_user_id') || 'anonymous',
+ research_id: item.id,
+ query: item.query,
+ refresh_hours: parseInt(frequency),
+ folder: folder,
+ notes: notes
+ })
+ });
+
+ if (response.ok) {
+ uiUtils.showMessage('Subscription created successfully!');
+ // Update UI to show subscription status
+ updateSubscriptionStatus(item.id);
+ } else {
+ const error = await response.json();
+ uiUtils.showError(error.message || 'Failed to create subscription');
+ }
+ } catch (error) {
+ console.error('Error creating subscription:', error);
+ uiUtils.showError('Failed to create subscription');
+ }
+ }
+
+ /**
+ * Get CSRF token
+ */
+ function getCSRFToken() {
+ return document.querySelector('meta[name="csrf-token"]')?.content || '';
+ }
+
+ /**
+ * Update subscription status in UI
+ */
+ function updateSubscriptionStatus(researchId) {
+ const item = document.querySelector(`[data-id="${researchId}"]`);
+ if (item) {
+ const subscribeBtn = item.querySelector('.subscribe-btn');
+ if (subscribeBtn) {
+ subscribeBtn.innerHTML = '<i class="fas fa-check"></i> Subscribed';
+ subscribeBtn.classList.add('subscribed');
+ subscribeBtn.disabled = true;
+ }
+ }
+ }
+
/**
* Format a title from a query string
* Truncates long queries and adds ellipsis
diff --git a/src/local_deep_research/web/static/js/components/news.js b/src/local_deep_research/web/static/js/components/news.js
new file mode 100644
index 0000000000..1cb2a33570
--- /dev/null
+++ b/src/local_deep_research/web/static/js/components/news.js
@@ -0,0 +1,128 @@
+// News Component JavaScript
+// Handles reusable news-related UI components
+
+// Empty alert container
+let alertTimeout = null;
+
+// Component initialization
+document.addEventListener('DOMContentLoaded', function() {
+ // Initialize any news-specific components
+ initializeSliders();
+});
+
+// Initialize sliders with value display
+function initializeSliders() {
+ const sliders = document.querySelectorAll('input[type="range"]');
+ sliders.forEach(slider => {
+ const valueDisplay = slider.nextElementSibling;
+ if (valueDisplay && valueDisplay.classList.contains('slider-value')) {
+ slider.addEventListener('input', function() {
+ valueDisplay.textContent = this.value;
+ });
+ }
+ });
+}
+
+// Modal utilities
+window.showModal = function(modalId) {
+ const modal = document.getElementById(modalId);
+ if (modal) {
+ modal.style.display = 'flex';
+ document.body.style.overflow = 'hidden';
+ }
+};
+
+window.hideModal = function(modalId) {
+ const modal = document.getElementById(modalId);
+ if (modal) {
+ modal.style.display = 'none';
+ document.body.style.overflow = 'auto';
+ }
+};
+
+// Close modal on outside click
+document.addEventListener('click', function(e) {
+ if (e.target.classList.contains('modal')) {
+ e.target.style.display = 'none';
+ document.body.style.overflow = 'auto';
+ }
+});
+
+// Empty state helper
+window.showEmptyState = function(container, message, icon = 'fas fa-newspaper') {
+ container.innerHTML = `
+ <div class="empty-state">
+ <i class="${icon}"></i>
+ <h3>No items found</h3>
+ <p>${message}</p>
+ </div>
+ `;
+};
+
+// Loading state helper
+window.showLoadingState = function(container, message = 'Loading...') {
+ container.innerHTML = `
+ <div class="loading-placeholder">
+ <div class="loading-spinner"></div>
+ <p>${message}</p>
+ </div>
+ `;
+};
+
+// Error state helper
+window.showErrorState = function(container, message) {
+ container.innerHTML = `
+ <div class="error-state">
+ <i class="fas fa-exclamation-triangle"></i>
+ <h3>Error</h3>
+ <p>${message}</p>
+ </div>
+ `;
+};
+
+// Format timestamp
+window.formatTimeAgo = function(timestamp) {
+ const now = new Date();
+ const time = new Date(timestamp);
+ const diff = Math.floor((now - time) / 1000); // seconds
+
+ if (diff < 60) return 'just now';
+ if (diff < 3600) return `${Math.floor(diff / 60)} minutes ago`;
+ if (diff < 86400) return `${Math.floor(diff / 3600)} hours ago`;
+ if (diff < 604800) return `${Math.floor(diff / 86400)} days ago`;
+
+ return time.toLocaleDateString();
+};
+
+// Create tag element
+window.createTag = function(text, className = 'tag') {
+ const tag = document.createElement('span');
+ tag.className = className;
+ tag.textContent = text;
+ return tag;
+};
+
+// Debounce helper
+window.debounce = function(func, wait) {
+ let timeout;
+ return function executedFunction(...args) {
+ const later = () => {
+ clearTimeout(timeout);
+ func(...args);
+ };
+ clearTimeout(timeout);
+ timeout = setTimeout(later, wait);
+ };
+};
+
+// Export utilities for use in other scripts
+window.NewsUtils = {
+ showModal,
+ hideModal,
+ showEmptyState,
+ showLoadingState,
+ showErrorState,
+ formatTimeAgo,
+ createTag,
+ debounce
+};
diff --git a/src/local_deep_research/web/static/js/components/results.js b/src/local_deep_research/web/static/js/components/results.js
index a8cca44349..2defb89997 100644
--- a/src/local_deep_research/web/static/js/components/results.js
+++ b/src/local_deep_research/web/static/js/components/results.js
@@ -157,8 +157,8 @@
// Query field
const queryElement = document.getElementById('result-query');
if (queryElement) {
- // Use query from metadata or content title
- const query = metadata.query || metadata.title || data.query || 'Untitled Research';
+ // Prefer processed query over original query for news subscriptions
+ const query = metadata.processed_query || metadata.query || metadata.title || data.query || 'Untitled Research';
console.log('Setting query to:', query);
queryElement.textContent = query;
}
diff --git a/src/local_deep_research/web/static/js/components/subscription-manager.js b/src/local_deep_research/web/static/js/components/subscription-manager.js
new file mode 100644
index 0000000000..3913f82dc9
--- /dev/null
+++ b/src/local_deep_research/web/static/js/components/subscription-manager.js
@@ -0,0 +1,434 @@
+/**
+ * Subscription Manager Component
+ * Handles subscription UI in the news page modal
+ */
+
+class SubscriptionManager {
+ constructor() {
+ this.subscriptions = {};
+ this.folders = [];
+ this.currentFolder = 'all';
+ this.initialized = false;
+ }
+
+ async initialize() {
+ if (this.initialized) return;
+
+ // Set up event listeners
+ this.setupEventListeners();
+
+ // Load data when modal opens
+ const modal = document.getElementById('subscriptionsModal');
+ if (modal) {
+ modal.addEventListener('shown.bs.modal', () => {
+ this.loadSubscriptionData();
+ });
+ }
+
+ this.initialized = true;
+ }
+
+ setupEventListeners() {
+ // Folder tab clicks
+ document.addEventListener('click', (e) => {
+ if (e.target.matches('#folderTabs .nav-link')) {
+ e.preventDefault();
+ this.switchFolder(e.target.dataset.folder);
+ }
+ });
+
+ // Create folder button
+ const createFolderBtn = document.getElementById('create-folder-btn');
+ if (createFolderBtn) {
+ createFolderBtn.addEventListener('click', () => this.showCreateFolderDialog());
+ }
+
+ // Subscription actions via delegation
+ document.addEventListener('click', (e) => {
+ if (e.target.matches('.edit-subscription-btn')) {
+ this.editSubscription(e.target.dataset.subscriptionId);
+ } else if (e.target.matches('.delete-subscription-btn')) {
+ this.deleteSubscription(e.target.dataset.subscriptionId);
+ } else if (e.target.matches('.pause-subscription-btn')) {
+ this.toggleSubscriptionStatus(e.target.dataset.subscriptionId);
+ }
+ });
+ }
+
+ async loadSubscriptionData() {
+ try {
+ // Show loading state
+ this.showLoading();
+
+ // Load stats
+ const statsResponse = await fetch('/news/api/subscription/stats');
+ if (statsResponse.ok) {
+ const stats = await statsResponse.json();
+ this.updateStats(stats);
+ }
+
+ // Load folders
+ const foldersResponse = await fetch('/news/api/subscription/folders');
+ if (foldersResponse.ok) {
+ this.folders = await foldersResponse.json();
+ this.renderFolderTabs();
+ }
+
+ // Load organized subscriptions
+ const subsResponse = await fetch('/news/api/subscription/subscriptions/organized');
+ if (subsResponse.ok) {
+ this.subscriptions = await subsResponse.json();
+ this.renderSubscriptions();
+ }
+
+ } catch (error) {
+ console.error('Error loading subscription data:', error);
+ this.showError('Failed to load subscriptions');
+ }
+ }
+
+ updateStats(stats) {
+ document.getElementById('total-subscriptions').textContent = stats.total_subscriptions || 0;
+ document.getElementById('active-subscriptions').textContent = stats.active_subscriptions || 0;
+ document.getElementById('total-folders').textContent = stats.total_folders || 0;
+
+ if (stats.next_refresh) {
+ const nextRefresh = new Date(stats.next_refresh);
+ const now = new Date();
+ const diff = nextRefresh - now;
+
+ if (diff > 0) {
+ const hours = Math.floor(diff / (1000 * 60 * 60));
+ const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
+ document.getElementById('next-refresh-time').textContent =
+ hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
+ } else {
+ document.getElementById('next-refresh-time').textContent = 'Soon';
+ }
+ }
+ }
+
+ renderFolderTabs() {
+ const tabsContainer = document.getElementById('folderTabs');
+ const existingTabs = tabsContainer.querySelectorAll('[data-folder]:not([data-folder="all"]):not([data-folder="Unfiled"])');
+
+ // Remove existing dynamic tabs
+ existingTabs.forEach(tab => tab.parentElement.remove());
+
+ // Add folder tabs before the create button
+ const createBtn = tabsContainer.querySelector('#create-folder-btn').parentElement;
+
+ this.folders.forEach(folder => {
+ const li = document.createElement('li');
+ li.className = 'nav-item';
+ li.innerHTML = `
+ <button class="nav-link" data-folder="${folder.name}" type="button">
+ ${folder.icon || '📁'} ${folder.name}
+ <span class="badge bg-secondary ms-1">${folder.item_count || 0}</span>
+ </button>
+ `;
+ tabsContainer.insertBefore(li, createBtn);
+ });
+ }
+
+ switchFolder(folderName) {
+ this.currentFolder = folderName;
+
+ // Update active tab
+ document.querySelectorAll('#folderTabs .nav-link').forEach(link => {
+ link.classList.toggle('active', link.dataset.folder === folderName);
+ });
+
+ // Render subscriptions for this folder
+ this.renderSubscriptions();
+ }
+
+ renderSubscriptions() {
+ const container = document.getElementById('subscriptions-list');
+
+ // Get subscriptions for current folder
+ let subsToShow = [];
+ if (this.currentFolder === 'all') {
+ // Show all subscriptions
+ Object.values(this.subscriptions).forEach(folderSubs => {
+ subsToShow = subsToShow.concat(folderSubs);
+ });
+ } else {
+ subsToShow = this.subscriptions[this.currentFolder] || [];
+ }
+
+ if (subsToShow.length === 0) {
+ container.innerHTML = `
+ <div class="text-center p-4 text-muted">
+ <i class="bi bi-inbox fs-1"></i>
+ <p>No subscriptions in this folder</p>
+ </div>
+ `;
+ return;
+ }
+
+ // Render subscription cards
+ container.innerHTML = subsToShow.map(sub => this.renderSubscriptionCard(sub)).join('');
+ }
+
+ renderSubscriptionCard(subscription) {
+ const nextRefresh = new Date(subscription.next_refresh);
+ const now = new Date();
+ const timeUntil = this.formatTimeUntil(nextRefresh - now);
+
+ return `
+ <div class="subscription-card mb-3" data-subscription-id="${subscription.id}">
+ <div class="d-flex justify-content-between align-items-start">
+ <div class="flex-grow-1">
+ <h6 class="mb-1">${this.escapeHtml(subscription.query_or_topic)}</h6>
+ <div class="text-muted small">
+ <span><i class="bi bi-clock"></i> Every ${subscription.refresh_interval_hours}h</span>
+ <span class="ms-3"><i class="bi bi-arrow-clockwise"></i> Next: ${timeUntil}</span>
+ ${subscription.folder ? `<span class="ms-3"><i class="bi bi-folder"></i> ${subscription.folder}</span>` : ''}
+ </div>
+ ${subscription.notes ? `<p class="mb-0 mt-2 small">${this.escapeHtml(subscription.notes)}</p>` : ''}
+ </div>
+ <div class="subscription-actions">
+ <button class="btn btn-sm btn-outline-primary edit-subscription-btn"
+ data-subscription-id="${subscription.id}" title="Edit">
+ <i class="bi bi-pencil"></i>
+ </button>
+ <button class="btn btn-sm btn-outline-warning pause-subscription-btn"
+ data-subscription-id="${subscription.id}" title="${subscription.status === 'active' ? 'Pause' : 'Resume'}">
+ <i class="bi bi-${subscription.status === 'active' ? 'pause' : 'play'}"></i>
+ </button>
+ <button class="btn btn-sm btn-outline-danger delete-subscription-btn"
+ data-subscription-id="${subscription.id}" title="Delete">
+ <i class="bi bi-trash"></i>
+ </button>
+ </div>
+ </div>
+ </div>
+ `;
+ }
+
+ async editSubscription(subscriptionId) {
+ // Find the subscription
+ let subscription = null;
+ for (const folderSubs of Object.values(this.subscriptions)) {
+ subscription = folderSubs.find(s => s.id === subscriptionId);
+ if (subscription) break;
+ }
+
+ if (!subscription) return;
+
+ // Create edit modal
+ const modalHtml = `
+ <div class="modal fade" id="editSubscriptionModal" tabindex="-1">
+ <div class="modal-dialog">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h5 class="modal-title">Edit Subscription</h5>
+ <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
+ </div>
+ <div class="modal-body">
+ <div class="mb-3">
+ <label class="form-label">Update Frequency</label>
+ <select class="form-select" id="edit-frequency">
+ <option value="1" ${subscription.refresh_interval_hours === 1 ? 'selected' : ''}>Every hour</option>
+ <option value="3" ${subscription.refresh_interval_hours === 3 ? 'selected' : ''}>Every 3 hours</option>
+ <option value="6" ${subscription.refresh_interval_hours === 6 ? 'selected' : ''}>Every 6 hours</option>
+ <option value="12" ${subscription.refresh_interval_hours === 12 ? 'selected' : ''}>Every 12 hours</option>
+ <option value="24" ${subscription.refresh_interval_hours === 24 ? 'selected' : ''}>Daily</option>
+ <option value="168" ${subscription.refresh_interval_hours === 168 ? 'selected' : ''}>Weekly</option>
+ </select>
+ </div>
+ <div class="mb-3">
+ <label class="form-label">Folder</label>
+ <select class="form-select" id="edit-folder">
+ <option value="">No folder</option>
+ ${this.folders.map(f =>
+ `<option value="${f.name}" ${subscription.folder === f.name ? 'selected' : ''}>${f.name}</option>`
+ ).join('')}
+ </select>
+ </div>
+ <div class="mb-3">
+ <label class="form-label">Notes</label>
+ <textarea class="form-control" id="edit-notes" rows="2">${subscription.notes || ''}</textarea>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
+ <button type="button" class="btn btn-primary" id="save-subscription-edit">Save Changes</button>
+ </div>
+ </div>
+ </div>
+ </div>
+ `;
+
+ // Remove existing modal if any
+ const existingModal = document.getElementById('editSubscriptionModal');
+ if (existingModal) existingModal.remove();
+
+ document.body.insertAdjacentHTML('beforeend', modalHtml);
+ const modal = new bootstrap.Modal(document.getElementById('editSubscriptionModal'));
+
+ // Handle save
+ document.getElementById('save-subscription-edit').addEventListener('click', async () => {
+ const updates = {
+ refresh_interval_hours: parseInt(document.getElementById('edit-frequency').value),
+ folder: document.getElementById('edit-folder').value,
+ notes: document.getElementById('edit-notes').value
+ };
+
+ await this.updateSubscription(subscriptionId, updates);
+ modal.hide();
+ });
+
+ modal.show();
+ }
+
+ async updateSubscription(subscriptionId, updates) {
+ try {
+ const response = await fetch(`/news/api/subscription/subscriptions/${subscriptionId}`, {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': this.getCSRFToken()
+ },
+ body: JSON.stringify(updates)
+ });
+
+ if (response.ok) {
+ this.showSuccess('Subscription updated');
+ await this.loadSubscriptionData();
+ } else {
+ this.showError('Failed to update subscription');
+ }
+ } catch (error) {
+ console.error('Error updating subscription:', error);
+ this.showError('Error updating subscription');
+ }
+ }
+
+ async deleteSubscription(subscriptionId) {
+ if (!confirm('Are you sure you want to delete this subscription?')) return;
+
+ try {
+ const response = await fetch(`/news/api/subscription/subscriptions/${subscriptionId}`, {
+ method: 'DELETE',
+ headers: {
+ 'X-CSRFToken': this.getCSRFToken()
+ }
+ });
+
+ if (response.ok) {
+ this.showSuccess('Subscription deleted');
+ await this.loadSubscriptionData();
+ } else {
+ this.showError('Failed to delete subscription');
+ }
+ } catch (error) {
+ console.error('Error deleting subscription:', error);
+ this.showError('Error deleting subscription');
+ }
+ }
+
+ async toggleSubscriptionStatus(subscriptionId) {
+ // Find the subscription
+ let subscription = null;
+ for (const folderSubs of Object.values(this.subscriptions)) {
+ subscription = folderSubs.find(s => s.id === subscriptionId);
+ if (subscription) break;
+ }
+
+ if (!subscription) return;
+
+ const newStatus = subscription.status === 'active' ? 'paused' : 'active';
+ await this.updateSubscription(subscriptionId, { status: newStatus });
+ }
+
+ showCreateFolderDialog() {
+ const name = prompt('Enter folder name:');
+ if (!name) return;
+
+ this.createFolder(name);
+ }
+
+ async createFolder(name, color = null, icon = null) {
+ try {
+ const response = await fetch('/news/api/subscription/folders', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': this.getCSRFToken()
+ },
+ body: JSON.stringify({ name, color, icon })
+ });
+
+ if (response.ok) {
+ this.showSuccess('Folder created');
+ await this.loadSubscriptionData();
+ } else {
+ const error = await response.json();
+ this.showError(error.error || 'Failed to create folder');
+ }
+ } catch (error) {
+ console.error('Error creating folder:', error);
+ this.showError('Error creating folder');
+ }
+ }
+
+ // Utility methods
+ formatTimeUntil(milliseconds) {
+ if (milliseconds <= 0) return 'Now';
+
+ const hours = Math.floor(milliseconds / (1000 * 60 * 60));
+ const days = Math.floor(hours / 24);
+
+ if (days > 0) return `${days}d`;
+ if (hours > 0) return `${hours}h`;
+
+ const minutes = Math.floor(milliseconds / (1000 * 60));
+ return `${minutes}m`;
+ }
+
+ escapeHtml(text) {
+ const div = document.createElement('div');
+ div.textContent = text;
+ return div.innerHTML;
+ }
+
+ getCSRFToken() {
+ return document.querySelector('meta[name="csrf-token"]')?.content || '';
+ }
+
+ showLoading() {
+ const container = document.getElementById('subscriptions-list');
+ container.innerHTML = `
+ <div class="text-center p-4">
+ <div class="spinner-border" role="status">
+ <span class="visually-hidden">Loading...</span>
+ </div>
+ </div>
+ `;
+ }
+
+ showError(message) {
+ // Use existing alert system if available
+ if (window.showAlert) {
+ window.showAlert(message, 'error');
+ } else {
+ alert(message);
+ }
+ }
+
+ showSuccess(message) {
+ if (window.showAlert) {
+ window.showAlert(message, 'success');
+ } else {
+ console.log(message);
+ }
+ }
+}
+
+// Initialize when DOM is ready
+document.addEventListener('DOMContentLoaded', () => {
+ window.subscriptionManager = new SubscriptionManager();
+ window.subscriptionManager.initialize();
+});
diff --git a/src/local_deep_research/web/static/js/news-enhancements.js b/src/local_deep_research/web/static/js/news-enhancements.js
new file mode 100644
index 0000000000..47b1ef6122
--- /dev/null
+++ b/src/local_deep_research/web/static/js/news-enhancements.js
@@ -0,0 +1,139 @@
+// News Page Design Enhancements
+document.addEventListener('DOMContentLoaded', function() {
+
+ // Add smooth hover effects to news items
+ const newsItems = document.querySelectorAll('.news-item');
+ newsItems.forEach((item, index) => {
+ // Add staggered animation
+ item.style.animationDelay = `${index * 0.1}s`;
+
+ // Add interactive hover effects
+ item.addEventListener('mouseenter', function() {
+ this.style.transform = 'translateY(-4px)';
+ });
+
+ item.addEventListener('mouseleave', function() {
+ this.style.transform = 'translateY(0)';
+ });
+ });
+
+ // Enhance vote buttons with ripple effect
+ const voteButtons = document.querySelectorAll('.vote-btn');
+ voteButtons.forEach(btn => {
+ btn.addEventListener('click', function(e) {
+ // Create ripple effect
+ const ripple = document.createElement('span');
+ ripple.classList.add('ripple');
+ this.appendChild(ripple);
+
+ const rect = this.getBoundingClientRect();
+ const size = Math.max(rect.width, rect.height);
+ const x = e.clientX - rect.left - size / 2;
+ const y = e.clientY - rect.top - size / 2;
+
+ ripple.style.width = ripple.style.height = size + 'px';
+ ripple.style.left = x + 'px';
+ ripple.style.top = y + 'px';
+
+ setTimeout(() => ripple.remove(), 600);
+ });
+ });
+
+ // Enhance topic pills
+ const topicPills = document.querySelectorAll('.topic-pill');
+ topicPills.forEach(pill => {
+ pill.addEventListener('click', function() {
+ // Add click animation
+ this.style.transform = 'scale(0.95)';
+ setTimeout(() => {
+ this.style.transform = 'scale(1)';
+ }, 150);
+ });
+ });
+
+ // Add loading skeleton when refreshing
+ const refreshBtn = document.getElementById('refresh-feed-btn');
+ if (refreshBtn) {
+ const originalRefresh = refreshBtn.onclick;
+ refreshBtn.onclick = function() {
+ // Add loading state
+ const newsContainer = document.querySelector('.news-cards-container');
+ if (newsContainer) {
+ newsContainer.style.opacity = '0.5';
+ newsContainer.classList.add('skeleton-loader');
+ }
+
+ // Call original function
+ if (originalRefresh) originalRefresh.call(this);
+
+ // Remove loading state after delay
+ setTimeout(() => {
+ if (newsContainer) {
+ newsContainer.style.opacity = '1';
+ newsContainer.classList.remove('skeleton-loader');
+ }
+ }, 1000);
+ };
+ }
+
+ // Enhance search input
+ const searchInput = document.getElementById('news-search');
+ if (searchInput) {
+ searchInput.addEventListener('focus', function() {
+ this.parentElement.style.transform = 'scale(1.02)';
+ });
+
+ searchInput.addEventListener('blur', function() {
+ this.parentElement.style.transform = 'scale(1)';
+ });
+ }
+
+ // Add smooth scroll behavior
+ document.documentElement.style.scrollBehavior = 'smooth';
+
+ // Enhance impact bars with animation
+ const impactBars = document.querySelectorAll('.impact-fill');
+ impactBars.forEach(bar => {
+ const width = bar.style.width;
+ bar.style.width = '0';
+ setTimeout(() => {
+ bar.style.width = width;
+ }, 500);
+ });
+
+ // Add parallax effect to header
+ const header = document.querySelector('.feed-header-section');
+ if (header) {
+ window.addEventListener('scroll', () => {
+ const scrolled = window.pageYOffset;
+ const parallax = -scrolled * 0.1;
+ header.style.transform = `translateY(${parallax}px)`;
+ });
+ }
+});
+
+// CSS for ripple effect
+const style = document.createElement('style');
+style.textContent = `
+ .ripple {
+ position: absolute;
+ border-radius: 50%;
+ background: rgba(255, 255, 255, 0.5);
+ transform: scale(0);
+ animation: ripple-animation 0.6s ease-out;
+ pointer-events: none;
+ }
+
+ @keyframes ripple-animation {
+ to {
+ transform: scale(4);
+ opacity: 0;
+ }
+ }
+
+ .vote-btn {
+ position: relative;
+ overflow: hidden;
+ }
+`;
+document.head.appendChild(style);
diff --git a/src/local_deep_research/web/static/js/pages/news.js b/src/local_deep_research/web/static/js/pages/news.js
new file mode 100644
index 0000000000..baa787f3ee
--- /dev/null
+++ b/src/local_deep_research/web/static/js/pages/news.js
@@ -0,0 +1,3112 @@
+// News Page JavaScript - Following LDR patterns
+
+// Global state
+let currentUser = localStorage.getItem('ldr_user_id') || 'anonymous';
+let activeSubscription = 'all';
+let newsItems = [];
+let subscriptions = [];
+let lastVisitTime = null;
+let seenNewsIds = new Set();
+let searchHistory = [];
+let autoRefreshInterval = null;
+let lastRefreshTime = new Date();
+let activeTimeFilter = 'all';
+let activeImpactThreshold = 0;
+let readNewsIds = new Set();
+let expandedNewsIds = new Set();
+let savedNewsIds = new Set();
+
+// Optimized news table query template
+const getNewsTableQuery = () => `Find UP TO 10 IMPORTANT breaking news stories from TODAY ${new Date().toLocaleDateString()} ONLY.
+
+START YOUR RESPONSE DIRECTLY WITH THE TABLE. NO INTRODUCTION OR PREAMBLE.
+
+CRITICAL: All information MUST be from real, verifiable sources. DO NOT invent or fabricate any news, events, or details. Only report what you find from actual news sources.
+
+OUTPUT FORMAT: Begin immediately with a markdown table using this exact structure:
+
+| SOURCES | DATE | HEADLINE | CATEGORY | WHAT HAPPENED | ANALYSIS | IMPACT |
+|---------|------|----------|----------|---------------|----------|--------|
+| [Citation numbers] | [YYYY-MM-DD] | [Descriptive headline] | [War/Security/Economy/Disaster/Politics/Tech] | [3 sentences max from actual sources] | [Why it matters + What happens next + Historical context] | [1-10 score] | [Status] |
+
+IMPORTANT: In the SOURCES column, list the citation numbers (e.g., [1, 3, 5]) that support this news item. These should match the numbered references at the end of your report.
+
+Example row:
+| [2, 4, 7] | 2025-01-12 | Major Earthquake Strikes Southern California | Disaster | A 7.1 magnitude earthquake hit near Los Angeles causing structural damage. Emergency services report multiple injuries. Aftershocks continue to affect the region. | Major infrastructure test for earthquake preparedness systems. FEMA mobilizing resources. Similar to 1994 Northridge event but with modern building codes. | 9 | Ongoing |
+
+SEARCH STRATEGY:
+1. breaking news today major incident developing impact
+2. crisis death disaster announcement today hours ago
+3. site:reuters.com OR site:bbc.com OR site:cnn.com today
+4. geopolitical economic security emergency today
+
+PRIORITIZE BY REAL-WORLD IMPACT:
+- Active conflicts with casualties (Impact 8-10)
+- Natural disasters affecting thousands (Impact 7-9)
+- Economic shocks (>3% market moves) (Impact 6-8)
+- Major political shifts (Impact 5-7)
+- Critical infrastructure failures (Impact 6-9)
+
+DIVERSITY IS MANDATORY: You MUST find 10 COMPLETELY DIFFERENT events. Examples of what NOT to do:
+- ✗ BAD: Multiple stories about the same earthquake (initial report, death toll update, rescue efforts)
+- ✗ BAD: Multiple stories about the same political event (announcement, reactions, analysis)
+- ✓ GOOD: One earthquake in Japan, one political crisis in Europe, one economic news from US, etc.
+
+If you can only find 7 truly distinct events, show 7. Do NOT pad with duplicate coverage.
+
+REQUIREMENTS:
+- Only include stories found from real sources
+- Sort by IMPACT score (highest first)
+- Each row must be complete with all columns filled
+- Keep analysis concise but informative
+- Verify sources are from today
+- If insufficient real news is found, include fewer rows rather than inventing content
+
+After the table, add:
+- **THE BIG PICTURE**: One paragraph connecting today's major events (based on actual findings)
+- **WATCH FOR**: 3 bullet points on what to monitor in next 24 hours`;
+
+// Initialize on page load
+document.addEventListener('DOMContentLoaded', function() {
+ console.log('News page DOMContentLoaded');
+ initializeNewsPage();
+});
+
+async function initializeNewsPage() {
+ console.log('initializeNewsPage called');
+
+ // Load last visit time and seen items
+ loadVisitTracking();
+
+ // Load search history
+ loadSearchHistory();
+
+ // Load read status
+ loadReadStatus();
+
+ // Load saved items
+ loadSavedItems();
+
+ // Load expanded state
+ loadExpandedState();
+
+ // Set up event listeners first
+ setupEventListeners();
+
+ // Load initial data in proper order
+ await loadSubscriptions();
+ await loadNewsFeed(); // Load main feed first
+
+ // Check for active news research
+ await checkActiveNewsResearch();
+
+ // Then check for other updates
+ checkPriorityStatus();
+
+ // Set up auto-refresh
+ setInterval(checkPriorityStatus, 30000);
+
+ // Update visit time when leaving page
+ window.addEventListener('beforeunload', () => {
+ saveVisitTracking();
+ saveSearchHistory();
+ saveReadStatus();
+ });
+}
+
+function setupEventListeners() {
+ // Search button
+ const searchBtn = document.getElementById('search-btn');
+ if (searchBtn) {
+ searchBtn.addEventListener('click', handleSearchSubmit);
+ }
+
+ // Create subscription button
+ const createSubBtn = document.getElementById('create-subscription-btn');
+ if (createSubBtn) {
+ console.log('Setting up create subscription button event listener');
+ createSubBtn.addEventListener('click', () => {
+ console.log('Create subscription button clicked');
+ showNewsSubscriptionModal('', '');
+ });
+ } else {
+ console.error('Create subscription button not found!');
+ }
+
+ // Run Once button in subscription modal
+ const runTemplateBtn = document.getElementById('run-template-btn');
+ if (runTemplateBtn) {
+ runTemplateBtn.addEventListener('click', async () => {
+ const query = document.getElementById('news-subscription-query').value;
+ console.log('Run Once clicked, query:', query);
+ if (query) {
+ // Close modal first
+ const modalElement = document.getElementById('newsSubscriptionModal');
+ if (modalElement) {
+ const modal = bootstrap.Modal.getInstance(modalElement);
+ if (modal) modal.hide();
+ }
+
+ // Use the same advanced search function that the search uses
+ console.log('Calling performAdvancedNewsSearch with query:', query);
+ await performAdvancedNewsSearch(query);
+ } else {
+ console.error('No query found in news-subscription-query input');
+ showAlert('Please enter a query', 'warning');
+ }
+ });
+ }
+
+ // Search input - handle Enter key
+ const searchInput = document.getElementById('news-search');
+ if (searchInput) {
+ searchInput.addEventListener('keypress', (e) => {
+ if (e.key === 'Enter') {
+ handleSearchSubmit(e);
+ }
+ });
+ }
+
+ // Table view toggle
+ const tableToggle = document.getElementById('table-view-toggle');
+ if (tableToggle) {
+ tableToggle.addEventListener('change', (e) => toggleTableView(e.target.checked));
+ }
+
+ // Impact threshold
+ const impactSlider = document.getElementById('impact-filter');
+ if (impactSlider) {
+ impactSlider.addEventListener('input', (e) => {
+ const impactValue = document.querySelector('.impact-value');
+ if (impactValue) {
+ impactValue.textContent = e.target.value + '+';
+ }
+ activeImpactThreshold = parseInt(e.target.value);
+ renderNewsItems();
+ });
+ }
+
+ // Event delegation for topic tags in news items
+ document.addEventListener('click', (e) => {
+ if (e.target.classList.contains('topic-tag')) {
+ const topic = e.target.getAttribute('data-topic');
+ if (topic) {
+ filterByTopic(topic);
+ }
+ }
+ });
+
+ // Auto-refresh toggle
+ const autoRefreshToggle = document.getElementById('auto-refresh');
+ if (autoRefreshToggle) {
+ autoRefreshToggle.addEventListener('change', (e) => {
+ if (e.target.checked) {
+ startAutoRefresh();
+ } else {
+ stopAutoRefresh();
+ }
+ });
+
+ // Start auto-refresh if enabled by default
+ if (autoRefreshToggle.checked) {
+ startAutoRefresh();
+ }
+ }
+
+ // Time filter buttons
+ const timeFilters = document.querySelectorAll('.time-filter-group .filter-btn');
+ timeFilters.forEach(btn => {
+ btn.addEventListener('click', (e) => {
+ // Remove active class from all buttons
+ timeFilters.forEach(b => b.classList.remove('active'));
+ // Add active class to clicked button
+ e.target.classList.add('active');
+ // Set active time filter
+ activeTimeFilter = e.target.dataset.time;
+ // Re-render news items with filter
+ renderNewsItems();
+ });
+ });
+
+ // Category filters removed - LDR uses dynamic topics instead
+
+ // Event delegation for news card clicks
+ document.addEventListener('click', (e) => {
+ // Find the closest news-item parent
+ const newsItem = e.target.closest('.news-item');
+ if (newsItem) {
+ // Check if click was on a button, link, or other interactive element
+ const isInteractive = e.target.closest('button, a, .vote-btn, .topic-tag, input, textarea');
+
+ if (!isInteractive) {
+ // Get the news item ID
+ const newsId = newsItem.dataset.newsId;
+ const item = newsItems.find(n => n.id === newsId);
+
+ if (item) {
+ // Mark as seen immediately
+ markNewsAsSeen(newsId);
+ saveVisitTracking();
+
+ // Navigate to the full report
+ const url = item.source_url || `/results/${item.research_id}`;
+ window.location.href = url;
+ }
+ }
+ }
+ });
+}
+
+// Search handling
+async function handleSearchSubmit(e) {
+ if (e && e.preventDefault) {
+ e.preventDefault();
+ }
+ const query = document.getElementById('news-search').value.trim();
+
+ if (!query) {
+ showAlert('Please enter a search query', 'warning');
+ return;
+ }
+
+ // Add to search history
+ addToSearchHistory(query, 'filter');
+
+ // Always filter the current results
+ await loadNewsFeed(query);
+}
+
+// Clear search and reload feed
+function clearSearch() {
+ document.getElementById('news-search').value = '';
+ loadNewsFeed();
+}
+
+// Advanced search using LDR search system
+async function performAdvancedNewsSearch(query) {
+ showAlert('Performing advanced news analysis...', 'info');
+
+ try {
+ const requestData = {
+ query: query,
+ mode: 'quick',
+ metadata: {
+ is_news_search: true,
+ search_type: 'news_analysis',
+ display_in: 'news_feed'
+ }
+ };
+
+ console.log('Sending research request:', requestData);
+
+ const response = await fetch('/api/start_research', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': getCSRFToken()
+ },
+ body: JSON.stringify(requestData)
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ console.log('Research API response:', data);
+ if (data.status === 'success' && data.research_id) {
+ showAlert('Analyzing news... Results will appear below when ready.', 'info');
+
+ // Show loading state in news feed FIRST
+ const container = document.getElementById('news-feed-content');
+ container.innerHTML = `
+ <div class="news-card priority-high">
+ <div class="news-header">
+ <h2 class="news-title">
+ <i class="bi bi-hourglass-split spinning"></i>
+ Analyzing: "${query.substring(0, 60)}..."
+ </h2>
+ </div>
+ <div class="news-meta">
+ <span><i class="bi bi-info-circle"></i> Research ID: ${data.research_id}</span>
+ <span><i class="bi bi-clock"></i> Started just now</span>
+ </div>
+ <div class="news-summary">
+ <div class="progress">
+ <div class="progress-bar progress-bar-striped progress-bar-animated"
+ role="progressbar" style="width: 10%"></div>
+ </div>
+ <p class="mt-2">Searching for breaking news and analyzing importance...</p>
+ </div>
+ </div>
+ `;
+
+ // Poll for results
+ pollForNewsResearchResults(data.research_id, query);
+
+ // Try to create subscription but don't let it block the loading
+ createSubscriptionFromSearch(query, data.research_id).catch(err => {
+ console.error('Failed to create subscription:', err);
+ });
+ } else {
+ console.error('Unexpected response format:', data);
+ showAlert('Failed to start research - unexpected response', 'error');
+ }
+ } else {
+ console.error('Research API error response:', response.status, response.statusText);
+ const errorData = await response.json().catch(() => ({}));
+ console.error('Error data:', errorData);
+ showAlert(errorData.message || 'Failed to perform advanced search', 'error');
+ }
+ } catch (error) {
+ console.error('Error in advanced search:', error);
+ showAlert('Error performing search', 'error');
+ }
+}
+
+// Create subscription from search
+async function createSubscriptionFromSearch(query, researchId) {
+ try {
+ const response = await fetch('/news/api/subscribe', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': getCSRFToken()
+ },
+ body: JSON.stringify({
+ user_id: currentUser,
+ query: query,
+ subscription_type: 'search',
+ refresh_hours: 1,
+ metadata: {
+ research_id: researchId,
+ is_advanced_query: true
+ }
+ })
+ });
+
+ if (response.ok) {
+ await loadSubscriptions();
+ showAlert('Advanced news subscription created!', 'success');
+ }
+ } catch (error) {
+ console.error('Error creating subscription:', error);
+ }
+}
+
+// Display advanced results
+function displayAdvancedResults(data) {
+ const content = data.formatted_response || '';
+
+ // Check for table content
+ if (content.includes('<table>') || content.includes('|')) {
+ document.getElementById('table-view-toggle').checked = true;
+ toggleTableView(true);
+ parseAndDisplayTable(content);
+ } else {
+ showAlert('Results loaded. Check your feed!', 'success');
+ loadNewsFeed();
+ }
+}
+
+// Parse and display news table
+function parseAndDisplayTable(content) {
+ const tableBody = document.getElementById('news-table-body');
+ const rows = [];
+
+ // Parse markdown table
+ const lines = content.split('\n');
+ let inTable = false;
+
+ for (const line of lines) {
+ // Check for table header - now includes SOURCES as first column
+ if ((line.includes('SOURCES') || line.includes('SOURCE')) && line.includes('HEADLINE')) {
+ inTable = true;
+ continue;
+ }
+ // Skip separator lines
+ if (line.includes('---') && line.includes('|')) {
+ continue;
+ }
+ if (inTable && line.includes('|')) {
+ const cells = line.split('|').map(cell => cell.trim()).filter(cell => cell);
+ if (cells.length >= 5) { // At least SOURCES, DATE/TIME, HEADLINE, etc.
+ rows.push(cells);
+ }
+ }
+ }
+
+ // Render rows with SOURCES as first column
+ if (rows.length > 0) {
+ tableBody.innerHTML = rows.map(row => {
+ // Check if we have an impact score column (usually second to last)
+ const impactIndex = row.length >= 7 ? 6 : (row.length >= 6 ? 5 : -1);
+ const hasImpact = impactIndex > 0 && !isNaN(parseInt(row[impactIndex]));
+
+ return `
+ <tr>
+ <td>${row[0] || ''}</td>
+ <td class="text-nowrap">${row[1] || ''}</td>
+ <td><strong>${row[2] || ''}</strong></td>
+ <td>${row[3] || ''}</td>
+ <td>${row[4] || ''}</td>
+ <td>${row[5] || ''}</td>
+ ${hasImpact ? `
+ <td>
+ <span class="impact-badge ${getImpactClass(row[impactIndex])}">
+ ${row[impactIndex] || 'N/A'}
+ </span>
+ </td>
+ ` : row[6] ? `
+ <td>${row[6] || ''}</td>
+ ` : ''}
+ </tr>
+ `}).join('');
+ }
+}
+
+// Simple subscription
+async function createSimpleSubscription(query) {
+ showAlert(`Creating subscription for: ${query}`, 'info');
+
+ try {
+ const response = await fetch('/news/api/subscribe', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': getCSRFToken()
+ },
+ body: JSON.stringify({
+ user_id: currentUser,
+ query: query,
+ subscription_type: 'search',
+ refresh_hours: 1
+ })
+ });
+
+ if (response.ok) {
+ await loadSubscriptions();
+ await loadNewsFeed();
+ showAlert('Subscription created!', 'success');
+ document.getElementById('news-query').value = '';
+ } else {
+ showAlert('Failed to create subscription', 'error');
+ }
+ } catch (error) {
+ console.error('Error creating subscription:', error);
+ showAlert('Error creating subscription', 'error');
+ }
+}
+
+// Load subscriptions
+async function loadSubscriptions() {
+ try {
+ const response = await fetch(`/news/api/subscriptions/${currentUser}`);
+ if (response.ok) {
+ const data = await response.json();
+ subscriptions = data.subscriptions || [];
+ // renderSubscriptions(); // Removed sidebar subscription list
+ }
+ } catch (error) {
+ console.error('Error loading subscriptions:', error);
+ }
+}
+
+// Render subscriptions - REMOVED: Subscription list moved to dedicated page
+/* function renderSubscriptions() {
+ const container = document.getElementById('sidebar-subscriptions-list');
+
+ // Add "All" option
+ let html = `
+ <div class="subscription-item ${activeSubscription === 'all' ? 'active' : ''}"
+ onclick="selectSubscription('all')">
+ <div class="subscription-type">ALL FEEDS</div>
+ <div class="subscription-query">Combined News Feed</div>
+ <div class="subscription-meta">All your subscriptions</div>
+ </div>
+ <div class="subscription-item ${activeSubscription === 'saved' ? 'active' : ''}"
+ onclick="selectSubscription('saved')">
+ <div class="subscription-type">SAVED</div>
+ <div class="subscription-query">Bookmarked Items</div>
+ <div class="subscription-meta">${savedNewsIds.size} saved items</div>
+ </div>
+ `;
+
+ // Add user subscriptions
+ subscriptions.forEach(sub => {
+ const typeLabel = sub.type === 'search' ? 'SEARCH' : 'TOPIC';
+ const query = sub.query || sub.topic || 'Unknown';
+ const nextRefresh = sub.next_refresh ? new Date(sub.next_refresh).toLocaleString() : 'Soon';
+
+ html += `
+ <div class="subscription-item ${activeSubscription === sub.id ? 'active' : ''}"
+ onclick="selectSubscription('${sub.id}')">
+ <div class="subscription-header">
+ <div>
+ <div class="subscription-type">${typeLabel}</div>
+ <div class="subscription-query">${query}</div>
+ <div class="subscription-meta">Next: ${nextRefresh}</div>
+ </div>
+ <button class="btn btn-sm btn-ghost" onclick="showSubscriptionHistory('${sub.id}'); event.stopPropagation();" title="View history">
+ <i class="bi bi-clock-history"></i>
+ </button>
+ </div>
+ </div>
+ `;
+ });
+
+ container.innerHTML = html;
+} */
+
+// Select subscription
+function selectSubscription(subId) {
+ activeSubscription = subId;
+ // renderSubscriptions(); // Removed sidebar subscription list
+ loadNewsFeed();
+}
+
+// Load news feed
+async function loadNewsFeed(focus = null) {
+ const container = document.getElementById('news-feed-content');
+ if (!container) {
+ console.error('News container not found!');
+ return;
+ }
+ container.innerHTML = '<div class="loading-placeholder"><div class="loading-spinner"></div><p>Loading news...</p></div>';
+
+ // Update feed header if subscription is selected
+ updateFeedHeader();
+
+ // Handle saved items view
+ if (activeSubscription === 'saved') {
+ loadSavedNewsFeed();
+ return;
+ }
+
+ try {
+ const params = new URLSearchParams({
+ user_id: currentUser,
+ limit: 20,
+ use_cache: true
+ });
+
+ if (focus) params.append('focus', focus);
+ if (activeSubscription !== 'all') params.append('subscription_id', activeSubscription);
+
+ console.log('Fetching news from:', `/news/api/feed?${params}`);
+ const response = await fetch(`/news/api/feed?${params}`);
+ console.log('Response status:', response.status);
+
+ if (response.ok) {
+ const data = await response.json();
+ newsItems = data.news_items || [];
+ console.log(`Loaded ${newsItems.length} news items from API`);
+ console.log('API response:', data);
+ if (newsItems.length > 0) {
+ console.log('First news item:', newsItems[0]);
+ }
+
+ // Apply client-side filtering if focus is provided
+ if (focus) {
+ const searchTerm = focus.toLowerCase();
+ newsItems = newsItems.filter(item => {
+ const headline = (item.headline || '').toLowerCase();
+ const summary = (item.summary || '').toLowerCase();
+ const query = (item.query || '').toLowerCase();
+ const topics = (item.topics || []).map(t => t.toLowerCase()).join(' ');
+
+ return headline.includes(searchTerm) ||
+ summary.includes(searchTerm) ||
+ query.includes(searchTerm) ||
+ topics.includes(searchTerm);
+ });
+ console.log(`Filtered to ${newsItems.length} items matching "${focus}"`);
+ }
+
+ renderNewsItems(focus);
+ extractTrendingTopics();
+ updateBulkActionsBar();
+ } else {
+ console.error('Failed to load news feed. Status:', response.status);
+ const errorText = await response.text();
+ console.error('Error response:', errorText);
+ container.innerHTML = `<p class="error-message">Failed to load news feed (${response.status})</p>`;
+ }
+ } catch (error) {
+ console.error('Error loading news:', error);
+ container.innerHTML = '<p class="error-message">Error loading news feed</p>';
+ }
+}
+
+// Render news items
+function renderNewsItems(searchQuery = null) {
+ const container = document.getElementById('news-feed-content');
+
+ console.log('renderNewsItems called with', newsItems.length, 'items');
+
+ // Apply all filters
+ let itemsToRender = newsItems;
+
+ // Apply topic filter if active
+ if (activeTopicFilter) {
+ itemsToRender = itemsToRender.filter(item => {
+ return item.topics && item.topics.includes(activeTopicFilter);
+ });
+ }
+
+ // Apply time filter
+ if (activeTimeFilter && activeTimeFilter !== 'all') {
+ itemsToRender = itemsToRender.filter(item => {
+ return isWithinTimeFilter(item, activeTimeFilter);
+ });
+ }
+
+ // Category filter removed - using dynamic topics instead
+
+ // Apply impact filter
+ if (activeImpactThreshold > 0) {
+ itemsToRender = itemsToRender.filter(item => {
+ return item.impact_score >= activeImpactThreshold;
+ });
+ }
+
+ // Preserve any existing filter bar
+ const existingFilterBar = container.querySelector('.active-filter-bar');
+
+ // Debug logging removed - was causing console spam
+
+ if (itemsToRender.length === 0) {
+ // Build filter status message
+ let filterMessage = [];
+ if (searchQuery) filterMessage.push(`search: "${searchQuery}"`);
+ if (activeTopicFilter) filterMessage.push(`topic: ${activeTopicFilter}`);
+ if (activeTimeFilter !== 'all') filterMessage.push(`time: ${activeTimeFilter}`);
+ if (activeImpactThreshold > 0) filterMessage.push(`impact ≥ ${activeImpactThreshold}`);
+
+ const hasFilters = filterMessage.length > 0;
+ const filterText = hasFilters ? ` matching ${filterMessage.join(', ')}` : '';
+
+ container.innerHTML = `
+ <div class="empty-state">
+ <i class="fas fa-newspaper"></i>
+ <h3>No news items${filterText}</h3>
+ <p>${hasFilters ? 'Try adjusting your filters or' : 'Start by searching for topics or creating subscriptions'}</p>
+ ${hasFilters ? `
+ <button class="btn btn-sm btn-outline-secondary mt-2" onclick="clearAllFilters()">
+ <i class="bi bi-x-circle"></i> Clear all filters
+ </button>
+ ` : ''}
+ </div>
+ `;
+ // Re-add filter bar if it existed
+ if (existingFilterBar && activeTopicFilter) {
+ container.insertBefore(existingFilterBar, container.firstChild);
+ }
+ return;
+ }
+
+ // Add search indicator if searching
+ let searchIndicatorHtml = '';
+ if (searchQuery) {
+ searchIndicatorHtml = `
+ <div class="search-indicator alert alert-info">
+ <i class="bi bi-search"></i> Showing results for: <strong>"${searchQuery}"</strong>
+ <button class="btn btn-sm btn-link" onclick="clearSearch()">
+ <i class="bi bi-x-circle"></i> Clear search
+ </button>
+ </div>
+ `;
+ }
+
+ container.innerHTML = searchIndicatorHtml + itemsToRender.map(item => {
+ const priorityClass = getPriorityClass(item.impact_score);
+ const isNew = isNewsNew(item);
+ const isRead = readNewsIds.has(item.id);
+ const newClasses = isNew ? 'is-new fade-in-new' : '';
+ const readClasses = isRead ? 'is-read' : 'is-unread';
+
+ // Add to seen items if rendering
+ if (!seenNewsIds.has(item.id)) {
+ // Mark as seen after a delay
+ setTimeout(() => markNewsAsSeen(item.id), 3000);
+ }
+
+ // Render findings if available - limit to a reasonable preview
+ let findingsHtml = '';
+ if (item.findings) {
+ // Limit findings to first 800 characters for preview
+ const findingsPreview = item.findings.substring(0, 800) + (item.findings.length > 800 ? '...' : '');
+
+ // Check if we have the renderMarkdown function available
+ if (typeof window.ui !== 'undefined' && window.ui.renderMarkdown) {
+ findingsHtml = `<div class="news-findings">${window.ui.renderMarkdown(findingsPreview)}</div>`;
+ } else if (typeof renderMarkdown !== 'undefined') {
+ findingsHtml = `<div class="news-findings">${renderMarkdown(findingsPreview)}</div>`;
+ } else {
+ // Basic fallback rendering
+ const basicHtml = findingsPreview
+ .replace(/\n\n/g, '</p><p>')
+ .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
+ .replace(/\*(.*?)\*/g, '<em>$1</em>')
+ .replace(/^- (.+)$/gm, '<li>$1</li>')
+ .replace(/(<li>.*<\/li>)/s, '<ul>$1</ul>');
+ findingsHtml = `<div class="news-findings"><p>${basicHtml}</p></div>`;
+ }
+ } else if (item.summary) {
+ // Fallback to summary if no findings
+ findingsHtml = `<div class="news-summary">${item.summary}</div>`;
+ }
+
+ // Render topics as clickable tags
+ let topicsHtml = '';
+ if (item.topics && item.topics.length > 0) {
+ const topicTags = item.topics.map(topic =>
+ `<span class="topic-tag" data-topic="${topic.replace(/"/g, '&quot;')}" title="Click to filter by ${topic}">${topic}</span>`
+ ).join('');
+ topicsHtml = `<div class="news-topics">${topicTags}</div>`;
+ }
+
+ const isExpanded = expandedNewsIds.has(item.id);
+
+ return `
+ <div class="news-item priority-${priorityClass} ${newClasses} ${readClasses} ${isExpanded ? 'is-expanded' : ''}" data-news-id="${item.id}">
+ ${isNew ? '<span class="new-indicator">New</span>' : ''}
+ <div class="news-item-header">
+ <div class="news-headline">${item.headline}</div>
+ <div class="news-actions-menu">
+ <button class="btn btn-sm btn-ghost" onclick="toggleReadStatus('${item.id}')" title="${isRead ? 'Mark as unread' : 'Mark as read'}">
+ <i class="bi ${isRead ? 'bi-envelope-open' : 'bi-envelope'}"></i>
+ </button>
+ <div class="dropdown">
+ <button class="btn btn-sm btn-ghost" data-bs-toggle="dropdown" title="More actions">
+ <i class="bi bi-three-dots-vertical"></i>
+ </button>
+ <ul class="dropdown-menu dropdown-menu-end">
+ <li><a class="dropdown-item" href="#" onclick="shareNews('${item.id}'); return false;">
+ <i class="bi bi-share"></i> Share
+ </a></li>
+ <li><a class="dropdown-item" href="#" onclick="copyNewsLink('${item.id}'); return false;">
+ <i class="bi bi-link-45deg"></i> Copy Link
+ </a></li>
+ <li><a class="dropdown-item" href="#" onclick="exportToMarkdown('${item.id}'); return false;">
+ <i class="bi bi-markdown"></i> Export as Markdown
+ </a></li>
+ <li><hr class="dropdown-divider"></li>
+ <li><a class="dropdown-item" href="#" onclick="hideNewsItem('${item.id}'); return false;">
+ <i class="bi bi-eye-slash"></i> Hide this item
+ </a></li>
+ <li><a class="dropdown-item text-danger" href="#" onclick="reportIssue('${item.id}'); return false;">
+ <i class="bi bi-flag"></i> Report issue
+ </a></li>
+ </ul>
+ </div>
+ </div>
+ </div>
+ <div class="news-meta">
+ <span class="news-category">${item.category || 'General'}</span>
+ <span class="impact-indicator">
+ Impact:
+ <div class="impact-bar">
+ <div class="impact-fill" style="width: ${item.impact_score * 10}%"></div>
+ </div>
+ ${item.impact_score}/10
+ </span>
+ <span><i class="fas fa-calendar"></i> ${formatNewsDate(item.created_at) || item.time_ago || 'Recently'}</span>
+ </div>
+ ${findingsHtml}
+ ${topicsHtml}
+ ${renderSourceLinks(item.links)}
+ <div class="news-actions">
+ <div class="vote-buttons">
+ <button class="vote-btn" onclick="vote('${item.id}', 'up')">
+ <i class="fas fa-thumbs-up"></i> ${item.upvotes || 0}
+ </button>
+ <button class="vote-btn" onclick="vote('${item.id}', 'down')">
+ <i class="fas fa-thumbs-down"></i> ${item.downvotes || 0}
+ </button>
+ </div>
+ <div class="action-buttons">
+ <a href="${item.source_url || `/results/${item.research_id}`}" class="btn btn-primary btn-sm">
+ <i class="fas fa-file-alt"></i> View Full Report
+ </a>
+ <button class="btn btn-secondary btn-sm save-btn" onclick="toggleSaveItem('${item.id}')" title="${savedNewsIds.has(item.id) ? 'Remove from saved' : 'Save for later'}">
+ <i class="${savedNewsIds.has(item.id) ? 'bi bi-bookmark-fill' : 'bi bi-bookmark'}"></i>
+ </button>
+ </div>
+ </div>
+ <button class="expand-toggle-btn" onclick="toggleExpanded('${item.id}')" title="${isExpanded ? 'Show less' : 'Show more'}">
+ <i class="bi bi-chevron-${isExpanded ? 'up' : 'down'}"></i>
+ ${isExpanded ? 'Show less' : 'Show more'}
+ </button>
+ </div>
+ `;
+ }).join('');
+
+ // Update table view if active
+ const tableToggle = document.getElementById('table-view-toggle');
+ if (tableToggle && tableToggle.checked) {
+ populateNewsTable();
+ }
+}
+
+// Populate news table
+function populateNewsTable() {
+ const tableBody = document.getElementById('news-table-body');
+
+ if (!tableBody) {
+ console.error('Table body not found');
+ return;
+ }
+
+ if (newsItems.length === 0) {
+ tableBody.innerHTML = '<tr><td colspan="7" style="text-align: center;">No news items to display</td></tr>';
+ return;
+ }
+
+ tableBody.innerHTML = newsItems.map(item => {
+ // Extract or format date/time
+ const dateTime = formatNewsDateTime(item.created_at || item.time_ago);
+
+ const impactClass = getImpactClass(item.impact_score);
+ const summary = item.summary || '';
+ const [whatHappened, ...analysisLines] = summary.split('. ');
+ const analysis = analysisLines.join('. ');
+ const sources = item.sources || [item.source_url];
+ const sourceLinks = sources.map((src, idx) =>
+ `<a href="${src}" target="_blank">[${idx + 1}]</a>`
+ ).join(' ');
+
+ return `
+ <tr>
+ <td>${sourceLinks}</td>
+ <td class="text-nowrap">${dateTime}</td>
+ <td><strong>${item.headline}</strong></td>
+ <td>${item.category || 'General'}</td>
+ <td>${whatHappened || 'Details pending...'}</td>
+ <td>${analysis || 'Analysis in progress...'}</td>
+ <td>
+ <span class="impact-badge ${impactClass}">
+ ${item.impact_score}/10
+ </span>
+ </td>
+ </tr>
+ `;
+ }).join('');
+}
+
+// Format date/time for news items
+function formatNewsDateTime(dateStr) {
+ if (!dateStr) return new Date().toLocaleString('en-US', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
+
+ // If it's already a formatted time like "2 hours ago"
+ if (dateStr.includes('ago') || dateStr.includes('Just now')) {
+ return dateStr;
+ }
+
+ // Otherwise parse and format the date
+ try {
+ const date = new Date(dateStr);
+ return date.toLocaleString('en-US', {
+ month: '2-digit',
+ day: '2-digit',
+ hour: '2-digit',
+ minute: '2-digit',
+ hour12: false
+ });
+ } catch (e) {
+ return dateStr;
+ }
+}
+
+// Format date for news items in ISO format with time
+function formatNewsDate(dateStr) {
+ if (!dateStr) return null;
+
+ try {
+ const date = new Date(dateStr);
+ // Return ISO date and time format YYYY-MM-DD HH:MM
+ const isoDate = date.toISOString().split('T')[0];
+ const hours = String(date.getUTCHours()).padStart(2, '0');
+ const minutes = String(date.getUTCMinutes()).padStart(2, '0');
+ return `${isoDate} ${hours}:${minutes}`;
+ } catch (e) {
+ return null;
+ }
+}
+
+// Helper functions
+function getPriorityClass(score) {
+ if (score >= 7) return 'high';
+ if (score >= 4) return 'medium';
+ return 'low';
+}
+
+function getImpactClass(score) {
+ const num = parseInt(score);
+ if (num >= 7) return 'impact-high';
+ if (num >= 4) return 'impact-medium';
+ return 'impact-low';
+}
+
+// Vote on news item
+async function vote(newsId, voteType) {
+ try {
+ const response = await fetch(`/news/api/feedback/${newsId}`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': getCSRFToken()
+ },
+ body: JSON.stringify({
+ user_id: currentUser,
+ vote: voteType
+ })
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ // Update UI
+ const item = document.querySelector(`[data-news-id="${newsId}"]`);
+ if (item) {
+ const upBtn = item.querySelector('.vote-btn:first-child');
+ const downBtn = item.querySelector('.vote-btn:last-child');
+ upBtn.innerHTML = `<i class="fas fa-thumbs-up"></i> ${data.upvotes}`;
+ downBtn.innerHTML = `<i class="fas fa-thumbs-down"></i> ${data.downvotes}`;
+
+ if (voteType === 'up') {
+ upBtn.classList.add('voted');
+ downBtn.classList.remove('voted');
+ } else {
+ downBtn.classList.add('voted');
+ upBtn.classList.remove('voted');
+ }
+ }
+ }
+ } catch (error) {
+ console.error('Error voting:', error);
+ }
+}
+
+// Research item
+async function researchItem(newsId) {
+ // TODO: Implement research modal
+ showAlert('Research feature coming soon!', 'info');
+}
+
+// Save/bookmark functionality
+// savedNewsIds is already declared at the top of the file
+
+function loadSavedItems() {
+ const saved = localStorage.getItem('saved_news_ids');
+ if (saved) {
+ try {
+ const ids = JSON.parse(saved);
+ savedNewsIds = new Set(ids);
+ } catch (e) {
+ savedNewsIds = new Set();
+ }
+ }
+}
+
+function saveSavedItems() {
+ localStorage.setItem('saved_news_ids', JSON.stringify(Array.from(savedNewsIds)));
+}
+
+function loadExpandedState() {
+ const saved = localStorage.getItem('expanded_news_ids');
+ if (saved) {
+ try {
+ const ids = JSON.parse(saved);
+ expandedNewsIds = new Set(ids);
+ } catch (e) {
+ expandedNewsIds = new Set();
+ }
+ }
+}
+
+function saveItem(newsId) {
+ const item = newsItems.find(n => n.id === newsId);
+ if (item) {
+ // Store full item data
+ const savedItems = JSON.parse(localStorage.getItem('saved_news_items') || '{}');
+ savedItems[newsId] = {
+ ...item,
+ savedAt: new Date().toISOString()
+ };
+ localStorage.setItem('saved_news_items', JSON.stringify(savedItems));
+
+ // Track saved ID
+ savedNewsIds.add(newsId);
+ saveSavedItems();
+
+ // Update UI
+ updateSaveButton(newsId, true);
+ showAlert('Item saved for later', 'success');
+ }
+}
+
+function unsaveItem(newsId) {
+ savedNewsIds.delete(newsId);
+ saveSavedItems();
+
+ // Remove from full data
+ const savedItems = JSON.parse(localStorage.getItem('saved_news_items') || '{}');
+ delete savedItems[newsId];
+ localStorage.setItem('saved_news_items', JSON.stringify(savedItems));
+
+ // Update UI
+ updateSaveButton(newsId, false);
+ showAlert('Item removed from saved', 'info');
+}
+
+function toggleSaveItem(newsId) {
+ if (savedNewsIds.has(newsId)) {
+ unsaveItem(newsId);
+ } else {
+ saveItem(newsId);
+ }
+}
+
+function updateSaveButton(newsId, isSaved) {
+ const btn = document.querySelector(`[data-news-id="${newsId}"] .save-btn`);
+ if (btn) {
+ const icon = btn.querySelector('i');
+ if (icon) {
+ icon.className = isSaved ? 'bi bi-bookmark-fill' : 'bi bi-bookmark';
+ }
+ }
+}
+
+// Load saved news feed
+function loadSavedNewsFeed() {
+ const savedItems = JSON.parse(localStorage.getItem('saved_news_items') || '{}');
+ const savedArray = Object.values(savedItems).sort((a, b) =>
+ new Date(b.savedAt) - new Date(a.savedAt)
+ );
+
+ // Set newsItems to saved items
+ newsItems = savedArray;
+
+ // Render items
+ renderNewsItems();
+ extractTrendingTopics();
+ updateBulkActionsBar();
+
+ // Show special header for saved items
+ const container = document.getElementById('news-feed-content');
+ if (savedArray.length === 0) {
+ container.innerHTML = `
+ <div class="empty-state">
+ <i class="bi bi-bookmark"></i>
+ <h3>No saved items</h3>
+ <p>Save news items to read them later</p>
+ </div>
+ `;
+ }
+}
+
+// Toggle expanded state for news items
+function toggleExpanded(newsId) {
+ if (expandedNewsIds.has(newsId)) {
+ expandedNewsIds.delete(newsId);
+ } else {
+ expandedNewsIds.add(newsId);
+ }
+
+ // Update the specific news item's appearance
+ const newsItem = document.querySelector(`[data-news-id="${newsId}"]`);
+ if (newsItem) {
+ newsItem.classList.toggle('is-expanded');
+
+ // Update button text and icon
+ const toggleBtn = newsItem.querySelector('.expand-toggle-btn');
+ if (toggleBtn) {
+ const isExpanded = expandedNewsIds.has(newsId);
+ toggleBtn.innerHTML = `
+ <i class="bi bi-chevron-${isExpanded ? 'up' : 'down'}"></i>
+ ${isExpanded ? 'Show less' : 'Show more'}
+ `;
+ toggleBtn.title = isExpanded ? 'Show less' : 'Show more';
+ }
+
+ // Update findings display
+ const findings = newsItem.querySelector('.news-findings');
+ if (findings) {
+ if (expandedNewsIds.has(newsId)) {
+ findings.style.maxHeight = 'none';
+ } else {
+ findings.style.maxHeight = '400px';
+ }
+ }
+ }
+
+ // Save state to localStorage
+ localStorage.setItem('expanded_news_ids', JSON.stringify(Array.from(expandedNewsIds)));
+}
+
+// Toggle table view
+function toggleTableView(showTable) {
+ const cardView = document.getElementById('news-feed-content');
+ let tableView = document.getElementById('news-table-view');
+
+ // Create table view if it doesn't exist
+ if (!tableView && showTable) {
+ tableView = createTableViewHTML();
+ cardView.parentNode.insertBefore(tableView, cardView.nextSibling);
+ }
+
+ if (showTable && tableView) {
+ cardView.style.display = 'none';
+ tableView.style.display = 'block';
+ populateNewsTable();
+ } else {
+ cardView.style.display = 'block';
+ if (tableView) tableView.style.display = 'none';
+ }
+}
+
+// Create table view HTML structure
+function createTableViewHTML() {
+ const tableContainer = document.createElement('div');
+ tableContainer.id = 'news-table-view';
+ tableContainer.className = 'news-table-container';
+ tableContainer.style.display = 'none';
+ tableContainer.innerHTML = `
+ <table class="news-table">
+ <thead>
+ <tr>
+ <th>SOURCES</th>
+ <th>DATE/TIME</th>
+ <th>HEADLINE</th>
+ <th>CATEGORY</th>
+ <th>WHAT HAPPENED</th>
+ <th>ANALYSIS</th>
+ <th>IMPACT</th>
+ </tr>
+ </thead>
+ <tbody id="news-table-body">
+ </tbody>
+ </table>
+ `;
+ return tableContainer;
+}
+
+// Filter by impact
+function filterNewsByImpact(threshold) {
+ activeImpactThreshold = parseInt(threshold);
+ updateFilterStatusBar();
+ renderNewsItems();
+}
+
+// Check priority status
+async function checkPriorityStatus() {
+ try {
+ // Check history for any active research
+ const response = await fetch('/api/history');
+ if (response.ok) {
+ const data = await response.json();
+ // Filter out news searches from active research display
+ const activeResearch = data.items?.filter(item =>
+ item.status === 'in_progress' &&
+ !item.metadata?.is_news_search
+ ) || [];
+
+ const statusDiv = document.getElementById('priority-status');
+ const message = document.getElementById('priority-message');
+
+ if (activeResearch.length > 0) {
+ statusDiv.style.display = 'block';
+ const research = activeResearch[0];
+ message.innerHTML = `
+ <strong>Research in progress:</strong> "${research.query.substring(0, 50)}..."
+ <a href="/progress/${research.id}" class="ms-2 text-white">View Progress →</a>
+ `;
+ } else {
+ statusDiv.style.display = 'none';
+ }
+ }
+ } catch (error) {
+ console.error('Error checking priority status:', error);
+ }
+
+ // Also check for completed news searches to display
+ // Commented out to prevent duplicate rendering - news items are already shown in the main feed
+ // checkForCompletedNewsSearches();
+}
+
+// Check for completed news searches
+async function checkForCompletedNewsSearches() {
+ try {
+ const response = await fetch('/api/history');
+ if (response.ok) {
+ const data = await response.json();
+ // Find recent completed news searches
+ const newsSearches = data.items?.filter(item =>
+ item.status === 'completed' &&
+ item.metadata?.is_news_search &&
+ // Only show searches from last 24 hours
+ new Date(item.completed_at) > new Date(Date.now() - 24 * 60 * 60 * 1000)
+ ) || [];
+
+ if (newsSearches.length > 0) {
+ // Display them as news cards
+ for (const search of newsSearches) {
+ // Check if already displayed
+ if (!document.querySelector(`[data-research-id="${search.id}"]`)) {
+ const reportResponse = await fetch(`/api/report/${search.id}`);
+ if (reportResponse.ok) {
+ const report = await reportResponse.json();
+ displayNewsResearchAsCard(search.id, search.query, report);
+ }
+ }
+ }
+ }
+ }
+ } catch (error) {
+ console.error('Error checking completed news searches:', error);
+ }
+}
+
+// Extract trending topics
+function extractTrendingTopics() {
+ // Collect all topics from news items
+ const topicCounts = {};
+
+ newsItems.forEach(item => {
+ // Use the actual topics array if available
+ if (item.topics && Array.isArray(item.topics)) {
+ item.topics.forEach(topic => {
+ if (topic && topic.trim()) {
+ topicCounts[topic] = (topicCounts[topic] || 0) + 1;
+ }
+ });
+ }
+ });
+
+ // Sort topics by frequency and get top 15 with counts
+ const topTopics = Object.entries(topicCounts)
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, 15); // Show more topics
+
+ const container = document.getElementById('trending-topics');
+
+ if (topTopics.length === 0) {
+ container.innerHTML = '<div class="text-muted small">No trending topics available</div>';
+ } else {
+ container.innerHTML = topTopics.map(([topic, count]) =>
+ `<span class="topic-tag" data-topic="${topic.replace(/"/g, '&quot;')}" title="Click to filter by ${topic} (${count} occurrences)">
+ ${topic} <span class="topic-count">${count}</span>
+ </span>`
+ ).join('');
+ // Event delegation is already handled in setupEventListeners
+ }
+}
+
+// Create topic subscription
+function createTopicSubscription(topic) {
+ document.getElementById('news-query').value = topic;
+ document.getElementById('news-search-form').dispatchEvent(new Event('submit'));
+}
+
+// Track active topic filter
+let activeTopicFilter = null;
+
+// Filter by topic
+function filterByTopic(topic) {
+ console.log('filterByTopic called with:', topic);
+
+ // Toggle filter if clicking the same topic
+ if (activeTopicFilter === topic) {
+ activeTopicFilter = null;
+ showAlert('Showing all news', 'info');
+ } else {
+ activeTopicFilter = topic;
+ showAlert(`Filtering by topic: ${topic}`, 'info');
+ }
+
+ // Update the UI to show active filter
+ updateActiveTopicUI();
+ updateFilterStatusBar();
+
+ // Re-render the news items with filter applied
+ renderNewsItems();
+}
+
+// Update UI to show active topic filter
+function updateActiveTopicUI() {
+ // Update all topic tags to show active state
+ document.querySelectorAll('.topic-tag').forEach(tag => {
+ const tagTopic = tag.getAttribute('data-topic');
+ if (tagTopic === activeTopicFilter) {
+ tag.classList.add('active');
+ } else {
+ tag.classList.remove('active');
+ }
+ });
+
+ // Show/hide clear filter button
+ const container = document.getElementById('news-feed-content');
+ const existingFilter = container.querySelector('.active-filter-bar');
+
+ if (activeTopicFilter) {
+ if (!existingFilter) {
+ const filterBar = document.createElement('div');
+ filterBar.className = 'active-filter-bar';
+ filterBar.innerHTML = `
+ <div class="filter-info">
+ <i class="bi bi-funnel-fill"></i>
+ Filtering by topic: <strong>${activeTopicFilter}</strong>
+ <button class="btn btn-sm btn-link" onclick="clearTopicFilter()">
+ <i class="bi bi-x-circle"></i> Clear filter
+ </button>
+ </div>
+ `;
+ container.insertBefore(filterBar, container.firstChild);
+ } else {
+ existingFilter.querySelector('strong').textContent = activeTopicFilter;
+ }
+ } else if (existingFilter) {
+ existingFilter.remove();
+ }
+}
+
+// Clear topic filter
+function clearTopicFilter() {
+ activeTopicFilter = null;
+ updateActiveTopicUI();
+ renderNewsItems();
+ showAlert('Filter cleared', 'info');
+}
+
+// Update bulk actions bar
+function updateBulkActionsBar() {
+ const feedContent = document.getElementById('news-feed-content');
+ if (!feedContent) return;
+
+ // Remove existing bulk actions bar
+ const existingBar = feedContent.querySelector('.bulk-actions-bar');
+ if (existingBar) existingBar.remove();
+
+ // Only show if there are items
+ if (newsItems.length === 0) return;
+
+ const unreadCount = newsItems.filter(item => !readNewsIds.has(item.id)).length;
+ const totalCount = newsItems.length;
+
+ const bulkBar = document.createElement('div');
+ bulkBar.className = 'bulk-actions-bar';
+ bulkBar.innerHTML = `
+ <div class="bulk-actions-content">
+ <div class="news-stats">
+ <span class="stat-item">
+ <i class="bi bi-envelope"></i> ${unreadCount} unread
+ </span>
+ <span class="stat-item">
+ <i class="bi bi-newspaper"></i> ${totalCount} total
+ </span>
+ </div>
+ <div class="bulk-actions">
+ <button class="btn btn-sm btn-outline-secondary" onclick="markAllAsRead()">
+ <i class="bi bi-check-all"></i> Mark all as read
+ </button>
+ <button class="btn btn-sm btn-outline-secondary" onclick="expandAll()">
+ <i class="bi bi-arrows-expand"></i> Expand all
+ </button>
+ <button class="btn btn-sm btn-outline-secondary" onclick="collapseAll()">
+ <i class="bi bi-arrows-collapse"></i> Collapse all
+ </button>
+ </div>
+ </div>
+ `;
+
+ // Insert at the beginning of feed content
+ feedContent.insertBefore(bulkBar, feedContent.firstChild);
+}
+
+// Update filter status bar
+function updateFilterStatusBar() {
+ const feedHeader = document.querySelector('.feed-header');
+ if (!feedHeader) return;
+
+ // Remove existing filter status bar
+ const existingBar = feedHeader.querySelector('.filter-status-bar');
+ if (existingBar) existingBar.remove();
+
+ // Check if any filters are active
+ const hasFilters = activeTopicFilter || activeTimeFilter !== 'all' || activeImpactThreshold > 0;
+
+ console.log('updateFilterStatusBar called:', {
+ activeTopicFilter,
+ activeTimeFilter,
+ activeImpactThreshold,
+ hasFilters
+ });
+
+ if (hasFilters) {
+ let filterBadges = [];
+
+ if (activeTopicFilter) {
+ filterBadges.push(`<span class="filter-badge">Topic: ${activeTopicFilter}</span>`);
+ }
+ if (activeTimeFilter !== 'all') {
+ filterBadges.push(`<span class="filter-badge">Time: ${activeTimeFilter}</span>`);
+ }
+ if (activeImpactThreshold > 0) {
+ filterBadges.push(`<span class="filter-badge">Impact ≥ ${activeImpactThreshold}</span>`);
+ }
+
+ // Only create and show the bar if we have actual filter badges
+ if (filterBadges.length > 0) {
+ const filterBar = document.createElement('div');
+ filterBar.className = 'filter-status-bar';
+
+ let filterHtml = '<div class="active-filters"><span>Active filters:</span>';
+ filterHtml += filterBadges.join('');
+ filterHtml += `<button class="btn btn-sm btn-link" onclick="clearAllFilters()">
+ <i class="bi bi-x-circle"></i> Clear all
+ </button></div>`;
+
+ filterBar.innerHTML = filterHtml;
+ feedHeader.appendChild(filterBar);
+ }
+ }
+}
+
+// Update feed header based on active subscription
+function updateFeedHeader() {
+ const feedTitle = document.querySelector('.feed-header h2');
+ if (!feedTitle) return;
+
+ if (activeSubscription === 'all') {
+ feedTitle.textContent = 'All News';
+ } else if (activeSubscription === 'saved') {
+ feedTitle.textContent = 'Saved Items';
+ } else {
+ // Find the subscription name
+ const sub = subscriptions.find(s => s.id === activeSubscription);
+ if (sub) {
+ const query = sub.query || sub.topic || sub.query_or_topic || 'Unknown';
+ feedTitle.innerHTML = `News for: <span class="text-muted">${query}</span>`;
+ }
+ }
+}
+
+// Clear all filters
+function clearAllFilters() {
+ // Clear all filter states
+ activeTopicFilter = null;
+ activeTimeFilter = 'all';
+ activeImpactThreshold = 0;
+
+ // Update UI
+ updateActiveTopicUI();
+
+ // Reset filter chips
+ document.querySelectorAll('#time-filters .filter-chip').forEach(chip => {
+ chip.classList.remove('active');
+ if (chip.dataset.time === 'all') chip.classList.add('active');
+ });
+
+ // Reset impact slider
+ const impactSlider = document.getElementById('impact-filter');
+ if (impactSlider) {
+ impactSlider.value = 0;
+ document.querySelector('.slider-value').textContent = '0';
+ }
+
+ // Re-render
+ renderNewsItems();
+ showAlert('All filters cleared', 'info');
+}
+
+// Render source links
+function renderSourceLinks(links) {
+ if (!links || links.length === 0) {
+ return '';
+ }
+
+ const linksHtml = links.map(link => {
+ // Extract domain name from URL to save space
+ let displayText = link.title;
+ try {
+ const url = new URL(link.url);
+ const domain = url.hostname.replace('www.', '');
+ // Use domain if title is too long
+ if (link.title.length > 30) {
+ displayText = domain;
+ }
+ } catch (e) {
+ // If URL parsing fails, truncate title
+ displayText = link.title.length > 30 ? link.title.substring(0, 27) + '...' : link.title;
+ }
+
+ return `<a href="${link.url}" target="_blank" rel="noopener noreferrer" class="source-link" title="${link.title}">
+ <i class="bi bi-link-45deg"></i>
+ ${displayText}
+ </a>`;
+ }).join('');
+
+ return `
+ <div class="news-sources">
+ <div class="sources-list">
+ ${linksHtml}
+ </div>
+ </div>
+ `;
+}
+
+// Show subscription history
+async function showSubscriptionHistory(subscriptionId) {
+ try {
+ const response = await fetch(`/news/api/subscriptions/${subscriptionId}/history`);
+ if (!response.ok) throw new Error('Failed to load history');
+
+ const data = await response.json();
+
+ // Create modal content
+ let historyHtml = '';
+ if (data.history && data.history.length > 0) {
+ historyHtml = data.history.map(item => `
+ <div class="history-item">
+ <div class="history-header">
+ <span class="history-status status-${item.status}">${item.status}</span>
+ <span class="history-time">${new Date(item.created_at).toLocaleString()}</span>
+ </div>
+ <div class="history-query">${item.query}</div>
+ <div class="history-actions">
+ <a href="${item.url}" class="btn btn-sm btn-primary">View Results</a>
+ ${item.duration_seconds ? `<span class="duration">${item.duration_seconds}s</span>` : ''}
+ </div>
+ </div>
+ `).join('');
+ } else {
+ historyHtml = '<p class="text-muted">No history available yet.</p>';
+ }
+
+ // Create modal
+ const modalHtml = `
+ <div class="modal fade" id="subscriptionHistoryModal" tabindex="-1">
+ <div class="modal-dialog modal-lg">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h5 class="modal-title">
+ Subscription History
+ <small class="text-muted">${data.subscription.query}</small>
+ </h5>
+ <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
+ </div>
+ <div class="modal-body">
+ <div class="subscription-stats mb-3">
+ <span class="stat-item">
+ <i class="bi bi-arrow-repeat"></i>
+ ${data.subscription.refresh_count} refreshes
+ </span>
+ <span class="stat-item">
+ <i class="bi bi-clock"></i>
+ Every ${data.subscription.refresh_interval}h
+ </span>
+ <span class="stat-item">
+ <i class="bi bi-calendar"></i>
+ Since ${new Date(data.subscription.created_at).toLocaleDateString()}
+ </span>
+ </div>
+ <div class="history-list">
+ ${historyHtml}
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ `;
+
+ // Remove existing modal if any
+ const existingModal = document.getElementById('subscriptionHistoryModal');
+ if (existingModal) existingModal.remove();
+
+ // Add modal to page
+ document.body.insertAdjacentHTML('beforeend', modalHtml);
+
+ // Show modal
+ const modal = new bootstrap.Modal(document.getElementById('subscriptionHistoryModal'));
+ modal.show();
+
+ // Clean up when modal is hidden
+ document.getElementById('subscriptionHistoryModal').addEventListener('hidden.bs.modal', function() {
+ this.remove();
+ });
+
+ } catch (error) {
+ console.error('Error loading subscription history:', error);
+ showAlert('Failed to load subscription history', 'error');
+ }
+}
+
+// Query template functions
+function loadNewsTableQuery() {
+ const template = document.getElementById('query-template');
+ template.style.display = 'block';
+ template.querySelector('.template-content').textContent = getNewsTableQuery();
+}
+
+function hideQueryTemplate() {
+ document.getElementById('query-template').style.display = 'none';
+}
+
+function useQueryTemplate() {
+ document.getElementById('news-query').value = getNewsTableQuery();
+ hideQueryTemplate();
+ document.getElementById('table-view-toggle').checked = true;
+ showAlert('Query template loaded. Click Search to execute!', 'info');
+}
+
+async function copyQueryTemplate() {
+ try {
+ await navigator.clipboard.writeText(getNewsTableQuery());
+ showAlert('Query copied to clipboard!', 'success');
+ } catch (err) {
+ console.error('Failed to copy:', err);
+ showAlert('Failed to copy query', 'error');
+ }
+}
+
+// Subscription modal
+function showCreateSubscriptionModal() {
+ // Create modal HTML
+ const modalHtml = `
+ <div class="modal fade" id="createSubscriptionModal" tabindex="-1">
+ <div class="modal-dialog">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h5 class="modal-title">Create New Subscription</h5>
+ <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
+ </div>
+ <div class="modal-body">
+ <div class="mb-3">
+ <label class="form-label">Subscription Type</label>
+ <div>
+ <div class="form-check form-check-inline">
+ <input class="form-check-input" type="radio" name="sub-type" id="sub-type-search" value="search" checked>
+ <label class="form-check-label" for="sub-type-search">Search Query</label>
+ </div>
+ <div class="form-check form-check-inline">
+ <input class="form-check-input" type="radio" name="sub-type" id="sub-type-topic" value="topic">
+ <label class="form-check-label" for="sub-type-topic">Topic</label>
+ </div>
+ </div>
+ </div>
+ <div class="mb-3">
+ <label for="sub-query" class="form-label">Query or Topic</label>
+ <input type="text" class="form-control" id="sub-query" placeholder="e.g., AI safety news, Ukraine conflict updates">
+ </div>
+ <div class="mb-3">
+ <label for="sub-refresh" class="form-label">Refresh Interval (hours)</label>
+ <select class="form-control" id="sub-refresh">
+ <option value="1">Every hour</option>
+ <option value="4" selected>Every 4 hours</option>
+ <option value="6">Every 6 hours</option>
+ <option value="12">Every 12 hours</option>
+ <option value="24">Daily</option>
+ </select>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
+ <button type="button" class="btn btn-primary" onclick="createSubscription()">Create Subscription</button>
+ </div>
+ </div>
+ </div>
+ </div>
+ `;
+
+ // Remove existing modal if any
+ const existingModal = document.getElementById('createSubscriptionModal');
+ if (existingModal) existingModal.remove();
+
+ // Add modal to page
+ document.body.insertAdjacentHTML('beforeend', modalHtml);
+
+ // Show modal
+ const modal = new bootstrap.Modal(document.getElementById('createSubscriptionModal'));
+ modal.show();
+
+ // Clean up when modal is hidden
+ document.getElementById('createSubscriptionModal').addEventListener('hidden.bs.modal', function() {
+ this.remove();
+ });
+}
+
+function hideSubscriptionModal() {
+ const modal = bootstrap.Modal.getInstance(document.getElementById('createSubscriptionModal'));
+ if (modal) modal.hide();
+}
+
+async function createSubscription() {
+ const type = document.querySelector('input[name="sub-type"]:checked').value;
+ const query = document.getElementById('sub-query').value;
+ const refreshHours = document.getElementById('sub-refresh').value;
+
+ if (!query) {
+ showAlert('Please enter a query or topic', 'warning');
+ return;
+ }
+
+ try {
+ const response = await fetch('/news/api/subscribe', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': getCSRFToken()
+ },
+ body: JSON.stringify({
+ user_id: currentUser,
+ query: query,
+ subscription_type: type,
+ refresh_hours: parseInt(refreshHours)
+ })
+ });
+
+ if (response.ok) {
+ hideSubscriptionModal();
+ await loadSubscriptions();
+ showAlert('Subscription created successfully!', 'success');
+ } else {
+ showAlert('Failed to create subscription', 'error');
+ }
+ } catch (error) {
+ console.error('Error creating subscription:', error);
+ showAlert('Error creating subscription', 'error');
+ }
+}
+
+// Utility functions
+function showAlert(message, type = 'info') {
+ const alertContainer = document.getElementById('news-alert');
+ alertContainer.className = `settings-alert-container alert-${type}`;
+ alertContainer.textContent = message;
+ alertContainer.style.display = 'block';
+
+ setTimeout(() => {
+ alertContainer.style.display = 'none';
+ }, 5000);
+}
+
+function getCSRFToken() {
+ return document.querySelector('meta[name="csrf-token"]').getAttribute('content');
+}
+
+// Refresh feed
+function refreshFeed() {
+ lastRefreshTime = new Date();
+ updateRefreshIndicator();
+ loadNewsFeed();
+ showAlert('Feed refreshed', 'info');
+}
+
+// Auto-refresh functions
+function startAutoRefresh() {
+ // Clear any existing interval
+ stopAutoRefresh();
+
+ // Set refresh interval to 5 minutes
+ const refreshInterval = 5 * 60 * 1000; // 5 minutes
+
+ autoRefreshInterval = setInterval(() => {
+ refreshFeed();
+ }, refreshInterval);
+
+ // Update indicator every second
+ setInterval(updateRefreshIndicator, 1000);
+
+ showAlert('Auto-refresh enabled (every 5 minutes)', 'success');
+}
+
+function stopAutoRefresh() {
+ if (autoRefreshInterval) {
+ clearInterval(autoRefreshInterval);
+ autoRefreshInterval = null;
+ }
+ showAlert('Auto-refresh disabled', 'info');
+}
+
+function updateRefreshIndicator() {
+ const timeSinceRefresh = Math.floor((new Date() - lastRefreshTime) / 1000);
+ const minutes = Math.floor(timeSinceRefresh / 60);
+ const seconds = timeSinceRefresh % 60;
+
+ // Update refresh button text if it exists
+ const refreshBtn = document.querySelector('button[onclick="refreshFeed()"] i');
+ if (refreshBtn) {
+ const timeText = minutes > 0 ? `${minutes}m ago` : `${seconds}s ago`;
+ refreshBtn.setAttribute('title', `Last refresh: ${timeText}`);
+
+ // Add visual indicator when it's been more than 5 minutes
+ if (minutes >= 5) {
+ refreshBtn.classList.add('text-warning');
+ } else {
+ refreshBtn.classList.remove('text-warning');
+ }
+ }
+
+ // Add countdown to next refresh if auto-refresh is active
+ if (autoRefreshInterval) {
+ const nextRefreshIn = 300 - timeSinceRefresh; // 5 minutes = 300 seconds
+ if (nextRefreshIn > 0) {
+ const nextMinutes = Math.floor(nextRefreshIn / 60);
+ const nextSeconds = nextRefreshIn % 60;
+ const countdownText = `Next refresh in ${nextMinutes}:${nextSeconds.toString().padStart(2, '0')}`;
+
+ // Update auto-refresh label
+ const autoRefreshLabel = document.querySelector('label[for="auto-refresh"]');
+ if (autoRefreshLabel) {
+ autoRefreshLabel.textContent = `Auto-refresh feed (${countdownText})`;
+ }
+ }
+ }
+}
+
+// Check for active news research on page load
+async function checkActiveNewsResearch() {
+ try {
+ // Check localStorage for active news research
+ const activeResearch = localStorage.getItem('active_news_research');
+ if (!activeResearch) return;
+
+ const { researchId, query, startTime } = JSON.parse(activeResearch);
+
+ // Check if research is still recent (within 10 minutes)
+ const elapsed = Date.now() - new Date(startTime).getTime();
+ if (elapsed > 10 * 60 * 1000) {
+ localStorage.removeItem('active_news_research');
+ return;
+ }
+
+ // Check research status
+ const statusResponse = await fetch(`/api/research/${researchId}/status`);
+ if (!statusResponse.ok) {
+ localStorage.removeItem('active_news_research');
+ return;
+ }
+
+ const status = await statusResponse.json();
+
+ if (status.status === 'in_progress') {
+ // Show progress indicator at the top of the feed
+ const container = document.getElementById('news-feed-content');
+ const progressCard = document.createElement('div');
+ progressCard.className = 'news-card priority-high active-research-card';
+ progressCard.innerHTML = `
+ <div class="news-header">
+ <h2 class="news-title">
+ <i class="bi bi-hourglass-split spinning"></i>
+ Continuing analysis: "${query.substring(0, 60)}..."
+ </h2>
+ </div>
+ <div class="news-meta">
+ <span><i class="bi bi-info-circle"></i> Research ID: ${researchId}</span>
+ <span><i class="bi bi-clock"></i> In progress</span>
+ </div>
+ <div class="news-summary">
+ <div class="progress">
+ <div class="progress-bar progress-bar-striped progress-bar-animated"
+ role="progressbar" style="width: ${status.progress || 10}%"></div>
+ </div>
+ <p class="mt-2">Your news analysis is still running. Results will appear when ready.</p>
+ <a href="/progress/${researchId}" class="btn btn-sm btn-outline-primary mt-2">
+ <i class="bi bi-arrow-right"></i> View detailed progress
+ </a>
+ </div>
+ `;
+
+ // Insert at the top of the feed
+ container.insertBefore(progressCard, container.firstChild);
+
+ // Resume polling
+ pollForNewsResearchResults(researchId, query, true);
+ } else if (status.status === 'completed') {
+ // Research completed while user was away
+ localStorage.removeItem('active_news_research');
+ showAlert('Your news analysis has completed! Loading results...', 'success');
+
+ // Reload the feed to show the results
+ await loadNewsFeed();
+ } else {
+ // Research failed or was cancelled
+ localStorage.removeItem('active_news_research');
+ }
+ } catch (error) {
+ console.error('Error checking active research:', error);
+ localStorage.removeItem('active_news_research');
+ }
+}
+
+// Poll for news research results
+async function pollForNewsResearchResults(researchId, originalQuery, isResume = false) {
+ let pollCount = 0;
+ const maxPolls = 60; // 5 minutes max
+
+ // Store active research in localStorage
+ if (!isResume) {
+ localStorage.setItem('active_news_research', JSON.stringify({
+ researchId,
+ query: originalQuery,
+ startTime: new Date().toISOString()
+ }));
+ }
+
+ const pollInterval = setInterval(async () => {
+ try {
+ // Check research status
+ const statusResponse = await fetch(`/api/research/${researchId}/status`);
+ if (!statusResponse.ok) {
+ clearInterval(pollInterval);
+ showAlert('Failed to check research status', 'error');
+ return;
+ }
+
+ const status = await statusResponse.json();
+
+ // Update progress bar
+ const progressBar = document.querySelector('.progress-bar');
+ if (progressBar) {
+ progressBar.style.width = `${status.progress || 10}%`;
+ }
+
+ if (status.status === 'completed') {
+ clearInterval(pollInterval);
+ localStorage.removeItem('active_news_research');
+
+ // Get the full report
+ const reportResponse = await fetch(`/api/report/${researchId}`);
+ if (reportResponse.ok) {
+ const report = await reportResponse.json();
+ displayNewsResearchAsCard(researchId, originalQuery, report);
+ } else {
+ showAlert('Failed to get research results', 'error');
+ }
+ } else if (status.status === 'error' || status.status === 'suspended') {
+ clearInterval(pollInterval);
+ localStorage.removeItem('active_news_research');
+ showAlert(`Research ${status.status}: ${status.metadata?.error || 'Unknown error'}`, 'error');
+ loadNewsFeed(); // Reload normal feed
+ }
+
+ pollCount++;
+ if (pollCount >= maxPolls) {
+ clearInterval(pollInterval);
+ localStorage.removeItem('active_news_research');
+ showAlert('Research taking too long. Check the progress page.', 'warning');
+ }
+ } catch (error) {
+ console.error('Error polling for results:', error);
+ clearInterval(pollInterval);
+ localStorage.removeItem('active_news_research');
+ showAlert('Error checking research status', 'error');
+ }
+ }, 5000); // Poll every 5 seconds
+}
+
+// Display news research as a card
+function displayNewsResearchAsCard(researchId, query, report) {
+ const container = document.getElementById('news-feed-content');
+
+ // Extract key findings from the report
+ const content = report.content || '';
+ const lines = content.split('\n');
+
+ // Find the summary or key findings section
+ let summary = '';
+ let inSummary = false;
+ for (const line of lines) {
+ if (line.includes('Summary') || line.includes('Key Findings') || line.includes('THE BIG PICTURE')) {
+ inSummary = true;
+ continue;
+ }
+ if (inSummary && line.trim() && !line.startsWith('#')) {
+ summary += line + ' ';
+ if (summary.length > 300) break; // Limit summary length
+ }
+ }
+
+ // If no summary found, take first few lines
+ if (!summary) {
+ summary = lines.filter(l => l.trim() && !l.startsWith('#')).slice(0, 3).join(' ');
+ }
+
+ // Create news card
+ const newsCard = `
+ <div class="news-card priority-high" data-research-id="${researchId}">
+ <div class="impact-score impact-high">
+ <i class="bi bi-stars"></i> News Analysis
+ </div>
+ <div class="news-header">
+ <h2 class="news-title">${query}</h2>
+ </div>
+ <div class="news-meta">
+ <span><i class="bi bi-check-circle"></i> Analysis Complete</span>
+ <span><i class="bi bi-clock"></i> Just now</span>
+ <span><i class="bi bi-file-text"></i> Full Report Available</span>
+ </div>
+ <div class="news-summary">
+ <p>${summary.substring(0, 300)}...</p>
+ </div>
+ <div class="news-actions">
+ <div class="vote-buttons">
+ <button class="vote-btn" onclick="vote('news-${researchId}', 'up')">
+ <i class="bi bi-hand-thumbs-up"></i> 0
+ </button>
+ <button class="vote-btn" onclick="vote('news-${researchId}', 'down')">
+ <i class="bi bi-hand-thumbs-down"></i> 0
+ </button>
+ </div>
+ <div>
+ <a href="/results/${researchId}" class="btn btn-sm btn-primary">
+ <i class="bi bi-arrow-right"></i> View Full Analysis
+ </a>
+ <button class="btn btn-sm btn-outline-secondary" onclick="saveNewsAnalysis('${researchId}')">
+ <i class="bi bi-bookmark"></i>
+ </button>
+ </div>
+ </div>
+ </div>
+ `;
+
+ // Append to existing content instead of replacing
+ const existingCard = document.querySelector(`[data-research-id="${researchId}"]`);
+ if (existingCard) {
+ existingCard.outerHTML = newsCard;
+ } else {
+ // Create a temporary div to hold the new card
+ const tempDiv = document.createElement('div');
+ tempDiv.innerHTML = newsCard;
+ container.insertBefore(tempDiv.firstElementChild, container.firstChild);
+ }
+
+ // Show success message
+ showAlert('News analysis complete! Click "View Full Analysis" for detailed report.', 'success');
+}
+
+// Save news analysis
+function saveNewsAnalysis(researchId) {
+ const saved = JSON.parse(localStorage.getItem('saved_news_analyses') || '[]');
+ saved.push({ id: researchId, timestamp: new Date().toISOString() });
+ localStorage.setItem('saved_news_analyses', JSON.stringify(saved));
+ showAlert('Analysis saved for later', 'success');
+}
+
+// Search history functions
+function loadSearchHistory() {
+ const stored = localStorage.getItem('news_search_history');
+ if (stored) {
+ try {
+ searchHistory = JSON.parse(stored);
+ // Keep only last 20 searches
+ searchHistory = searchHistory.slice(0, 20);
+ displayRecentSearches();
+ } catch (e) {
+ searchHistory = [];
+ }
+ }
+}
+
+function saveSearchHistory() {
+ localStorage.setItem('news_search_history', JSON.stringify(searchHistory));
+}
+
+function addToSearchHistory(query, type = 'quick') {
+ // Remove duplicates
+ searchHistory = searchHistory.filter(item => item.query !== query);
+
+ // Add to beginning
+ searchHistory.unshift({
+ query: query,
+ type: type,
+ timestamp: new Date().toISOString(),
+ resultCount: newsItems.length
+ });
+
+ // Keep only last 20
+ searchHistory = searchHistory.slice(0, 20);
+
+ // Update display
+ displayRecentSearches();
+ saveSearchHistory();
+}
+
+function displayRecentSearches() {
+ const container = document.getElementById('recent-searches');
+ if (!container) return;
+
+ if (searchHistory.length === 0) {
+ container.innerHTML = '<div class="text-muted small">Your recent news searches will appear here</div>';
+ return;
+ }
+
+ const html = searchHistory.slice(0, 10).map(item => {
+ const date = new Date(item.timestamp);
+ const timeAgo = getTimeAgo(date);
+ const typeIcon = item.type === 'deep' ? 'bi-search-heart' :
+ item.type === 'table' ? 'bi-table' : 'bi-search';
+
+ return `
+ <div class="recent-search-item" onclick="rerunSearch('${item.query.replace(/'/g, "\\'")}', '${item.type}')">
+ <i class="bi ${typeIcon}"></i>
+ <div class="flex-grow-1">
+ <div class="search-query">${item.query}</div>
+ <div class="search-meta">${timeAgo} • ${item.resultCount || 0} results</div>
+ </div>
+ <i class="bi bi-arrow-repeat"></i>
+ </div>
+ `;
+ }).join('');
+
+ container.innerHTML = html;
+}
+
+function rerunSearch(query, type = 'quick') {
+ // Fill the search input
+ document.getElementById('news-search').value = query;
+
+ // Trigger search
+ handleSearchSubmit();
+}
+
+function getTimeAgo(date) {
+ const seconds = Math.floor((new Date() - date) / 1000);
+
+ if (seconds < 60) return 'just now';
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
+ if (seconds < 604800) return `${Math.floor(seconds / 86400)}d ago`;
+ return date.toLocaleDateString();
+}
+
+// Check if item is within time filter
+function isWithinTimeFilter(item, timeFilter) {
+ // Try multiple date fields
+ const itemDate = item.created_at || item.date || item.timestamp || item.published_at;
+ if (!itemDate) return true; // If no date, include it
+
+ const date = new Date(itemDate);
+ const now = new Date();
+ const hoursDiff = (now - date) / (1000 * 60 * 60);
+ const daysDiff = hoursDiff / 24;
+
+ switch (timeFilter) {
+ case 'hour':
+ return hoursDiff <= 1;
+ case 'today':
+ return daysDiff < 1;
+ case 'week':
+ return daysDiff <= 7;
+ case 'month':
+ return daysDiff <= 30;
+ default:
+ return true;
+ }
+}
+
+// Read status functions
+function loadReadStatus() {
+ const stored = localStorage.getItem('news_read_ids');
+ if (stored) {
+ try {
+ const ids = JSON.parse(stored);
+ readNewsIds = new Set(ids);
+ } catch (e) {
+ readNewsIds = new Set();
+ }
+ }
+}
+
+function saveReadStatus() {
+ localStorage.setItem('news_read_ids', JSON.stringify(Array.from(readNewsIds)));
+}
+
+function markAsRead(newsId) {
+ readNewsIds.add(newsId);
+ // Update UI immediately
+ const element = document.querySelector(`[data-news-id="${newsId}"]`);
+ if (element) {
+ element.classList.add('is-read');
+ element.classList.remove('is-unread');
+ }
+}
+
+function markAsUnread(newsId) {
+ readNewsIds.delete(newsId);
+ // Update UI immediately
+ const element = document.querySelector(`[data-news-id="${newsId}"]`);
+ if (element) {
+ element.classList.remove('is-read');
+ element.classList.add('is-unread');
+ }
+}
+
+function toggleReadStatus(newsId) {
+ if (readNewsIds.has(newsId)) {
+ markAsUnread(newsId);
+ } else {
+ markAsRead(newsId);
+ }
+ saveReadStatus();
+}
+
+function markAllAsRead() {
+ newsItems.forEach(item => {
+ readNewsIds.add(item.id);
+ });
+ saveReadStatus();
+ renderNewsItems();
+ showAlert('All items marked as read', 'success');
+}
+
+// Expand all items
+function expandAll() {
+ document.querySelectorAll('.news-item').forEach(item => {
+ const newsId = item.dataset.newsId;
+ if (!expandedNewsIds.has(newsId)) {
+ expandedNewsIds.add(newsId);
+ item.classList.add('is-expanded');
+ const icon = item.querySelector('.expand-icon');
+ if (icon) icon.style.transform = 'rotate(180deg)';
+ }
+ });
+ showAlert('All items expanded', 'info');
+}
+
+// Collapse all items
+function collapseAll() {
+ expandedNewsIds.clear();
+ document.querySelectorAll('.news-item').forEach(item => {
+ item.classList.remove('is-expanded');
+ const icon = item.querySelector('.expand-icon');
+ if (icon) icon.style.transform = 'rotate(0)';
+ });
+ showAlert('All items collapsed', 'info');
+}
+
+// Expandable content functions
+function toggleExpanded(newsId) {
+ const element = document.querySelector(`[data-news-id="${newsId}"]`);
+ if (!element) return;
+
+ if (expandedNewsIds.has(newsId)) {
+ expandedNewsIds.delete(newsId);
+ element.classList.remove('is-expanded');
+ } else {
+ expandedNewsIds.add(newsId);
+ element.classList.add('is-expanded');
+ // Mark as read when expanded
+ if (!readNewsIds.has(newsId)) {
+ markAsRead(newsId);
+ saveReadStatus();
+ }
+ }
+
+ // Rotate the chevron icon
+ const icon = element.querySelector('.expand-icon');
+ if (icon) {
+ icon.style.transform = expandedNewsIds.has(newsId) ? 'rotate(180deg)' : 'rotate(0)';
+ }
+}
+
+// Share and export functions
+function shareNews(newsId) {
+ const item = newsItems.find(n => n.id === newsId);
+ if (!item) return;
+
+ const shareUrl = window.location.origin + (item.source_url || `/results/${item.research_id}`);
+ const shareText = `${item.headline}\n\n${shareUrl}`;
+
+ if (navigator.share) {
+ // Use Web Share API if available
+ navigator.share({
+ title: item.headline,
+ text: item.summary || item.findings?.substring(0, 200) + '...',
+ url: shareUrl
+ }).then(() => {
+ showAlert('Shared successfully', 'success');
+ }).catch(err => {
+ if (err.name !== 'AbortError') {
+ copyToClipboard(shareText);
+ }
+ });
+ } else {
+ // Fallback to copy
+ copyToClipboard(shareText);
+ }
+}
+
+function copyNewsLink(newsId) {
+ const item = newsItems.find(n => n.id === newsId);
+ if (!item) return;
+
+ const url = window.location.origin + (item.source_url || `/results/${item.research_id}`);
+ copyToClipboard(url);
+}
+
+function exportToMarkdown(newsId) {
+ const item = newsItems.find(n => n.id === newsId);
+ if (!item) return;
+
+ let markdown = `# ${item.headline}\n\n`;
+ markdown += `**Category:** ${item.category || 'General'}\n`;
+ markdown += `**Impact Score:** ${item.impact_score}/10\n`;
+ markdown += `**Date:** ${new Date(item.created_at || Date.now()).toLocaleDateString()}\n\n`;
+
+ if (item.findings) {
+ markdown += `## Key Findings\n\n${item.findings}\n\n`;
+ } else if (item.summary) {
+ markdown += `## Summary\n\n${item.summary}\n\n`;
+ }
+
+ if (item.topics && item.topics.length > 0) {
+ markdown += `## Topics\n\n${item.topics.map(t => `- ${t}`).join('\n')}\n\n`;
+ }
+
+ if (item.links && item.links.length > 0) {
+ markdown += `## Sources\n\n${item.links.map(l => `- [${l.title}](${l.url})`).join('\n')}\n\n`;
+ }
+
+ const url = window.location.origin + (item.source_url || `/results/${item.research_id}`);
+ markdown += `\n[View Full Report](${url})`;
+
+ // Create and download file
+ const blob = new Blob([markdown], { type: 'text/markdown' });
+ const a = document.createElement('a');
+ a.href = URL.createObjectURL(blob);
+ a.download = `${item.headline.replace(/[^a-z0-9]/gi, '_').toLowerCase()}.md`;
+ a.click();
+
+ showAlert('Exported to Markdown', 'success');
+}
+
+function hideNewsItem(newsId) {
+ const element = document.querySelector(`[data-news-id="${newsId}"]`);
+ if (element) {
+ element.style.transition = 'opacity 0.3s, transform 0.3s';
+ element.style.opacity = '0';
+ element.style.transform = 'translateX(-20px)';
+ setTimeout(() => {
+ element.remove();
+ // Remove from newsItems array
+ newsItems = newsItems.filter(item => item.id !== newsId);
+ updateBulkActionsBar();
+ }, 300);
+ }
+ showAlert('Item hidden', 'info');
+}
+
+function reportIssue(newsId) {
+ const item = newsItems.find(n => n.id === newsId);
+ if (!item) return;
+
+ // You could open a modal here or redirect to a feedback form
+ const subject = encodeURIComponent(`Issue with news item: ${item.headline}`);
+ const body = encodeURIComponent(`News ID: ${newsId}\nHeadline: ${item.headline}\n\nDescribe the issue:\n`);
+ window.open(`mailto:[email protected]?subject=${subject}&body=${body}`);
+}
+
+function copyToClipboard(text) {
+ if (navigator.clipboard) {
+ navigator.clipboard.writeText(text).then(() => {
+ showAlert('Copied to clipboard', 'success');
+ }).catch(err => {
+ // Fallback
+ const textarea = document.createElement('textarea');
+ textarea.value = text;
+ textarea.style.position = 'fixed';
+ textarea.style.opacity = '0';
+ document.body.appendChild(textarea);
+ textarea.select();
+ document.execCommand('copy');
+ document.body.removeChild(textarea);
+ showAlert('Copied to clipboard', 'success');
+ });
+ }
+}
+
+// Visit tracking functions
+function loadVisitTracking() {
+ // Load last visit time
+ const storedLastVisit = localStorage.getItem('news_last_visit');
+ if (storedLastVisit) {
+ lastVisitTime = new Date(storedLastVisit);
+ } else {
+ lastVisitTime = new Date();
+ }
+
+ // Load seen news IDs
+ const storedSeenIds = localStorage.getItem('news_seen_ids');
+ if (storedSeenIds) {
+ try {
+ const ids = JSON.parse(storedSeenIds);
+ seenNewsIds = new Set(ids);
+ } catch (e) {
+ seenNewsIds = new Set();
+ }
+ }
+
+ // Clean up old seen IDs (keep only last 100)
+ if (seenNewsIds.size > 100) {
+ const idsArray = Array.from(seenNewsIds);
+ seenNewsIds = new Set(idsArray.slice(-100));
+ }
+}
+
+function saveVisitTracking() {
+ // Save current time as last visit
+ localStorage.setItem('news_last_visit', new Date().toISOString());
+
+ // Save seen news IDs
+ localStorage.setItem('news_seen_ids', JSON.stringify(Array.from(seenNewsIds)));
+}
+
+function markNewsAsSeen(newsId) {
+ seenNewsIds.add(newsId);
+ // Remove the new indicator after a delay
+ setTimeout(() => {
+ const element = document.querySelector(`[data-news-id="${newsId}"]`);
+ if (element) {
+ element.classList.remove('is-new', 'fade-in-new');
+ }
+ }, 5000); // Remove after 5 seconds
+}
+
+function isNewsNew(item) {
+ // Check if we've seen this item before
+ if (seenNewsIds.has(item.id)) {
+ return false;
+ }
+
+ // Check if the item was created after last visit
+ if (item.created_at && lastVisitTime) {
+ const itemDate = new Date(item.created_at);
+ return itemDate > lastVisitTime;
+ }
+
+ // If no timestamp, consider it new if we haven't seen it
+ return true;
+}
+
+// News Templates
+const newsTemplates = {
+ 'breaking-news': {
+ name: 'Breaking News Table',
+ query: `Find UP TO 10 IMPORTANT breaking news stories from TODAY YYYY-MM-DD ONLY.
+
+START YOUR RESPONSE DIRECTLY WITH THE TABLE. NO INTRODUCTION OR PREAMBLE.
+
+CRITICAL: All information MUST be from real, verifiable sources. DO NOT invent or fabricate any news, events, or details. Only report what you find from actual news sources.
+
+OUTPUT FORMAT: Begin immediately with a markdown table using this exact structure:
+
+| SOURCES | DATE | HEADLINE | CATEGORY | WHAT HAPPENED | ANALYSIS | IMPACT |
+|---------|------|----------|----------|---------------|----------|--------|
+| [Citation numbers] | [YYYY-MM-DD] | [Descriptive headline] | [War/Security/Economy/Disaster/Politics/Tech] | [3 sentences max from actual sources] | [Why it matters + What happens next + Historical context] | [1-10 score] | [Status] |
+
+IMPORTANT: In the SOURCES column, list the citation numbers (e.g., [1, 3, 5]) that support this news item. These should match the numbered references at the end of your report.
+
+Example row:
+| [2, 4, 7] | 2025-01-12 | Major Earthquake Strikes Southern California | Disaster | A 7.1 magnitude earthquake hit near Los Angeles causing structural damage. Emergency services report multiple injuries. Aftershocks continue to affect the region. | Major infrastructure test for earthquake preparedness systems. FEMA mobilizing resources. Similar to 1994 Northridge event but with modern building codes. | 9 | Ongoing |
+
+SEARCH STRATEGY:
+1. breaking news today major incident developing impact
+2. crisis death disaster announcement today hours ago
+3. site:reuters.com OR site:bbc.com OR site:cnn.com today
+4. geopolitical economic security emergency today
+
+PRIORITIZE BY REAL-WORLD IMPACT:
+- Active conflicts with casualties (Impact 8-10)
+- Natural disasters affecting thousands (Impact 7-9)
+- Economic shocks (>3% market moves) (Impact 6-8)
+- Major political shifts (Impact 5-7)
+- Critical infrastructure failures (Impact 6-9)
+
+DIVERSITY IS MANDATORY: You MUST find 10 COMPLETELY DIFFERENT events. Examples of what NOT to do:
+- ✗ BAD: Multiple stories about the same earthquake (initial report, death toll update, rescue efforts)
+- ✗ BAD: Multiple stories about the same political event (announcement, reactions, analysis)
+- ✓ GOOD: One earthquake in Japan, one political crisis in Europe, one economic news from US, etc.
+
+If you can only find 7 truly distinct events, show 7. Do NOT pad with duplicate coverage.
+
+REQUIREMENTS:
+- Only include stories found from real sources
+- Sort by IMPACT score (highest first)
+- Each row must be complete with all columns filled
+- Keep analysis concise but informative
+- Verify sources are from today
+- If insufficient real news is found, include fewer rows rather than inventing content
+
+After the table, add:
+- **THE BIG PICTURE**: One paragraph connecting today's major events (based on actual findings)
+- **WATCH FOR**: 3 bullet points on what to monitor in next 24 hours`
+ },
+ 'market-analysis': {
+ name: 'Market Analysis',
+ query: `Analyze today's financial markets and economic news from YYYY-MM-DD.
+
+Find UP TO 10 SIGNIFICANT market movements, economic events, or financial news items from today.
+
+CRITICAL: All information MUST be from real, verifiable sources. DO NOT invent or fabricate any market data or movements. Only report actual market information from reliable financial sources.
+
+Create a comprehensive table with these columns:
+| SOURCES | DATE | Market/Asset | Movement | Key Drivers | Analysis | Outlook |
+|---------|------|--------------|----------|-------------|----------|----------|
+| [Citation numbers] | [YYYY-MM-DD] | [Asset name] | [% change] | [Main reason] | [Impact analysis] | [Next 24h outlook] |
+
+IMPORTANT: In the SOURCES column, list the citation numbers (e.g., [1, 3, 5]) that support this data. These should match the numbered references at the end of your report.
+
+Focus on finding 10 DISTINCT market events:
+- Major stock indices (S&P 500, NASDAQ, DOW)
+- Cryptocurrency movements
+- Commodity prices (Oil, Gold, etc.)
+- Currency pairs
+- Notable company earnings or news
+- IPOs, mergers, or acquisitions
+- Central bank decisions
+- Economic indicators (GDP, inflation, employment)
+
+Each row should be a SEPARATE market event or movement, not multiple updates about the same thing.
+
+Include market sentiment analysis and tomorrow's key events to watch.
+
+REQUIREMENTS:
+- Only use real market data from verified sources
+- Do not invent prices, movements, or market events
+- If data is unavailable, state so rather than fabricating`
+ },
+ 'tech-updates': {
+ name: 'Technology Updates',
+ query: `Find UP TO 10 IMPORTANT technology news stories and updates from today YYYY-MM-DD.
+
+CRITICAL: All information MUST be from real, verifiable sources. DO NOT invent or fabricate any tech news, announcements, or details. Only report what you find from actual technology news sources.
+
+Format as a table:
+| SOURCES | DATE | Company/Topic | Announcement | Impact | Technical Details | Market Reaction |
+|---------|------|---------------|--------------|--------|-------------------|------------------|
+| [Citation numbers] | [YYYY-MM-DD] | [Company/Tech] | [What was announced] | [Industry impact] | [Technical specifics] | [Stock/Market response] |
+
+IMPORTANT: In the SOURCES column, list the citation numbers (e.g., [1, 3, 5]) that support this news. These should match the numbered references at the end of your report.
+
+Cover 10 DISTINCT technology stories from:
+- AI/ML developments
+- Major tech company news
+- Cybersecurity updates
+- Product launches
+- Research breakthroughs
+- Industry trends
+- Startup funding rounds
+- Tech policy and regulation
+- Open source projects
+- Hardware innovations
+
+Each row should be a SEPARATE tech news item, not multiple angles of the same story.
+
+Focus on developments with significant industry impact.
+
+REQUIREMENTS:
+- Only include real announcements from verified sources
+- Do not fabricate company news or technical details
+- If insufficient news is found, include fewer rows rather than inventing content`
+ },
+ 'local-news': {
+ name: 'Local News',
+ query: `LOCATION: [ENTER YOUR CITY/REGION HERE]
+
+Find UP TO 10 LOCAL NEWS ITEMS for the specified location from today YYYY-MM-DD.
+
+START YOUR RESPONSE DIRECTLY WITH THE TABLE. NO INTRODUCTION.
+
+CRITICAL: All information MUST be from real, verifiable local sources. DO NOT invent or fabricate any local news, events, or details. Only report what you find from actual local news sources.
+
+OUTPUT FORMAT:
+| SOURCE | DATE | HEADLINE | CATEGORY | DETAILS | IMPACT ON COMMUNITY |
+|--------|------|----------|----------|---------|---------------------|
+| [Citation numbers] | [YYYY-MM-DD] | [Brief headline] | [Local Gov/Crime/Business/Community/Weather] | [What happened] | [How it affects residents] |
+
+IMPORTANT: In the SOURCE column, list the citation numbers (e.g., [1, 3, 5]) that support this news. These should match the numbered references at the end of your report.
+
+Include UP TO 10 DISTINCT local stories from:
+- Local government decisions
+- Community events
+- Crime and safety updates
+- Business openings/closures
+- Infrastructure changes
+- Weather impacts
+- School and education news
+- Local sports and recreation
+- Health and public services
+- Transportation updates
+
+Each row should be a SEPARATE local event, not multiple updates about the same story.
+
+IMPORTANT: Focus ONLY on news from the location specified at the top.
+
+REQUIREMENTS:
+- Only use real local news from verified sources
+- Do not invent local events or incidents
+- If insufficient local news is found, include fewer rows rather than fabricating content`
+ },
+ 'topic-news': {
+ name: 'Topic News',
+ query: `TOPIC: [ENTER YOUR TOPIC HERE - e.g., anime, space exploration, renewable energy, etc.]
+
+Find UP TO 10 DISTINCT, SEPARATE news stories about the specified topic from today YYYY-MM-DD.
+
+CRITICAL INSTRUCTION: Each row MUST be about a COMPLETELY DIFFERENT news item. Do NOT include multiple articles, updates, or perspectives about the same story. For example, if searching for anime news:
+- ✗ BAD: Three rows about the same My Hero Academia announcement (initial news, fan reactions, industry analysis)
+- ✓ GOOD: One row each for: My Hero Academia news, Attack on Titan update, new Crunchyroll series, Studio Ghibli announcement, etc.
+
+START YOUR RESPONSE DIRECTLY WITH THE TABLE. NO INTRODUCTION OR PREAMBLE.
+
+CRITICAL: All information MUST be from real, verifiable sources. DO NOT invent or fabricate any news, events, or details. Only report what you find from actual sources.
+
+OUTPUT FORMAT: Begin immediately with a markdown table using this exact structure:
+
+| SOURCES | DATE | HEADLINE | SUBTOPIC | KEY DEVELOPMENTS | SIGNIFICANCE | IMPACT |
+|---------|------|----------|----------|------------------|--------------|--------|
+| [Citation numbers] | [YYYY-MM-DD] | [Descriptive headline] | [Specific aspect/genre] | [What happened - 3 sentences max] | [Why it matters to the community] | [1-10 score] |
+
+IMPORTANT: In the SOURCES column, list the citation numbers (e.g., [1, 3, 5]) that support this news item. These should match the numbered references at the end of your report.
+
+Example for anime topic:
+| [1, 3] | 2025-01-07 | Studio Ghibli Announces New Film Project | Animation/Film | Legendary animation studio reveals first details about upcoming feature. Director Hayao Miyazaki returns from retirement again. Production scheduled to begin this spring. | Major event for anime industry and global animation fans. Could influence animation trends for years. | 8 |
+
+SEARCH STRATEGY:
+1. "[TOPIC]" news today YYYY-MM-DD latest announcement update
+2. "[TOPIC]" breaking developments industry changes YYYY-MM-DD
+3. site:specialized-sites.com "[TOPIC]" today YYYY-MM-DD (use relevant specialized sites for the topic)
+4. "[TOPIC]" different various multiple separate news YYYY-MM-DD
+
+DIVERSITY REQUIREMENTS - MUST find news about:
+- DIFFERENT companies/studios/creators (not all from the same source)
+- DIFFERENT products/series/projects (not all about the same thing)
+- DIFFERENT aspects of the topic (technology, business, culture, events, etc.)
+- DIFFERENT geographic regions if applicable
+
+Focus areas (adapt based on topic) - aim for 10 DISTINCT news items:
+- Major announcements or releases
+- Industry developments
+- Community events or conventions
+- Creator/artist news
+- Technology or innovation updates
+- Cultural impact stories
+- Business and market news
+- Fan community highlights
+- Awards and recognition
+- Controversies or debates
+- International developments
+- Future predictions or trends
+
+Each row MUST be a COMPLETELY SEPARATE news story, not multiple angles of the same event.
+
+REQUIREMENTS:
+- Only include real news from verified sources
+- Sort by relevance and impact to the topic community
+- Each row must be complete with all columns filled
+- Keep focus on news that matters to enthusiasts of this topic
+- If insufficient news is found, include fewer rows rather than inventing content
+
+After the table, add:
+- **COMMUNITY PULSE**: One paragraph about how the [TOPIC] community is reacting to today's developments
+- **UPCOMING**: 3 bullet points about what to watch for in this topic area`
+ }
+};
+
+// Use news template
+function useNewsTemplate(templateId) {
+ if (templateId === 'custom') {
+ // For custom template, open subscription modal with empty query
+ showNewsSubscriptionModal('');
+ return;
+ }
+
+ const template = newsTemplates[templateId];
+ if (template) {
+ // DON'T replace YYYY-MM-DD here - keep it as a placeholder for the subscription
+ let updatedQuery = template.query;
+
+ // For topic news template, prompt for topic
+ if (templateId === 'topic-news') {
+ const topic = prompt('Enter the topic you want to track (e.g., anime, space exploration, renewable energy):');
+ if (!topic) {
+ return; // User cancelled
+ }
+ // Replace the topic placeholder and all instances of [TOPIC]
+ updatedQuery = updatedQuery.replace(/\[ENTER YOUR TOPIC HERE[^\]]*\]/g, topic);
+ updatedQuery = updatedQuery.replace(/\[TOPIC\]/g, topic);
+ }
+
+ // For local news template, prompt for location
+ if (templateId === 'local-news') {
+ const location = prompt('Enter your city or region:');
+ if (!location) {
+ return; // User cancelled
+ }
+ updatedQuery = updatedQuery.replace(/\[ENTER YOUR CITY\/REGION HERE\]/g, location);
+ }
+
+ // Open subscription modal with prefilled template
+ // Add a note to show user that dates will be dynamic
+ const modalName = template.name + (updatedQuery.includes('YYYY-MM-DD') ? ' (with dynamic dates)' : '');
+ showNewsSubscriptionModal(updatedQuery, modalName);
+ }
+}
+
+// Show subscription modal for news templates
+function showNewsSubscriptionModal(query = '', templateName = '') {
+ console.log('showNewsSubscriptionModal called with:', query, templateName);
+
+ // Create modal HTML if it doesn't exist
+ if (!document.getElementById('newsSubscriptionModal')) {
+ console.log('Creating modal HTML');
+ const modalHtml = `
+ <div class="modal fade" id="newsSubscriptionModal" tabindex="-1">
+ <div class="modal-dialog">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h5 class="modal-title">Create News Subscription</h5>
+ <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
+ </div>
+ <form id="news-subscription-form">
+ <div class="modal-body">
+ <div class="mb-3">
+ <label for="news-subscription-query" class="form-label">Topic or Search Query</label>
+ <textarea class="form-control" id="news-subscription-query" rows="4"
+ placeholder="e.g., artificial intelligence, climate change, tech news" required></textarea>
+ <div class="form-text">Enter keywords, topics, or search queries you want to track</div>
+ </div>
+
+ <div class="mb-3">
+ <label for="news-subscription-name" class="form-label">Subscription Name (Optional)</label>
+ <input type="text" class="form-control" id="news-subscription-name"
+ placeholder="e.g., AI Research Updates">
+ </div>
+
+ <div class="row">
+ <div class="col-md-6 mb-3">
+ <label for="news-subscription-frequency" class="form-label">Update Frequency</label>
+ <select class="form-select" id="news-subscription-frequency">
+ <option value="hourly">Every Hour</option>
+ <option value="daily" selected>Daily</option>
+ <option value="weekly">Weekly</option>
+ </select>
+ </div>
+
+ <div class="col-md-6 mb-3">
+ <label for="news-subscription-folder" class="form-label">Folder</label>
+ <select class="form-select" id="news-subscription-folder">
+ <option value="">Uncategorized</option>
+ <!-- Dynamic folders will be added here -->
+ </select>
+ </div>
+ </div>
+
+ <div class="mb-3">
+ <div class="form-check">
+ <input class="form-check-input" type="checkbox" id="news-subscription-active" checked>
+ <label class="form-check-label" for="news-subscription-active">
+ Start active (begin collecting news immediately)
+ </label>
+ </div>
+ </div>
+
+ <div class="mb-3">
+ <div class="form-check">
+ <input class="form-check-input" type="checkbox" id="news-subscription-run-now" checked>
+ <label class="form-check-label" for="news-subscription-run-now">
+ Run immediately after creating
+ </label>
+ </div>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
+ <button type="button" class="btn btn-primary" id="run-template-btn">Run Once</button>
+ <button type="submit" class="btn btn-primary">Create Subscription</button>
+ </div>
+ </form>
+ </div>
+ </div>
+ </div>
+ `;
+ document.body.insertAdjacentHTML('beforeend', modalHtml);
+
+ // Set up form submission handler
+ document.getElementById('news-subscription-form').addEventListener('submit', handleNewsSubscriptionSubmit);
+
+ // Set up run once button
+ document.getElementById('run-template-btn').addEventListener('click', async () => {
+ const query = document.getElementById('news-subscription-query').value;
+ console.log('Run Once clicked, query:', query);
+ if (query) {
+ // Close modal first
+ bootstrap.Modal.getInstance(document.getElementById('newsSubscriptionModal')).hide();
+
+ // Use the same advanced search function that the search uses
+ console.log('Calling performAdvancedNewsSearch with query:', query);
+ await performAdvancedNewsSearch(query);
+ } else {
+ console.error('No query found in news-subscription-query input');
+ showAlert('Please enter a query', 'warning');
+ }
+ });
+ }
+
+ // Prefill the form
+ document.getElementById('news-subscription-query').value = query;
+ document.getElementById('news-subscription-name').value = templateName;
+
+ // Load folders
+ loadSubscriptionFolders();
+
+ // Show the modal
+ try {
+ console.log('Attempting to show modal');
+ if (typeof bootstrap === 'undefined') {
+ console.error('Bootstrap is not loaded!');
+ alert('Bootstrap is not loaded. Please refresh the page.');
+ return;
+ }
+ const modalElement = document.getElementById('newsSubscriptionModal');
+ if (!modalElement) {
+ console.error('Modal element not found!');
+ return;
+ }
+ const modal = new bootstrap.Modal(modalElement);
+ modal.show();
+ console.log('Modal should be visible now');
+ } catch (error) {
+ console.error('Error showing modal:', error);
+ alert('Error showing subscription modal: ' + error.message);
+ }
+}
+
+// Handle news subscription form submission
+async function handleNewsSubscriptionSubmit(e) {
+ e.preventDefault();
+
+ const query = document.getElementById('news-subscription-query').value;
+ const name = document.getElementById('news-subscription-name').value || query.substring(0, 50);
+ const frequency = document.getElementById('news-subscription-frequency').value;
+ const folder = document.getElementById('news-subscription-folder').value;
+ const isActive = document.getElementById('news-subscription-active').checked;
+ const runNow = document.getElementById('news-subscription-run-now').checked;
+
+ try {
+ // Create the subscription
+ const response = await fetch('/news/api/subscribe', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': getCSRFToken()
+ },
+ body: JSON.stringify({
+ user_id: currentUser,
+ query: query,
+ subscription_type: 'search',
+ refresh_hours: parseInt(frequency)
+ })
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ showAlert('Subscription created successfully!', 'success');
+
+ // Close modal
+ bootstrap.Modal.getInstance(document.getElementById('newsSubscriptionModal')).hide();
+
+ // Run immediately if requested
+ if (runNow && data.subscription_id) {
+ // Call the run endpoint for this subscription
+ try {
+ const runResponse = await fetch(`/news/api/subscriptions/${data.subscription_id}/run`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': getCSRFToken()
+ }
+ });
+
+ if (runResponse.ok) {
+ const runData = await runResponse.json();
+
+ if (runData.research_id) {
+ showAlert('Subscription research started...', 'info');
+
+ // Show loading state in news feed with progress visualization
+ const container = document.getElementById('news-feed-content');
+ const progressCard = document.createElement('div');
+ progressCard.className = 'news-card priority-high active-research-card';
+ progressCard.innerHTML = `
+ <div class="news-header">
+ <h2 class="news-title">
+ <i class="bi bi-hourglass-split spinning"></i>
+ Running subscription: "${query.substring(0, 60)}..."
+ </h2>
+ </div>
+ <div class="news-meta">
+ <span><i class="bi bi-info-circle"></i> Research ID: ${runData.research_id}</span>
+ <span><i class="bi bi-clock"></i> Started just now</span>
+ </div>
+ <div class="news-summary">
+ <div class="progress">
+ <div class="progress-bar progress-bar-striped progress-bar-animated"
+ role="progressbar" style="width: 10%"></div>
+ </div>
+ <p class="mt-2">Searching for breaking news and analyzing importance...</p>
+ </div>
+ `;
+
+ // Insert at the top of the feed
+ container.insertBefore(progressCard, container.firstChild);
+
+ // Poll for results
+ pollForNewsResearchResults(runData.research_id, query);
+ }
+ } else {
+ console.error('Failed to run subscription immediately');
+ }
+ } catch (error) {
+ console.error('Error running subscription:', error);
+ }
+ }
+
+ // Update sidebar subscriptions
+ loadSubscriptions();
+ } else {
+ const error = await response.json();
+ showAlert(error.error || 'Failed to create subscription', 'danger');
+ }
+ } catch (error) {
+ console.error('Error creating subscription:', error);
+ showAlert('Failed to create subscription', 'danger');
+ }
+}
+
+// Load subscription folders for the modal
+async function loadSubscriptionFolders() {
+ try {
+ const response = await fetch('/news/api/subscription/folders');
+ if (response.ok) {
+ const folders = await response.json();
+ const select = document.getElementById('news-subscription-folder');
+
+ // Clear existing options except the first one
+ select.innerHTML = '<option value="">Uncategorized</option>';
+
+ // Add folder options
+ folders.forEach(folder => {
+ const option = document.createElement('option');
+ option.value = folder.name;
+ option.textContent = `${folder.icon || '📁'} ${folder.name}`;
+ select.appendChild(option);
+ });
+ }
+ } catch (error) {
+ console.error('Error loading folders:', error);
+ }
+}
+
+// Show custom template modal
+function showCustomTemplateModal() {
+ const modalHtml = `
+ <div class="modal fade" id="customTemplateModal" tabindex="-1">
+ <div class="modal-dialog modal-lg">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h5 class="modal-title">Create Custom News Template</h5>
+ <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
+ </div>
+ <div class="modal-body">
+ <div class="mb-3">
+ <label class="form-label">Template Name</label>
+ <input type="text" class="form-control" id="template-name" placeholder="e.g., Industry Analysis">
+ </div>
+ <div class="mb-3">
+ <label class="form-label">Search Query Template</label>
+ <textarea class="form-control" id="template-query" rows="10" placeholder="Enter your custom news search query..."></textarea>
+ </div>
+ <div class="alert alert-info">
+ <i class="bi bi-info-circle"></i> Tips:
+ <ul class="mb-0 mt-2">
+ <li>Use markdown tables for structured output</li>
+ <li>Include specific search instructions</li>
+ <li>Define clear column headers</li>
+ <li>Specify date ranges and sources</li>
+ </ul>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
+ <button type="button" class="btn btn-primary" onclick="applyCustomTemplate()">Use Template</button>
+ </div>
+ </div>
+ </div>
+ </div>
+ `;
+
+ // Remove existing modal if any
+ const existingModal = document.getElementById('customTemplateModal');
+ if (existingModal) {
+ existingModal.remove();
+ }
+
+ // Add modal to body
+ document.body.insertAdjacentHTML('beforeend', modalHtml);
+
+ // Show modal
+ const modal = new bootstrap.Modal(document.getElementById('customTemplateModal'));
+ modal.show();
+}
+
+// Apply custom template
+function applyCustomTemplate() {
+ const templateName = document.getElementById('template-name').value;
+ const templateQuery = document.getElementById('template-query').value;
+
+ if (!templateQuery.trim()) {
+ showAlert('Please enter a template query', 'warning');
+ return;
+ }
+
+ // Set the query
+ const searchInput = document.getElementById('news-search-input');
+ searchInput.value = templateQuery;
+
+ // Close modal
+ const modal = bootstrap.Modal.getInstance(document.getElementById('customTemplateModal'));
+ modal.hide();
+
+ // Show message
+ showAlert(`Custom template "${templateName || 'Untitled'}" loaded. Click "Search News" to run.`, 'success');
+}
+
+// Expose functions to global scope for onclick handlers
+window.filterByTopic = filterByTopic;
+window.clearTopicFilter = clearTopicFilter;
+window.clearAllFilters = clearAllFilters;
+window.createTopicSubscription = createTopicSubscription;
+window.useNewsTemplate = useNewsTemplate;
+window.applyCustomTemplate = applyCustomTemplate;
+window.vote = vote;
+window.saveItem = saveItem;
+window.loadNewsTableQuery = loadNewsTableQuery;
+window.hideQueryTemplate = hideQueryTemplate;
+window.useQueryTemplate = useQueryTemplate;
+window.copyQueryTemplate = copyQueryTemplate;
+window.refreshFeed = refreshFeed;
+window.rerunSearch = rerunSearch;
+window.toggleReadStatus = toggleReadStatus;
+window.markAllAsRead = markAllAsRead;
+window.toggleExpanded = toggleExpanded;
+window.expandAll = expandAll;
+window.collapseAll = collapseAll;
+window.shareNews = shareNews;
+window.copyNewsLink = copyNewsLink;
+window.exportToMarkdown = exportToMarkdown;
+window.hideNewsItem = hideNewsItem;
+window.reportIssue = reportIssue;
+window.toggleSaveItem = toggleSaveItem;
+window.selectSubscription = selectSubscription;
+// window.filterBySubscription = filterBySubscription; // Function not implemented yet
+window.showCreateSubscriptionModal = showCreateSubscriptionModal;
+window.createSubscription = createSubscription;
diff --git a/src/local_deep_research/web/static/js/pages/subscriptions.js b/src/local_deep_research/web/static/js/pages/subscriptions.js
new file mode 100644
index 0000000000..bcf71a0645
--- /dev/null
+++ b/src/local_deep_research/web/static/js/pages/subscriptions.js
@@ -0,0 +1,874 @@
+// Subscriptions Management Page
+let subscriptions = [];
+let folders = [];
+let currentFilter = {
+ folder: 'all',
+ status: 'all',
+ frequency: 'all',
+ search: ''
+};
+
+// Initialize page
+document.addEventListener('DOMContentLoaded', function() {
+ loadSubscriptions();
+ loadFolders();
+ setupEventListeners();
+ checkSchedulerStatus();
+});
+
+// Setup event listeners
+function setupEventListeners() {
+ // Search box
+ document.getElementById('subscription-search').addEventListener('input', (e) => {
+ currentFilter.search = e.target.value;
+ renderSubscriptions();
+ });
+
+ // Filter dropdowns
+ document.getElementById('status-filter').addEventListener('change', (e) => {
+ currentFilter.status = e.target.value;
+ renderSubscriptions();
+ });
+
+ document.getElementById('frequency-filter').addEventListener('change', (e) => {
+ currentFilter.frequency = e.target.value;
+ renderSubscriptions();
+ });
+
+ // Folder navigation
+ document.addEventListener('click', (e) => {
+ if (e.target.closest('.folder-item')) {
+ const folderItem = e.target.closest('.folder-item');
+ const folderId = folderItem.dataset.folder;
+ selectFolder(folderId);
+ }
+ });
+
+ // New subscription form
+ const form = document.getElementById('new-subscription-form');
+ if (form) {
+ form.addEventListener('submit', handleNewSubscription);
+ }
+
+ // Edit subscription form
+ const editForm = document.getElementById('edit-subscription-form');
+ if (editForm) {
+ editForm.addEventListener('submit', handleEditSubscription);
+ }
+
+ // Delete subscription button
+ const deleteBtn = document.getElementById('delete-subscription-btn');
+ if (deleteBtn) {
+ deleteBtn.addEventListener('click', handleDeleteSubscription);
+ }
+
+ // Add folder button
+ document.getElementById('add-folder-btn').addEventListener('click', createNewFolder);
+}
+
+// Load subscriptions from API
+async function loadSubscriptions() {
+ try {
+ const userId = getCurrentUserId();
+ const response = await fetch(`/news/api/subscriptions/${userId}`);
+
+ if (response.ok) {
+ const data = await response.json();
+ subscriptions = data.subscriptions || [];
+ renderSubscriptions();
+ updateStats();
+ }
+ } catch (error) {
+ console.error('Error loading subscriptions:', error);
+ showAlert('Failed to load subscriptions', 'error');
+ }
+}
+
+// Load folders
+async function loadFolders() {
+ try {
+ const response = await fetch(`/news/api/subscription/folders?user_id=${getCurrentUserId()}`);
+ if (response.ok) {
+ const data = await response.json();
+ folders = Array.isArray(data) ? data : (data.folders || []);
+ renderFolders();
+ }
+ } catch (error) {
+ console.error('Error loading folders:', error);
+ }
+}
+
+// Render subscriptions grid
+function renderSubscriptions() {
+ const grid = document.getElementById('subscriptions-grid');
+ const filtered = filterSubscriptions();
+
+ if (filtered.length === 0) {
+ grid.innerHTML = `
+ <div class="empty-state">
+ <i class="bi bi-bell-slash"></i>
+ <h3>No subscriptions found</h3>
+ <p>Create your first subscription to start tracking news topics</p>
+ </div>
+ `;
+ return;
+ }
+
+ grid.innerHTML = filtered.map(sub => createSubscriptionCard(sub)).join('');
+}
+
+// Create subscription card HTML
+function createSubscriptionCard(subscription) {
+ const statusClass = subscription.is_active ? 'active' : 'paused';
+ const statusIcon = subscription.is_active ? 'bi-play-circle' : 'bi-pause-circle';
+ const lastUpdated = subscription.last_refreshed ?
+ new Date(subscription.last_refreshed).toLocaleString() : 'Never';
+
+ // Convert refresh_hours to readable format
+ const refreshInterval = subscription.refresh_hours === 1 ? 'Hourly' :
+ subscription.refresh_hours === 168 ? 'Weekly' :
+ subscription.refresh_hours === 24 ? 'Daily' :
+ `Every ${subscription.refresh_hours} hours`;
+
+ // Truncate long text
+ const displayName = subscription.name || subscription.query;
+ const truncatedName = displayName.length > 50 ? displayName.substring(0, 50) + '...' : displayName;
+ const truncatedQuery = subscription.query.length > 80 ? subscription.query.substring(0, 80) + '...' : subscription.query;
+
+ return `
+ <div class="subscription-card" data-subscription-id="${subscription.id}" onclick="viewSubscriptionHistory('${subscription.id}')" style="cursor: pointer;">
+ <div class="card-header">
+ <h4 title="${displayName}">${truncatedName}</h4>
+ <div class="card-actions">
+ <button class="btn btn-sm btn-icon" onclick="event.stopPropagation(); runSubscriptionNow('${subscription.id}')" title="Run now">
+ <i class="bi bi-arrow-clockwise"></i>
+ </button>
+ <button class="btn btn-sm btn-icon" onclick="event.stopPropagation(); toggleSubscription('${subscription.id}')" title="${statusClass === 'active' ? 'Pause' : 'Resume'}">
+ <i class="bi ${statusIcon}"></i>
+ </button>
+ <button class="btn btn-sm btn-icon" onclick="event.stopPropagation(); viewSubscriptionHistory('${subscription.id}')" title="View history">
+ <i class="bi bi-clock-history"></i>
+ </button>
+ <button class="btn btn-sm btn-icon" onclick="event.stopPropagation(); editSubscription('${subscription.id}')" title="Edit">
+ <i class="bi bi-pencil"></i>
+ </button>
+ <button class="btn btn-sm btn-icon btn-danger" onclick="event.stopPropagation(); deleteSubscriptionDirect('${subscription.id}')" title="Delete">
+ <i class="bi bi-trash"></i>
+ </button>
+ </div>
+ </div>
+ <div class="card-body">
+ <div class="query-text" title="${subscription.query}">${truncatedQuery}</div>
+ <div class="subscription-meta">
+ <span class="status-badge status-${statusClass}">${statusClass}</span>
+ <span class="frequency-badge">${refreshInterval}</span>
+ ${subscription.folder_id ? `<span class="folder-badge">${getFolderName(subscription.folder_id)}</span>` : ''}
+ </div>
+ <div class="subscription-stats">
+ <div class="stat-item">
+ <i class="bi bi-file-text"></i>
+ <span>${subscription.total_runs || 0} research runs</span>
+ </div>
+ ${subscription.source_id ? `
+ <div class="stat-item">
+ <i class="bi bi-link-45deg"></i>
+ <a href="/progress/${subscription.source_id}" class="source-link">View original research</a>
+ </div>
+ ` : ''}
+ </div>
+ <div class="last-updated">
+ <i class="bi bi-clock"></i> Last updated: ${lastUpdated}
+ </div>
+ ${subscription.next_refresh ? `
+ <div class="next-update">
+ <i class="bi bi-arrow-clockwise"></i> Next update: ${new Date(subscription.next_refresh).toLocaleString()}
+ </div>
+ ` : ''}
+ </div>
+ </div>
+ `;
+}
+
+// Filter subscriptions based on current filters
+function filterSubscriptions() {
+ return subscriptions.filter(sub => {
+ // Folder filter
+ if (currentFilter.folder !== 'all') {
+ if (currentFilter.folder === 'uncategorized' && sub.folder_id) return false;
+ if (currentFilter.folder !== 'uncategorized' && sub.folder_id !== currentFilter.folder) return false;
+ }
+
+ // Status filter
+ if (currentFilter.status !== 'all') {
+ const isActive = sub.is_active;
+ if (currentFilter.status === 'active' && !isActive) return false;
+ if (currentFilter.status === 'paused' && isActive) return false;
+ }
+
+ // Frequency filter
+ if (currentFilter.frequency !== 'all' && sub.refresh_interval !== currentFilter.frequency) {
+ return false;
+ }
+
+ // Search filter
+ if (currentFilter.search) {
+ const searchLower = currentFilter.search.toLowerCase();
+ const nameMatch = (sub.name || '').toLowerCase().includes(searchLower);
+ const queryMatch = sub.query.toLowerCase().includes(searchLower);
+ if (!nameMatch && !queryMatch) return false;
+ }
+
+ return true;
+ });
+}
+
+// Handle new subscription creation
+async function handleNewSubscription(e) {
+ e.preventDefault();
+
+ const query = document.getElementById('subscription-query').value.trim();
+ const name = document.getElementById('subscription-name').value.trim();
+ const frequency = document.getElementById('subscription-frequency').value;
+ const folderId = document.getElementById('subscription-folder').value;
+ const isActive = document.getElementById('subscription-active').checked;
+
+ if (!query) {
+ showAlert('Please enter a topic or search query', 'warning');
+ return;
+ }
+
+ try {
+ const response = await fetch('/news/api/subscribe', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': getCSRFToken()
+ },
+ body: JSON.stringify({
+ user_id: getCurrentUserId(),
+ query: query,
+ subscription_type: 'search',
+ refresh_hours: frequency === 'hourly' ? 1 : frequency === 'weekly' ? 168 : 24,
+ name: name || null,
+ folder_id: folderId || null,
+ is_active: isActive
+ })
+ });
+
+ if (response.ok) {
+ const result = await response.json();
+ showAlert('Subscription created successfully!', 'success');
+
+ // Close modal
+ const modal = bootstrap.Modal.getInstance(document.getElementById('addSubscriptionModal'));
+ modal.hide();
+
+ // Reset form
+ document.getElementById('new-subscription-form').reset();
+
+ // Reload subscriptions
+ await loadSubscriptions();
+ } else {
+ const error = await response.json();
+ showAlert(error.error || 'Failed to create subscription', 'error');
+ }
+ } catch (error) {
+ console.error('Error creating subscription:', error);
+ showAlert('Failed to create subscription', 'error');
+ }
+}
+
+// Run subscription now - uses the same research system as news page
+async function runSubscriptionNow(subscriptionId) {
+ const subscription = subscriptions.find(s => s.id === subscriptionId);
+ if (!subscription) return;
+
+ try {
+ const query = subscription.query || subscription.query_or_topic || '';
+ console.log('Running subscription:', subscriptionId, 'with query:', query);
+ showAlert('Starting research for: ' + query, 'info');
+
+ const requestData = {
+ query: query,
+ mode: 'quick',
+ metadata: {
+ is_news_search: true,
+ search_type: 'news_analysis',
+ display_in: 'news_feed',
+ subscription_id: subscriptionId,
+ triggered_by: 'manual_run'
+ }
+ };
+ console.log('Sending research request:', requestData);
+
+ // Use the same research endpoint as the news page
+ const response = await fetch('/api/start_research', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': getCSRFToken()
+ },
+ body: JSON.stringify(requestData)
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ console.log('Research API response:', data);
+
+ if (data.status === 'success' && data.research_id) {
+ showAlert(`Research started! <a href="/progress/${data.research_id}" style="color: white; text-decoration: underline;">View progress</a>`, 'success');
+
+ // Store active research in localStorage so news page can show progress
+ localStorage.setItem('active_news_research', JSON.stringify({
+ researchId: data.research_id,
+ query: query,
+ startTime: new Date().toISOString()
+ }));
+
+ // Update the subscription's last run time
+ subscription.last_run = new Date().toISOString();
+ renderSubscriptions();
+
+ // Refresh subscription data after a delay
+ setTimeout(() => loadSubscriptions(), 2000);
+
+ // Optional: Open news page to show progress
+ // window.open('/news', '_blank');
+ } else {
+ console.error('Unexpected response:', data);
+ showAlert('Failed to start research: ' + (data.message || 'Unknown error'), 'error');
+ }
+ } else {
+ console.error('Research API error:', response.status, response.statusText);
+ const errorData = await response.json().catch(() => ({}));
+ console.error('Error data:', errorData);
+ showAlert(errorData.message || 'Failed to start research', 'error');
+ }
+ } catch (error) {
+ console.error('Error running subscription:', error);
+ showAlert('Failed to start research', 'error');
+ }
+}
+
+// Toggle subscription active/paused
+async function toggleSubscription(subscriptionId) {
+ const subscription = subscriptions.find(s => s.id === subscriptionId);
+ if (!subscription) return;
+
+ try {
+ const response = await fetch(`/news/api/subscription/subscriptions/${subscriptionId}`, {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': getCSRFToken()
+ },
+ body: JSON.stringify({
+ is_active: !subscription.is_active
+ })
+ });
+
+ if (response.ok) {
+ subscription.is_active = !subscription.is_active;
+ renderSubscriptions();
+ updateStats();
+ }
+ } catch (error) {
+ console.error('Error toggling subscription:', error);
+ showAlert('Failed to update subscription', 'error');
+ }
+}
+
+// View subscription history
+async function viewSubscriptionHistory(subscriptionId) {
+ const subscription = subscriptions.find(s => s.id === subscriptionId);
+ if (!subscription) return;
+
+ try {
+ // Fetch subscription history
+ const response = await fetch(`/news/api/subscriptions/${subscriptionId}/history`);
+ if (response.ok) {
+ const data = await response.json();
+ showSubscriptionHistoryModal(subscription, data);
+ } else {
+ showAlert('Failed to load subscription history', 'error');
+ }
+ } catch (error) {
+ console.error('Error loading subscription history:', error);
+ showAlert('Failed to load subscription history', 'error');
+ }
+}
+
+// Show subscription history modal
+function showSubscriptionHistoryModal(subscription, historyData) {
+ // Create modal content
+ const modalContent = `
+ <div class="modal fade" id="historyModal" tabindex="-1">
+ <div class="modal-dialog modal-lg">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h5 class="modal-title">
+ <i class="bi bi-clock-history"></i> History: ${subscription.name || subscription.query}
+ </h5>
+ <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
+ </div>
+ <div class="modal-body">
+ <div class="history-summary">
+ <p><strong>Total research runs:</strong> ${historyData.total_runs || 0}</p>
+ <p><strong>Created:</strong> ${new Date(subscription.created_at).toLocaleString()}</p>
+ ${subscription.source_id ? `
+ <p><strong>Created from:</strong>
+ <a href="/progress/${subscription.source_id}" target="_blank">
+ Original research <i class="bi bi-box-arrow-up-right"></i>
+ </a>
+ </p>
+ ` : ''}
+ </div>
+
+ <h6 class="mt-4">Recent Research Runs</h6>
+ <div class="history-list" style="max-height: 400px; overflow-y: auto;">
+ ${historyData.history && historyData.history.length > 0 ?
+ historyData.history.map(item => `
+ <div class="history-item">
+ <div class="history-item-header">
+ <a href="/progress/${item.research_id}" target="_blank">
+ ${item.headline || '[No headline]'} <i class="bi bi-box-arrow-up-right"></i>
+ </a>
+ <span class="history-date">${new Date(item.created_at).toLocaleString()}</span>
+ </div>
+ <div class="history-item-meta">
+ <span class="status-badge status-${item.status}">${item.status}</span>
+ ${item.duration_seconds ? `<span class="duration">${item.duration_seconds}s</span>` : ''}
+ ${item.topics && item.topics.length > 0 ?
+ `<div class="topics-list">${item.topics.slice(0, 3).map(topic =>
+ `<span class="topic-badge">${topic}</span>`
+ ).join('')}</div>` : ''
+ }
+ </div>
+ </div>
+ `).join('') :
+ '<p class="text-muted">No research runs yet</p>'
+ }
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ `;
+
+ // Remove existing history modal if any
+ const existingModal = document.getElementById('historyModal');
+ if (existingModal) {
+ existingModal.remove();
+ }
+
+ // Add modal to page
+ document.body.insertAdjacentHTML('beforeend', modalContent);
+
+ // Show modal
+ const modal = new bootstrap.Modal(document.getElementById('historyModal'));
+ modal.show();
+
+ // Clean up when modal is hidden
+ document.getElementById('historyModal').addEventListener('hidden.bs.modal', function() {
+ this.remove();
+ });
+}
+
+// Edit subscription
+function editSubscription(subscriptionId) {
+ const subscription = subscriptions.find(s => s.id === subscriptionId);
+ if (!subscription) return;
+
+ // Populate edit modal
+ document.getElementById('edit-subscription-id').value = subscriptionId;
+ document.getElementById('edit-subscription-query').value = subscription.query;
+ document.getElementById('edit-subscription-name').value = subscription.name || '';
+ document.getElementById('edit-subscription-active').checked = subscription.is_active;
+
+ // Set frequency based on refresh_hours
+ let frequency = 'daily';
+ if (subscription.refresh_hours === 1) frequency = 'hourly';
+ else if (subscription.refresh_hours === 168) frequency = 'weekly';
+ document.getElementById('edit-subscription-frequency').value = frequency;
+
+ // Set folder
+ document.getElementById('edit-subscription-folder').value = subscription.folder_id || '';
+
+ // Update folder dropdown options
+ const folderSelect = document.getElementById('edit-subscription-folder');
+ folderSelect.innerHTML = '<option value="">Uncategorized</option>' +
+ folders.map(f => `<option value="${f.id}">${f.name}</option>`).join('');
+
+ // Re-select the folder after updating options
+ folderSelect.value = subscription.folder_id || '';
+
+ // Show modal
+ const modal = new bootstrap.Modal(document.getElementById('editSubscriptionModal'));
+ modal.show();
+}
+
+// Handle edit subscription form submission
+async function handleEditSubscription(e) {
+ e.preventDefault();
+
+ const subscriptionId = document.getElementById('edit-subscription-id').value;
+ const query = document.getElementById('edit-subscription-query').value.trim();
+ const name = document.getElementById('edit-subscription-name').value.trim();
+ const frequency = document.getElementById('edit-subscription-frequency').value;
+ const folderId = document.getElementById('edit-subscription-folder').value;
+ const isActive = document.getElementById('edit-subscription-active').checked;
+
+ if (!query) {
+ showAlert('Please enter a topic or search query', 'warning');
+ return;
+ }
+
+ try {
+ // Note: The news API doesn't have a direct update endpoint, so we'll need to use
+ // the subscription update endpoint which currently only supports folder updates
+ // For now, we'll show a message that full editing is coming soon
+ showAlert('Full subscription editing coming soon! Currently only folder assignment can be updated.', 'info');
+
+ // Close modal
+ const modal = bootstrap.Modal.getInstance(document.getElementById('editSubscriptionModal'));
+ modal.hide();
+
+ } catch (error) {
+ console.error('Error updating subscription:', error);
+ showAlert('Failed to update subscription', 'error');
+ }
+}
+
+// Handle delete subscription
+async function handleDeleteSubscription() {
+ const subscriptionId = document.getElementById('edit-subscription-id').value;
+ const subscription = subscriptions.find(s => s.id === subscriptionId);
+
+ if (!subscription || !confirm(`Are you sure you want to delete the subscription "${subscription.name || subscription.query}"?`)) {
+ return;
+ }
+
+ try {
+ const response = await fetch(`/news/api/subscriptions/${subscriptionId}`, {
+ method: 'DELETE',
+ headers: {
+ 'X-CSRFToken': getCSRFToken()
+ }
+ });
+
+ if (response.ok) {
+ showAlert('Subscription deleted successfully', 'success');
+
+ // Close modal
+ const modal = bootstrap.Modal.getInstance(document.getElementById('editSubscriptionModal'));
+ modal.hide();
+
+ // Reload subscriptions
+ await loadSubscriptions();
+ } else {
+ const error = await response.json();
+ showAlert(error.error || 'Failed to delete subscription', 'error');
+ }
+ } catch (error) {
+ console.error('Error deleting subscription:', error);
+ showAlert('Failed to delete subscription', 'error');
+ }
+}
+
+// Delete subscription directly from card
+async function deleteSubscriptionDirect(subscriptionId) {
+ const subscription = subscriptions.find(s => s.id === subscriptionId);
+
+ if (!subscription || !confirm(`Are you sure you want to delete the subscription "${subscription.name || subscription.query}"?`)) {
+ return;
+ }
+
+ try {
+ const response = await fetch(`/news/api/subscriptions/${subscriptionId}`, {
+ method: 'DELETE',
+ headers: {
+ 'X-CSRFToken': getCSRFToken()
+ }
+ });
+
+ if (response.ok) {
+ showAlert('Subscription deleted successfully', 'success');
+ // Reload subscriptions
+ await loadSubscriptions();
+ } else {
+ const error = await response.json();
+ showAlert(error.error || 'Failed to delete subscription', 'error');
+ }
+ } catch (error) {
+ console.error('Error deleting subscription:', error);
+ showAlert('Failed to delete subscription', 'error');
+ }
+}
+
+// Update statistics
+function updateStats() {
+ const total = subscriptions.length;
+ const active = subscriptions.filter(s => s.is_active).length;
+ const paused = total - active;
+ const updatedToday = subscriptions.filter(s => {
+ if (!s.last_refreshed) return false;
+ const lastUpdate = new Date(s.last_refreshed);
+ const today = new Date();
+ return lastUpdate.toDateString() === today.toDateString();
+ }).length;
+
+ document.getElementById('total-subscriptions').textContent = total;
+ document.getElementById('active-subscriptions').textContent = active;
+ document.getElementById('paused-subscriptions').textContent = paused;
+ document.getElementById('updates-today').textContent = updatedToday;
+}
+
+// Folder management
+function renderFolders() {
+ const folderList = document.querySelector('.folder-list');
+
+ // Remove existing dynamic folders first
+ document.querySelectorAll('.folder-item[data-folder]:not([data-folder="all"]):not([data-folder="uncategorized"])').forEach(el => el.remove());
+
+ const dynamicFolders = folders.map(folder => `
+ <div class="folder-item" data-folder="${folder.id}">
+ <i class="bi bi-folder"></i> ${folder.name}
+ <span class="folder-count">${countSubscriptionsInFolder(folder.id)}</span>
+ </div>
+ `).join('');
+
+ // Update counts for default folders
+ document.querySelector('[data-folder="all"] .folder-count').textContent = subscriptions.length;
+ document.querySelector('[data-folder="uncategorized"] .folder-count').textContent =
+ subscriptions.filter(s => !s.folder_id).length;
+
+ // Insert dynamic folders after uncategorized
+ const uncategorizedFolder = document.querySelector('[data-folder="uncategorized"]');
+ if (dynamicFolders) {
+ uncategorizedFolder.insertAdjacentHTML('afterend', dynamicFolders);
+ }
+
+ // Update folder dropdown in add modal
+ const folderSelect = document.getElementById('subscription-folder');
+ if (folderSelect) {
+ folderSelect.innerHTML = '<option value="">Uncategorized</option>' +
+ folders.map(f => `<option value="${f.id}">${f.name}</option>`).join('');
+ }
+
+ // Also update edit modal folder dropdown if it exists
+ const editFolderSelect = document.getElementById('edit-subscription-folder');
+ if (editFolderSelect) {
+ editFolderSelect.innerHTML = '<option value="">Uncategorized</option>' +
+ folders.map(f => `<option value="${f.id}">${f.name}</option>`).join('');
+ }
+}
+
+function countSubscriptionsInFolder(folderId) {
+ return subscriptions.filter(s => s.folder_id === folderId).length;
+}
+
+function selectFolder(folderId) {
+ // Update active state
+ document.querySelectorAll('.folder-item').forEach(item => {
+ item.classList.toggle('active', item.dataset.folder === folderId);
+ });
+
+ currentFilter.folder = folderId;
+ renderSubscriptions();
+}
+
+async function createNewFolder() {
+ const name = prompt('Enter folder name:');
+ if (!name || !name.trim()) return;
+
+ try {
+ const response = await fetch('/news/api/subscription/folders', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': getCSRFToken()
+ },
+ body: JSON.stringify({
+ name: name.trim(),
+ user_id: getCurrentUserId()
+ })
+ });
+
+ if (response.ok) {
+ const folder = await response.json();
+ showAlert(`Folder "${folder.name}" created successfully!`, 'success');
+
+ // Reload folders
+ await loadFolders();
+
+ // Re-render subscriptions to update folder badges
+ renderSubscriptions();
+ } else {
+ const error = await response.json();
+ if (response.status === 409) {
+ showAlert('A folder with that name already exists', 'warning');
+ } else {
+ showAlert(error.error || 'Failed to create folder', 'error');
+ }
+ }
+ } catch (error) {
+ console.error('Error creating folder:', error);
+ showAlert('Failed to create folder', 'error');
+ }
+}
+
+// Utility functions
+function getCurrentUserId() {
+ return localStorage.getItem('userId') || 'anonymous';
+}
+
+function getCSRFToken() {
+ return document.querySelector('meta[name="csrf-token"]')?.content || '';
+}
+
+function getFolderName(folderId) {
+ const folder = folders.find(f => f.id === folderId);
+ return folder ? folder.name : 'Unknown';
+}
+
+function showAlert(message, type) {
+ // Simple alert implementation
+ const alertDiv = document.createElement('div');
+ alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
+ alertDiv.innerHTML = `
+ ${message}
+ <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
+ `;
+
+ const container = document.querySelector('.page-header');
+ container.insertAdjacentElement('afterend', alertDiv);
+
+ // Auto-dismiss after 5 seconds
+ setTimeout(() => alertDiv.remove(), 5000);
+}
+
+// Scheduler status functions
+async function checkSchedulerStatus() {
+ const statusIndicator = document.getElementById('status-indicator');
+ const statusText = document.getElementById('status-text');
+ const schedulerDetails = document.getElementById('scheduler-details');
+ const toggleButton = document.getElementById('toggle-scheduler');
+ const checkNowButton = document.getElementById('check-now');
+
+ // Set checking state
+ statusIndicator.className = 'status-indicator checking';
+ statusText.textContent = 'Checking...';
+
+ try {
+ const response = await fetch('/news/api/scheduler/status');
+ if (response.ok) {
+ const data = await response.json();
+
+ if (data.scheduler_available) {
+ if (data.is_running) {
+ statusIndicator.className = 'status-indicator active';
+ statusText.textContent = 'Active';
+ schedulerDetails.textContent = data.next_check ?
+ `Next check: ${new Date(data.next_check).toLocaleTimeString()}` :
+ 'Running...';
+
+ // Update button state
+ toggleButton.style.display = 'none';
+ checkNowButton.disabled = false;
+ } else {
+ statusIndicator.className = 'status-indicator inactive';
+ statusText.textContent = 'Stopped';
+ schedulerDetails.textContent = 'Auto-refresh is disabled';
+
+ // Show start button
+ toggleButton.style.display = 'inline-flex';
+ toggleButton.innerHTML = '<i class="bi bi-play-fill"></i> Start Scheduler';
+ toggleButton.onclick = () => startScheduler();
+ checkNowButton.disabled = true;
+ }
+ } else {
+ statusIndicator.className = 'status-indicator inactive';
+ statusText.textContent = 'Not Available';
+ schedulerDetails.textContent = 'Install APScheduler: pip install apscheduler';
+ toggleButton.style.display = 'none';
+ checkNowButton.disabled = true;
+ }
+ } else {
+ throw new Error('Failed to check scheduler status');
+ }
+ } catch (error) {
+ console.error('Error checking scheduler status:', error);
+ statusIndicator.className = 'status-indicator inactive';
+ statusText.textContent = 'Error';
+ schedulerDetails.textContent = 'Unable to check scheduler status';
+ toggleButton.style.display = 'none';
+ checkNowButton.disabled = true;
+ }
+
+ // Set up check now button
+ checkNowButton.onclick = () => checkAllSubscriptionsNow();
+}
+
+async function startScheduler() {
+ const toggleButton = document.getElementById('toggle-scheduler');
+ toggleButton.disabled = true;
+ toggleButton.innerHTML = '<i class="bi bi-hourglass-split"></i> Starting...';
+
+ try {
+ const response = await fetch('/news/api/scheduler/start', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': getCSRFToken()
+ }
+ });
+
+ if (response.ok) {
+ showAlert('Scheduler started successfully', 'success');
+ // Recheck status after a delay
+ setTimeout(() => checkSchedulerStatus(), 1000);
+ } else {
+ const error = await response.json();
+ showAlert(`Failed to start scheduler: ${error.error || 'Unknown error'}`, 'error');
+ toggleButton.disabled = false;
+ }
+ } catch (error) {
+ console.error('Error starting scheduler:', error);
+ showAlert('Failed to start scheduler', 'error');
+ toggleButton.disabled = false;
+ }
+}
+
+async function checkAllSubscriptionsNow() {
+ const checkButton = document.getElementById('check-now');
+ const originalHtml = checkButton.innerHTML;
+ checkButton.disabled = true;
+ checkButton.innerHTML = '<i class="bi bi-hourglass-split"></i> Checking...';
+
+ try {
+ const response = await fetch('/news/api/scheduler/check-now', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': getCSRFToken()
+ }
+ });
+
+ if (response.ok) {
+ const result = await response.json();
+ showAlert(`Checking ${result.count || 0} due subscriptions...`, 'info');
+
+ // Reload subscriptions after a delay to show updated times
+ setTimeout(() => loadSubscriptions(), 3000);
+ } else {
+ const error = await response.json();
+ showAlert(`Failed to check subscriptions: ${error.error || 'Unknown error'}`, 'error');
+ }
+ } catch (error) {
+ console.error('Error checking subscriptions:', error);
+ showAlert('Failed to check subscriptions', 'error');
+ } finally {
+ checkButton.disabled = false;
+ checkButton.innerHTML = originalHtml;
+ }
+}
diff --git a/src/local_deep_research/web/static/js/services/socket.js b/src/local_deep_research/web/static/js/services/socket.js
index 8cb22bb976..9855ad0ea4 100644
--- a/src/local_deep_research/web/static/js/services/socket.js
+++ b/src/local_deep_research/web/static/js/services/socket.js
@@ -25,6 +25,17 @@ window.socket = (function() {
return socket;
}
+ // Only initialize socket.io on research pages
+ const currentPath = window.location.pathname;
+ const isResearchPage = currentPath.includes('/research') ||
+ currentPath.includes('/progress') ||
+ currentPath.includes('/benchmark');
+
+ if (!isResearchPage) {
+ console.log('Socket.IO not needed on this page:', currentPath);
+ return null;
+ }
+
// Get the base URL from the current page
const baseUrl = window.location.protocol + '//' + window.location.host;
diff --git a/src/local_deep_research/web/templates/components/mobile_nav.html b/src/local_deep_research/web/templates/components/mobile_nav.html
index 4977270bf2..d0f0ac1132 100644
--- a/src/local_deep_research/web/templates/components/mobile_nav.html
+++ b/src/local_deep_research/web/templates/components/mobile_nav.html
@@ -12,6 +12,18 @@
<span>History</span>
</a>
</li>
+ <li {% if active_page == 'news' %}class="active"{% endif %} data-page="news">
+ <a href="{{ url_for('news.news_page') }}">
+ <i class="fas fa-newspaper"></i>
+ <span>News</span>
+ </a>
+ </li>
+ <li {% if active_page == 'subscriptions' %}class="active"{% endif %} data-page="subscriptions">
+ <a href="{{ url_for('news.subscriptions_page') }}">
+ <i class="fas fa-bell"></i>
+ <span>Subscriptions</span>
+ </a>
+ </li>
<li {% if active_page == 'settings' %}class="active"{% endif %} data-page="settings">
<a href="{{ url_for('settings.settings_page') }}">
<i class="fas fa-cog"></i>
diff --git a/src/local_deep_research/web/templates/components/sidebar.html b/src/local_deep_research/web/templates/components/sidebar.html
index b2f9d5320f..9d0557cce5 100644
--- a/src/local_deep_research/web/templates/components/sidebar.html
+++ b/src/local_deep_research/web/templates/components/sidebar.html
@@ -10,6 +10,12 @@
<li {% if active_page == 'history' %}class="active"{% endif %} data-page="history">
<a href="{{ url_for('history.history_page') }}"><i class="fas fa-history"></i> History</a>
</li>
+ <li {% if active_page == 'news' %}class="active"{% endif %} data-page="news">
+ <a href="{{ url_for('news.news_page') }}"><i class="fas fa-newspaper"></i> News</a>
+ </li>
+ <li {% if active_page == 'subscriptions' %}class="active"{% endif %} data-page="subscriptions">
+ <a href="{{ url_for('news.subscriptions_page') }}"><i class="fas fa-bell"></i> Subscriptions</a>
+ </li>
<li {% if active_page == 'benchmark' %}class="active"{% endif %} data-page="benchmark">
<a href="{{ url_for('benchmark.index') }}"><i class="fas fa-tachometer-alt"></i> Benchmark</a>
</li>
diff --git a/src/local_deep_research/web/templates/pages/history.html b/src/local_deep_research/web/templates/pages/history.html
index fba365924e..b9cb6fded3 100644
--- a/src/local_deep_research/web/templates/pages/history.html
+++ b/src/local_deep_research/web/templates/pages/history.html
@@ -7,6 +7,7 @@
{% block styles %}
{{ super() }}
<link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/components/history.css') }}">
+<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
{% endblock %}
{% block content %}
@@ -48,4 +49,6 @@
<script src="{{ url_for('research.serve_static', path='js/services/api.js') }}"></script>
<!-- Then load the component -->
<script src="{{ url_for('research.serve_static', path='js/components/history.js') }}"></script>
+<!-- Add Bootstrap JavaScript -->
+<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
{% endblock %}
diff --git a/src/local_deep_research/web/templates/pages/news.html b/src/local_deep_research/web/templates/pages/news.html
new file mode 100644
index 0000000000..a0fc18bdfb
--- /dev/null
+++ b/src/local_deep_research/web/templates/pages/news.html
@@ -0,0 +1,381 @@
+{% extends "base.html" %}
+
+{% block title %}LDR News - AI-Powered Research Feed{% endblock %}
+
+{% block extra_head %}
+<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
+<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.7.2/font/bootstrap-icons.min.css">
+<link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/news.css') }}">
+<link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/news-enhanced.css') }}">
+<style>
+ /* Override Bootstrap defaults to ensure dark theme */
+ body {
+ background-color: #121212 !important;
+ color: #f5f5f5 !important;
+ }
+ .main-content {
+ background-color: #121212 !important;
+ }
+</style>
+{% endblock %}
+
+{% block content %}
+<!-- Alert Container -->
+<div id="news-alert" class="settings-alert-container"></div>
+
+<div class="news-page-wrapper">
+ <!-- Main Content Container with Right Sidebar -->
+ <div class="news-container">
+ <!-- News Feed Section -->
+ <div class="news-feed">
+ <!-- Header with integrated search -->
+ <div class="feed-header-section">
+ <div class="feed-header">
+ <h1><i class="bi bi-newspaper"></i> Research News Feed</h1>
+ </div>
+
+ <!-- Search box below header -->
+ <div class="news-search-container">
+ <div class="news-search-box">
+ <i class="bi bi-search search-icon"></i>
+ <input type="text" id="news-search" class="form-control" placeholder="Search news topics, headlines, or keywords...">
+ <button id="search-btn" class="btn btn-primary">
+ Search
+ </button>
+ </div>
+ </div>
+
+ <!-- Quick actions row -->
+ <div class="quick-actions-row">
+ <button class="btn btn-warning" id="refresh-feed-btn">
+ <i class="bi bi-arrow-clockwise"></i> Refresh Feed
+ </button>
+ <button class="btn btn-outline-primary" id="create-subscription-btn">
+ <i class="bi bi-plus-circle"></i> Create Subscription
+ </button>
+ <a href="/news/subscriptions" class="btn btn-outline-secondary">
+ <i class="bi bi-bell"></i> Manage Subscriptions
+ </a>
+ <button class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#settingsModal">
+ <i class="bi bi-gear"></i> Settings
+ </button>
+ </div>
+ </div>
+
+ <!-- Priority Status Alert -->
+ <div id="priority-status" class="priority-alert" style="display: none;">
+ <i class="bi bi-info-circle"></i>
+ <span id="priority-message"></span>
+ </div>
+
+ <!-- Filters Bar -->
+ <div class="filters-bar">
+ <div class="filter-section">
+ <div class="subscriptions-horizontal">
+ <select id="subscription-filter" class="form-select">
+ <option value="">All News</option>
+ </select>
+ </div>
+
+ <div class="time-filter-group">
+ <button class="filter-btn active" data-time="today">Today</button>
+ <button class="filter-btn" data-time="week">This Week</button>
+ <button class="filter-btn" data-time="month">This Month</button>
+ </div>
+
+ <div class="impact-filter-group">
+ <label>Impact:</label>
+ <input type="range" class="impact-slider" min="0" max="10" value="0" id="impact-filter">
+ <span class="impact-value">0+</span>
+ </div>
+ </div>
+ </div>
+
+ <!-- News Cards Container -->
+ <div class="news-cards-container">
+ <div id="news-feed-content">
+ <!-- This is where news items will be displayed -->
+ </div>
+ </div>
+
+ <!-- Load More -->
+ <div class="load-more-section">
+ <button class="btn btn-outline-primary" id="load-more-btn">
+ <i class="bi bi-plus-circle"></i> Load More Stories
+ </button>
+ </div>
+ </div>
+
+ <!-- Right Sidebar - Recommendations -->
+ <div class="recommendations">
+ <!-- News Templates -->
+ <h3><i class="bi bi-table"></i> News Templates</h3>
+ <div class="news-templates">
+ <button class="template-btn" onclick="useNewsTemplate('breaking-news')">
+ <i class="bi bi-newspaper"></i>
+ <span>Breaking News Table</span>
+ </button>
+ <button class="template-btn" onclick="useNewsTemplate('market-analysis')">
+ <i class="bi bi-graph-up-arrow"></i>
+ <span>Market Analysis</span>
+ </button>
+ <button class="template-btn" onclick="useNewsTemplate('tech-updates')">
+ <i class="bi bi-cpu"></i>
+ <span>Tech Updates</span>
+ </button>
+ <button class="template-btn" onclick="useNewsTemplate('local-news')">
+ <i class="bi bi-geo-alt"></i>
+ <span>Local News</span>
+ </button>
+ <button class="template-btn" onclick="useNewsTemplate('topic-news')">
+ <i class="bi bi-bookmark-star"></i>
+ <span>Topic News</span>
+ </button>
+ <button class="template-btn" onclick="useNewsTemplate('custom')">
+ <i class="bi bi-pencil-square"></i>
+ <span>Custom Template</span>
+ </button>
+ </div>
+
+ <!-- Trending Topics -->
+ <h3 class="mt-4"><i class="bi bi-trending-up"></i> Trending Topics</h3>
+ <div id="trending-topics" class="topic-tags">
+ <!-- Will be populated with trending topics -->
+ </div>
+
+
+
+ <h3 class="mt-4"><i class="bi bi-clock-history"></i> Recent Searches</h3>
+ <div class="recent-searches" id="recent-searches">
+ <!-- Will be populated dynamically -->
+ </div>
+
+ <!-- Query Templates -->
+ <div id="query-templates" class="mt-4">
+ <!-- Will be populated with query templates -->
+ </div>
+ </div>
+ </div>
+</div>
+
+
+<!-- Settings Modal -->
+<div class="modal fade" id="settingsModal" tabindex="-1">
+ <div class="modal-dialog">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h5 class="modal-title"><i class="bi bi-gear"></i> News Feed Settings</h5>
+ <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
+ </div>
+ <div class="modal-body">
+ <form id="settings-form">
+ <div class="mb-3">
+ <label class="form-label">Update Frequency</label>
+ <select class="form-select" id="update-frequency">
+ <option value="15">Every 15 minutes</option>
+ <option value="30">Every 30 minutes</option>
+ <option value="60">Every hour</option>
+ <option value="180">Every 3 hours</option>
+ </select>
+ </div>
+
+ <div class="mb-3">
+ <label class="form-label">Default Time Range</label>
+ <select class="form-select" id="default-time-range">
+ <option value="today">Today</option>
+ <option value="week">This Week</option>
+ <option value="month">This Month</option>
+ </select>
+ </div>
+
+ <div class="mb-3">
+ <label class="form-label">Minimum Impact Score</label>
+ <input type="range" class="form-range" min="0" max="10" value="0" id="min-impact-score">
+ <span id="impact-score-value">0</span>
+ </div>
+
+ <div class="mb-3">
+ <div class="form-check">
+ <input class="form-check-input" type="checkbox" id="show-summaries" checked>
+ <label class="form-check-label" for="show-summaries">
+ Show article summaries
+ </label>
+ </div>
+ </div>
+
+ <div class="mb-3">
+ <div class="form-check">
+ <input class="form-check-input" type="checkbox" id="auto-refresh" checked>
+ <label class="form-check-label" for="auto-refresh">
+ Auto-refresh feed
+ </label>
+ </div>
+ </div>
+ </form>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
+ <button type="button" class="btn btn-primary" id="save-settings-btn">Save Settings</button>
+ </div>
+ </div>
+ </div>
+</div>
+
+<!-- Subscriptions Modal -->
+<div class="modal fade" id="subscriptionsModal" tabindex="-1">
+ <div class="modal-dialog modal-lg">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h5 class="modal-title">Manage News Subscriptions</h5>
+ <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
+ </div>
+ <div class="modal-body">
+ <!-- Subscription Stats -->
+ <div class="subscription-stats mb-3">
+ <div class="row text-center">
+ <div class="col-md-3">
+ <div class="stat-card">
+ <h3 id="total-subscriptions">0</h3>
+ <p>Total Subscriptions</p>
+ </div>
+ </div>
+ <div class="col-md-3">
+ <div class="stat-card">
+ <h3 id="active-subscriptions">0</h3>
+ <p>Active</p>
+ </div>
+ </div>
+ <div class="col-md-3">
+ <div class="stat-card">
+ <h3 id="total-folders">0</h3>
+ <p>Folders</p>
+ </div>
+ </div>
+ <div class="col-md-3">
+ <div class="stat-card">
+ <h3 id="next-refresh-time">--</h3>
+ <p>Next Update</p>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Folder Tabs -->
+ <ul class="nav nav-tabs mb-3" id="folderTabs" role="tablist">
+ <li class="nav-item" role="presentation">
+ <button class="nav-link active" data-folder="all" type="button">
+ All Subscriptions
+ </button>
+ </li>
+ <li class="nav-item" role="presentation">
+ <button class="nav-link" data-folder="Unfiled" type="button">
+ 📁 Unfiled
+ </button>
+ </li>
+ <!-- Dynamic folder tabs will be added here -->
+ <li class="nav-item ms-auto" role="presentation">
+ <button class="btn btn-sm btn-outline-primary" id="create-folder-btn">
+ <i class="bi bi-plus"></i> New Folder
+ </button>
+ </li>
+ </ul>
+
+ <!-- Subscriptions List -->
+ <div id="subscriptions-list" class="subscriptions-container">
+ <div class="text-center p-4">
+ <div class="spinner-border" role="status">
+ <span class="visually-hidden">Loading...</span>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
+ </div>
+ </div>
+ </div>
+</div>
+
+<!-- News Subscription Modal -->
+<div class="modal fade" id="newsSubscriptionModal" tabindex="-1">
+ <div class="modal-dialog">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h5 class="modal-title"><i class="bi bi-bell-fill"></i> Create News Subscription</h5>
+ <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
+ </div>
+ <form id="news-subscription-form" onsubmit="handleNewsSubscriptionSubmit(event)">
+ <div class="modal-body">
+ <div class="mb-3">
+ <label for="news-subscription-query" class="form-label">Search Query</label>
+ <textarea class="form-control" id="news-subscription-query" rows="3" required
+ placeholder="e.g., AI breakthroughs, climate news, tech updates..."></textarea>
+ <small class="text-muted">Enter keywords or topics you want to track</small>
+ </div>
+
+ <div class="mb-3">
+ <label for="news-subscription-name" class="form-label">Subscription Name</label>
+ <input type="text" class="form-control" id="news-subscription-name"
+ placeholder="Optional - defaults to query">
+ </div>
+
+ <div class="mb-3">
+ <label for="news-subscription-frequency" class="form-label">Update Frequency</label>
+ <select class="form-select" id="news-subscription-frequency">
+ <option value="1">Every hour</option>
+ <option value="2">Every 2 hours</option>
+ <option value="4" selected>Every 4 hours</option>
+ <option value="8">Every 8 hours</option>
+ <option value="24">Daily</option>
+ </select>
+ </div>
+
+ <div class="mb-3">
+ <label for="news-subscription-folder" class="form-label">Folder</label>
+ <select class="form-select" id="news-subscription-folder">
+ <option value="">Uncategorized</option>
+ </select>
+ </div>
+
+ <div class="form-check mb-3">
+ <input class="form-check-input" type="checkbox" id="news-subscription-active" checked>
+ <label class="form-check-label" for="news-subscription-active">
+ Active
+ </label>
+ </div>
+
+ <div class="form-check">
+ <input class="form-check-input" type="checkbox" id="news-subscription-run-now">
+ <label class="form-check-label" for="news-subscription-run-now">
+ Run search immediately
+ </label>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
+ <button type="button" class="btn btn-primary" id="run-template-btn">Run Once</button>
+ <button type="submit" class="btn btn-primary">Create Subscription</button>
+ </div>
+ </form>
+ </div>
+ </div>
+</div>
+
+<!-- Add marked.js for markdown rendering -->
+<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/4.0.2/marked.min.js"></script>
+
+<!-- Add UI services for markdown rendering -->
+<script src="{{ url_for('research.serve_static', path='js/services/ui.js') }}"></script>
+
+<!-- Add news page JavaScript -->
+<script src="{{ url_for('research.serve_static', path='js/pages/news.js') }}"></script>
+
+<!-- Add subscription manager -->
+<script src="{{ url_for('research.serve_static', path='js/components/subscription-manager.js') }}"></script>
+
+<!-- Add Bootstrap JavaScript -->
+<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
+
+<!-- Add design enhancements -->
+<script src="{{ url_for('research.serve_static', path='js/news-enhancements.js') }}"></script>
+{% endblock %}
diff --git a/src/local_deep_research/web/templates/pages/news_cleaned.html b/src/local_deep_research/web/templates/pages/news_cleaned.html
new file mode 100644
index 0000000000..91ab139cec
--- /dev/null
+++ b/src/local_deep_research/web/templates/pages/news_cleaned.html
@@ -0,0 +1,224 @@
+{% extends "base.html" %}
+
+{% block title %}LDR News - AI-Powered Research Feed{% endblock %}
+
+{% block extra_head %}
+<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
+<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.7.2/font/bootstrap-icons.min.css">
+<link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/news.css') }}">
+{% endblock %}
+
+{% block content %}
+<!-- Alert Container -->
+<div id="news-alert" class="settings-alert-container" style="display: none; position: fixed; top: 20px; right: 20px; z-index: 1000;"></div>
+
+<div class="news-page-wrapper">
+ <!-- Main Content Container with Right Sidebar -->
+ <div class="news-container">
+ <!-- News Feed Section -->
+ <div class="news-feed">
+ <!-- Header with integrated search -->
+ <div class="feed-header-section">
+ <div class="feed-header">
+ <h1><i class="bi bi-newspaper"></i> Research News Feed</h1>
+ <div class="news-search-box">
+ <input type="text" id="news-search" class="form-control" placeholder="Search news topics...">
+ <button id="search-btn" class="btn btn-primary">
+ <i class="bi bi-search"></i>
+ </button>
+ </div>
+ </div>
+
+ <!-- Quick actions row -->
+ <div class="quick-actions-row">
+ <button class="btn btn-warning" id="refresh-feed-btn">
+ <i class="bi bi-arrow-clockwise"></i> Refresh Feed
+ </button>
+ <button class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#subscriptionsModal">
+ <i class="bi bi-bell"></i> Manage Subscriptions
+ </button>
+ <button class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#settingsModal">
+ <i class="bi bi-gear"></i> Settings
+ </button>
+ </div>
+ </div>
+
+ <!-- Filters Bar -->
+ <div class="filters-bar">
+ <div class="filter-section">
+ <div class="subscriptions-horizontal">
+ <select id="subscription-filter" class="form-select">
+ <option value="">All Topics</option>
+ <option value="ai">AI & Technology</option>
+ <option value="science">Science</option>
+ <option value="business">Business</option>
+ <option value="health">Health</option>
+ <option value="climate">Climate</option>
+ </select>
+ </div>
+
+ <div class="time-filter-group">
+ <button class="filter-btn active" data-time="today">Today</button>
+ <button class="filter-btn" data-time="week">This Week</button>
+ <button class="filter-btn" data-time="month">This Month</button>
+ </div>
+
+ <div class="impact-filter-group">
+ <label>Impact:</label>
+ <input type="range" class="impact-slider" min="0" max="10" value="0" id="impact-filter">
+ <span class="impact-value">0+</span>
+ </div>
+ </div>
+ </div>
+
+ <!-- News Cards Container -->
+ <div class="news-cards-container" id="news-container">
+ <!-- Loading skeleton -->
+ <div class="loading-skeleton">
+ <div class="skeleton-card"></div>
+ <div class="skeleton-card"></div>
+ <div class="skeleton-card"></div>
+ </div>
+ </div>
+
+ <!-- Load More -->
+ <div class="load-more-section">
+ <button class="btn btn-outline-primary" id="load-more-btn">
+ <i class="bi bi-plus-circle"></i> Load More Stories
+ </button>
+ </div>
+ </div>
+
+ <!-- Right Sidebar - Recommendations -->
+ <div class="recommendations">
+ <h3><i class="bi bi-stars"></i> Recommended Topics</h3>
+ <div class="recommendation-list" id="recommendations-list">
+ <div class="recommendation-item">
+ <i class="bi bi-lightning-charge"></i>
+ <span>Quantum Computing Breakthroughs</span>
+ <button class="btn btn-sm btn-outline-primary">Follow</button>
+ </div>
+ <div class="recommendation-item">
+ <i class="bi bi-cpu"></i>
+ <span>AI Safety Research</span>
+ <button class="btn btn-sm btn-outline-primary">Follow</button>
+ </div>
+ <div class="recommendation-item">
+ <i class="bi bi-graph-up"></i>
+ <span>Tech Market Analysis</span>
+ <button class="btn btn-sm btn-outline-primary">Follow</button>
+ </div>
+ </div>
+
+ <h3 class="mt-4"><i class="bi bi-clock-history"></i> Recent Searches</h3>
+ <div class="recent-searches" id="recent-searches">
+ <!-- Will be populated dynamically -->
+ </div>
+ </div>
+ </div>
+</div>
+
+<!-- Subscriptions Modal -->
+<div class="modal fade" id="subscriptionsModal" tabindex="-1">
+ <div class="modal-dialog modal-lg">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h5 class="modal-title"><i class="bi bi-bell"></i> Manage Subscriptions</h5>
+ <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
+ </div>
+ <div class="modal-body">
+ <div class="subscription-section">
+ <h6>Your Subscriptions</h6>
+ <div id="current-subscriptions" class="subscriptions-list">
+ <!-- Will be populated dynamically -->
+ </div>
+
+ <h6 class="mt-4">Add New Subscription</h6>
+ <form id="add-subscription-form">
+ <div class="input-group">
+ <input type="text" class="form-control" placeholder="Enter topic or search query" id="new-subscription-input">
+ <button class="btn btn-primary" type="submit">
+ <i class="bi bi-plus"></i> Subscribe
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ </div>
+ </div>
+</div>
+
+<!-- Settings Modal -->
+<div class="modal fade" id="settingsModal" tabindex="-1">
+ <div class="modal-dialog">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h5 class="modal-title"><i class="bi bi-gear"></i> News Feed Settings</h5>
+ <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
+ </div>
+ <div class="modal-body">
+ <form id="settings-form">
+ <div class="mb-3">
+ <label class="form-label">Update Frequency</label>
+ <select class="form-select" id="update-frequency">
+ <option value="15">Every 15 minutes</option>
+ <option value="30">Every 30 minutes</option>
+ <option value="60">Every hour</option>
+ <option value="180">Every 3 hours</option>
+ </select>
+ </div>
+
+ <div class="mb-3">
+ <label class="form-label">Default Time Range</label>
+ <select class="form-select" id="default-time-range">
+ <option value="today">Today</option>
+ <option value="week">This Week</option>
+ <option value="month">This Month</option>
+ </select>
+ </div>
+
+ <div class="mb-3">
+ <label class="form-label">Minimum Impact Score</label>
+ <input type="range" class="form-range" min="0" max="10" value="0" id="min-impact-score">
+ <span id="impact-score-value">0</span>
+ </div>
+
+ <div class="mb-3">
+ <div class="form-check">
+ <input class="form-check-input" type="checkbox" id="show-summaries" checked>
+ <label class="form-check-label" for="show-summaries">
+ Show article summaries
+ </label>
+ </div>
+ </div>
+
+ <div class="mb-3">
+ <div class="form-check">
+ <input class="form-check-input" type="checkbox" id="auto-refresh" checked>
+ <label class="form-check-label" for="auto-refresh">
+ Auto-refresh feed
+ </label>
+ </div>
+ </div>
+ </form>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
+ <button type="button" class="btn btn-primary" id="save-settings-btn">Save Settings</button>
+ </div>
+ </div>
+ </div>
+</div>
+
+<!-- Add marked.js for markdown rendering -->
+<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/4.0.2/marked.min.js"></script>
+
+<!-- Add UI services for markdown rendering -->
+<script src="{{ url_for('research.serve_static', path='js/services/ui.js') }}"></script>
+
+<!-- Add news page JavaScript -->
+<script src="{{ url_for('research.serve_static', path='js/pages/news.js') }}"></script>
+
+<!-- Add Bootstrap JavaScript -->
+<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
+{% endblock %}
diff --git a/src/local_deep_research/web/templates/pages/subscriptions.html b/src/local_deep_research/web/templates/pages/subscriptions.html
new file mode 100644
index 0000000000..e62eb2a89b
--- /dev/null
+++ b/src/local_deep_research/web/templates/pages/subscriptions.html
@@ -0,0 +1,294 @@
+{% extends "base.html" %}
+{% set active_page = 'subscriptions' %}
+
+{% block title %}Manage News Subscriptions - LDR{% endblock %}
+
+{% block extra_head %}
+<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
+<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.7.2/font/bootstrap-icons.min.css">
+<link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/subscriptions.css') }}">
+<style>
+ /* Override Bootstrap defaults to ensure dark theme */
+ body {
+ background-color: #121212 !important;
+ color: #f5f5f5 !important;
+ }
+ .main-content {
+ background-color: #121212 !important;
+ }
+ .modal-content {
+ background-color: #1e1e2d !important;
+ color: #f5f5f5 !important;
+ }
+ .form-control, .form-select {
+ background-color: #2a2a3a !important;
+ border-color: #343452 !important;
+ color: #f5f5f5 !important;
+ }
+ .form-control:focus, .form-select:focus {
+ background-color: #2a2a3a !important;
+ border-color: #6e4ff6 !important;
+ color: #f5f5f5 !important;
+ box-shadow: 0 0 0 0.2rem rgba(110, 79, 246, 0.25) !important;
+ }
+ .btn-secondary {
+ background-color: #2a2a3a !important;
+ border-color: #343452 !important;
+ }
+ .btn-secondary:hover {
+ background-color: #343452 !important;
+ border-color: #343452 !important;
+ }
+ .alert {
+ background-color: #2a2a3a !important;
+ border-color: #343452 !important;
+ color: #f5f5f5 !important;
+ }
+</style>
+{% endblock %}
+
+{% block content %}
+<div class="subscriptions-page">
+ <!-- Header Section -->
+ <div class="page-header">
+ <div class="header-content">
+ <h1><i class="bi bi-bell"></i> News Subscriptions</h1>
+ <p class="subtitle">Manage your news topics and scheduled searches</p>
+ </div>
+ <div class="header-actions">
+ <a href="/news" class="btn btn-outline-secondary">
+ <i class="bi bi-arrow-left"></i> Back to News Feed
+ </a>
+ <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addSubscriptionModal">
+ <i class="bi bi-plus-circle"></i> New Subscription
+ </button>
+ </div>
+ </div>
+
+ <!-- Stats Overview -->
+ <div class="stats-overview">
+ <div class="stat-card">
+ <div class="stat-value" id="total-subscriptions">0</div>
+ <div class="stat-label">Total Subscriptions</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-value" id="active-subscriptions">0</div>
+ <div class="stat-label">Active</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-value" id="paused-subscriptions">0</div>
+ <div class="stat-label">Paused</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-value" id="updates-today">0</div>
+ <div class="stat-label">Updates Today</div>
+ </div>
+ </div>
+
+ <!-- Scheduler Status Bar -->
+ <div class="scheduler-status-bar">
+ <div class="scheduler-info">
+ <i class="bi bi-clock-history"></i>
+ <span class="scheduler-label">Auto-Refresh Scheduler:</span>
+ <span id="scheduler-status" class="scheduler-status">
+ <span class="status-indicator" id="status-indicator"></span>
+ <span id="status-text">Checking...</span>
+ </span>
+ <span class="scheduler-details" id="scheduler-details"></span>
+ </div>
+ <div class="scheduler-actions">
+ <button class="btn btn-sm btn-outline-secondary" id="toggle-scheduler" style="display: none;">
+ <i class="bi bi-play-fill"></i> Start Scheduler
+ </button>
+ <button class="btn btn-sm btn-outline-info" id="check-now" title="Check all subscriptions now">
+ <i class="bi bi-arrow-clockwise"></i> Check All Now
+ </button>
+ </div>
+ </div>
+
+ <!-- Subscriptions List -->
+ <div class="subscriptions-container">
+ <!-- Folder/Category Sidebar -->
+ <div class="folders-sidebar">
+ <h3>Folders</h3>
+ <div class="folder-list">
+ <div class="folder-item active" data-folder="all">
+ <i class="bi bi-collection"></i> All Subscriptions
+ <span class="folder-count">0</span>
+ </div>
+ <div class="folder-item" data-folder="uncategorized">
+ <i class="bi bi-folder"></i> Uncategorized
+ <span class="folder-count">0</span>
+ </div>
+ <!-- Dynamic folders will be added here -->
+ </div>
+ <button class="btn btn-sm btn-outline-secondary mt-3" id="add-folder-btn">
+ <i class="bi bi-plus"></i> New Folder
+ </button>
+ </div>
+
+ <!-- Main Content Area -->
+ <div class="subscriptions-main">
+ <!-- Search and Filter Bar -->
+ <div class="filter-bar">
+ <div class="search-box">
+ <i class="bi bi-search"></i>
+ <input type="text" id="subscription-search" placeholder="Search subscriptions...">
+ </div>
+ <div class="filter-options">
+ <select id="status-filter" class="form-select form-select-sm">
+ <option value="all">All Status</option>
+ <option value="active">Active</option>
+ <option value="paused">Paused</option>
+ </select>
+ <select id="frequency-filter" class="form-select form-select-sm">
+ <option value="all">All Frequencies</option>
+ <option value="hourly">Hourly</option>
+ <option value="daily">Daily</option>
+ <option value="weekly">Weekly</option>
+ </select>
+ </div>
+ </div>
+
+ <!-- Subscriptions Grid -->
+ <div id="subscriptions-grid" class="subscriptions-grid">
+ <!-- Subscription cards will be dynamically loaded here -->
+ <div class="loading-placeholder">
+ <div class="spinner-border text-primary" role="status">
+ <span class="visually-hidden">Loading...</span>
+ </div>
+ <p>Loading subscriptions...</p>
+ </div>
+ </div>
+ </div>
+ </div>
+</div>
+
+<!-- Add Subscription Modal -->
+<div class="modal fade" id="addSubscriptionModal" tabindex="-1">
+ <div class="modal-dialog">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h5 class="modal-title">Create New Subscription</h5>
+ <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
+ </div>
+ <form id="new-subscription-form">
+ <div class="modal-body">
+ <div class="mb-3">
+ <label for="subscription-query" class="form-label">Topic or Search Query</label>
+ <input type="text" class="form-control" id="subscription-query"
+ placeholder="e.g., artificial intelligence, climate change, tech news" required>
+ <div class="form-text">Enter keywords, topics, or search queries you want to track</div>
+ </div>
+
+ <div class="mb-3">
+ <label for="subscription-name" class="form-label">Subscription Name (Optional)</label>
+ <input type="text" class="form-control" id="subscription-name"
+ placeholder="e.g., AI Research Updates">
+ </div>
+
+ <div class="row">
+ <div class="col-md-6 mb-3">
+ <label for="subscription-frequency" class="form-label">Update Frequency</label>
+ <select class="form-select" id="subscription-frequency">
+ <option value="hourly">Every Hour</option>
+ <option value="daily" selected>Daily</option>
+ <option value="weekly">Weekly</option>
+ </select>
+ </div>
+
+ <div class="col-md-6 mb-3">
+ <label for="subscription-folder" class="form-label">Folder</label>
+ <select class="form-select" id="subscription-folder">
+ <option value="">Uncategorized</option>
+ <!-- Dynamic folders will be added here -->
+ </select>
+ </div>
+ </div>
+
+ <div class="mb-3">
+ <div class="form-check">
+ <input class="form-check-input" type="checkbox" id="subscription-active" checked>
+ <label class="form-check-label" for="subscription-active">
+ Start active (begin collecting news immediately)
+ </label>
+ </div>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
+ <button type="submit" class="btn btn-primary">Create Subscription</button>
+ </div>
+ </form>
+ </div>
+ </div>
+</div>
+
+<!-- Edit Subscription Modal -->
+<div class="modal fade" id="editSubscriptionModal" tabindex="-1">
+ <div class="modal-dialog">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h5 class="modal-title">Edit Subscription</h5>
+ <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
+ </div>
+ <form id="edit-subscription-form">
+ <input type="hidden" id="edit-subscription-id">
+ <div class="modal-body">
+ <div class="mb-3">
+ <label for="edit-subscription-query" class="form-label">Topic or Search Query</label>
+ <input type="text" class="form-control" id="edit-subscription-query"
+ placeholder="e.g., artificial intelligence, climate change, tech news" required>
+ <div class="form-text">Enter keywords, topics, or search queries you want to track</div>
+ </div>
+
+ <div class="mb-3">
+ <label for="edit-subscription-name" class="form-label">Subscription Name (Optional)</label>
+ <input type="text" class="form-control" id="edit-subscription-name"
+ placeholder="e.g., AI Research Updates">
+ </div>
+
+ <div class="row">
+ <div class="col-md-6 mb-3">
+ <label for="edit-subscription-frequency" class="form-label">Update Frequency</label>
+ <select class="form-select" id="edit-subscription-frequency">
+ <option value="hourly">Every Hour</option>
+ <option value="daily">Daily</option>
+ <option value="weekly">Weekly</option>
+ </select>
+ </div>
+
+ <div class="col-md-6 mb-3">
+ <label for="edit-subscription-folder" class="form-label">Folder</label>
+ <select class="form-select" id="edit-subscription-folder">
+ <option value="">Uncategorized</option>
+ <!-- Dynamic folders will be added here -->
+ </select>
+ </div>
+ </div>
+
+ <div class="mb-3">
+ <div class="form-check">
+ <input class="form-check-input" type="checkbox" id="edit-subscription-active">
+ <label class="form-check-label" for="edit-subscription-active">
+ Active (collecting news)
+ </label>
+ </div>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-danger" id="delete-subscription-btn">Delete</button>
+ <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
+ <button type="submit" class="btn btn-primary">Save Changes</button>
+ </div>
+ </form>
+ </div>
+ </div>
+</div>
+
+{% endblock %}
+
+{% block page_scripts %}
+<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
+<script src="{{ url_for('research.serve_static', path='js/pages/subscriptions.js') }}"></script>
+{% endblock %}
diff --git a/src/run_migration.py b/src/run_migration.py
new file mode 100644
index 0000000000..57f0385bd3
--- /dev/null
+++ b/src/run_migration.py
@@ -0,0 +1,27 @@
+#!/usr/bin/env python3
+"""Quick script to run the subscription folders migration"""
+
+from local_deep_research.news.database import get_news_database
+from local_deep_research.news.migrations import (
+ apply_subscription_folders_migration,
+)
+from loguru import logger
+
+if __name__ == "__main__":
+ logger.info("Running subscription folders migration...")
+
+ db = get_news_database()
+ db.initialize()
+
+ # Run migration
+ apply_subscription_folders_migration(db.engine)
+
+ logger.info("Migration completed!")
+
+ # Check the columns
+ from sqlalchemy import text
+
+ with db.engine.connect() as conn:
+ result = conn.execute(text("PRAGMA table_info(news_subscriptions)"))
+ columns = [row[1] for row in result]
+ logger.info(f"Current columns in news_subscriptions: {columns}")
diff --git a/tests/ldr-news-dev-files/redundant-tests/test_news_api_debug.js b/tests/ldr-news-dev-files/redundant-tests/test_news_api_debug.js
new file mode 100644
index 0000000000..ac894d3f2c
--- /dev/null
+++ b/tests/ldr-news-dev-files/redundant-tests/test_news_api_debug.js
@@ -0,0 +1,211 @@
+/**
+ * Debug news API and feed issues
+ */
+
+const puppeteer = require('puppeteer');
+
+async function debugNewsAPI() {
+ console.log('🔍 Debugging News API\n');
+
+ const browser = await puppeteer.launch({
+ headless: false,
+ args: ['--no-sandbox', '--disable-setuid-sandbox', '--window-size=1400,900'],
+ defaultViewport: { width: 1400, height: 900 }
+ });
+
+ const page = await browser.newPage();
+
+ try {
+ console.log('📍 Loading news page...');
+ await page.goto('http://localhost:5000/news/', { waitUntil: 'networkidle2' });
+ await new Promise(r => setTimeout(r, 2000));
+
+ // Test 1: Check news feed endpoint
+ console.log('\n1️⃣ Testing /news/api/feed endpoint');
+ const feedTest = await page.evaluate(async () => {
+ const response = await fetch('/news/api/feed?user_id=test&limit=10');
+ const data = await response.json();
+ return {
+ status: response.status,
+ ok: response.ok,
+ data: data
+ };
+ });
+
+ console.log('Feed response:', JSON.stringify(feedTest, null, 2));
+
+ // Test 2: Check Flask API response structure
+ console.log('\n2️⃣ Checking Flask API wrapper');
+ const flaskCheck = await page.evaluate(async () => {
+ const response = await fetch('/news/api/feed?user_id=test&limit=5&use_cache=false');
+ const text = await response.text();
+ try {
+ const json = JSON.parse(text);
+ return { type: 'json', data: json };
+ } catch {
+ return { type: 'text', data: text.substring(0, 200) };
+ }
+ });
+
+ console.log('Flask response:', JSON.stringify(flaskCheck, null, 2));
+
+ // Test 3: Create a subscription to trigger news generation
+ console.log('\n3️⃣ Creating subscription to trigger news generation');
+ const subResponse = await page.evaluate(async () => {
+ const response = await fetch('/news/api/subscribe', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ user_id: 'test',
+ query: 'AI technology news',
+ subscription_type: 'search',
+ refresh_hours: 1
+ })
+ });
+
+ return {
+ status: response.status,
+ ok: response.ok,
+ data: await response.json()
+ };
+ });
+
+ console.log('Subscription response:', JSON.stringify(subResponse, null, 2));
+
+ // Wait for subscription to process
+ await new Promise(r => setTimeout(r, 3000));
+
+ // Test 4: Check feed again after subscription
+ console.log('\n4️⃣ Checking feed after subscription');
+ const feedAfterSub = await page.evaluate(async () => {
+ const response = await fetch('/news/api/feed?user_id=test&limit=10');
+ const data = await response.json();
+ return {
+ cardCount: data.cards?.length || 0,
+ newsItemsCount: data.news_items?.length || 0,
+ hasError: !!data.error,
+ keys: Object.keys(data)
+ };
+ });
+
+ console.log('Feed after subscription:', feedAfterSub);
+
+ // Test 5: Try direct research endpoint
+ console.log('\n5️⃣ Triggering news research directly');
+ const researchResponse = await page.evaluate(async () => {
+ const response = await fetch('/api/start_research', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ query: 'Latest breaking news in technology',
+ mode: 'quick',
+ metadata: {
+ is_news_search: true,
+ source: 'news_feed_test'
+ }
+ })
+ });
+
+ return {
+ status: response.status,
+ ok: response.ok,
+ data: await response.json()
+ };
+ });
+
+ console.log('Research response:', JSON.stringify(researchResponse, null, 2));
+
+ // Test 6: Check loadNewsFeed function
+ console.log('\n6️⃣ Testing loadNewsFeed JavaScript function');
+ const loadFeedTest = await page.evaluate(async () => {
+ if (typeof loadNewsFeed !== 'function') {
+ return { error: 'loadNewsFeed function not found' };
+ }
+
+ try {
+ // Override renderNewsFeed to capture data
+ const originalRender = window.renderNewsFeed;
+ let capturedData = null;
+
+ window.renderNewsFeed = function(feed) {
+ capturedData = feed;
+ if (originalRender) originalRender(feed);
+ };
+
+ await loadNewsFeed();
+
+ // Restore original
+ window.renderNewsFeed = originalRender;
+
+ return {
+ success: true,
+ capturedData: capturedData,
+ cardsAfterLoad: document.querySelectorAll('.news-card').length
+ };
+ } catch (error) {
+ return {
+ success: false,
+ error: error.message
+ };
+ }
+ });
+
+ console.log('LoadNewsFeed test:', JSON.stringify(loadFeedTest, null, 2));
+
+ // Test 7: Check if we need to initialize news data
+ console.log('\n7️⃣ Checking news system initialization');
+ const initCheck = await page.evaluate(async () => {
+ // Check localStorage for news data
+ const savedNews = localStorage.getItem('news_feed_cache');
+ const lastUpdate = localStorage.getItem('news_last_update');
+
+ return {
+ hasCachedNews: !!savedNews,
+ lastUpdate: lastUpdate,
+ subscriptionCount: document.querySelectorAll('.subscription-item').length
+ };
+ });
+
+ console.log('Initialization check:', initCheck);
+
+ // ANALYSIS
+ console.log('\n' + '='.repeat(60));
+ console.log('📊 ANALYSIS');
+ console.log('='.repeat(60));
+
+ if (feedTest.data && feedTest.data.cards && feedTest.data.cards.length === 0) {
+ console.log('\n❌ ISSUE: API returns empty cards array');
+ console.log(' The news system may not have any data yet');
+ console.log(' Need to trigger news generation through subscriptions or searches');
+ }
+
+ if (feedTest.data && feedTest.data.news_items && feedTest.data.news_items.length === 0) {
+ console.log('\n❌ ISSUE: API returns empty news_items array');
+ console.log(' The recommender may not be finding any content');
+ }
+
+ if (flaskCheck.data && flaskCheck.data.error) {
+ console.log('\n❌ ISSUE: API returns error:', flaskCheck.data.error);
+ }
+
+ console.log('\n💡 SOLUTION:');
+ console.log(' 1. Create subscriptions to trigger news collection');
+ console.log(' 2. Use the search feature to generate news content');
+ console.log(' 3. The system needs to populate data before showing in feed');
+
+ console.log('\n✨ Debug complete! Browser will close in 15 seconds...');
+ await new Promise(r => setTimeout(r, 15000));
+
+ } catch (error) {
+ console.error('❌ Test error:', error.message);
+ } finally {
+ await browser.close();
+ }
+}
+
+// Run test
+debugNewsAPI().catch(console.error);
diff --git a/tests/ldr-news-dev-files/redundant-tests/test_news_basic_functionality.js b/tests/ldr-news-dev-files/redundant-tests/test_news_basic_functionality.js
new file mode 100644
index 0000000000..68edb4540b
--- /dev/null
+++ b/tests/ldr-news-dev-files/redundant-tests/test_news_basic_functionality.js
@@ -0,0 +1,167 @@
+const puppeteer = require('puppeteer');
+
+const BASE_URL = 'http://localhost:5000';
+const TIMEOUT = 10000;
+
+async function runBasicNewsTests() {
+ console.log('🚀 Starting LDR News Basic Functionality Tests\n');
+
+ const browser = await puppeteer.launch({
+ headless: 'new',
+ args: ['--no-sandbox', '--disable-setuid-sandbox']
+ });
+
+ let passed = 0;
+ let failed = 0;
+
+ try {
+ const page = await browser.newPage();
+ await page.setViewport({ width: 1280, height: 800 });
+
+ // Capture console messages
+ page.on('console', msg => {
+ if (msg.type() === 'error') {
+ console.log('🔴 Console error:', msg.text());
+ }
+ });
+
+ console.log('📰 Test 1: Load News Page');
+ try {
+ await page.goto(`${BASE_URL}/news/`, { waitUntil: 'networkidle2' });
+ const title = await page.title();
+ console.log(`✅ Page loaded - Title: ${title}`);
+ passed++;
+ } catch (e) {
+ console.log(`❌ Failed to load page: ${e.message}`);
+ failed++;
+ return;
+ }
+
+ console.log('\n📰 Test 2: Check News Feed Structure');
+ try {
+ // Check for news container or cards
+ const hasNewsDisplay = await page.evaluate(() => {
+ return document.querySelector('.news-card') !== null ||
+ document.querySelector('#news-feed') !== null ||
+ document.querySelector('.card') !== null;
+ });
+
+ if (hasNewsDisplay) {
+ console.log('✅ News display elements found');
+ passed++;
+
+ // Count cards
+ const cardCount = await page.$$eval('.card, .news-card', cards => cards.length);
+ console.log(` Found ${cardCount} news cards`);
+ } else {
+ console.log('❌ No news display elements found');
+ failed++;
+ }
+ } catch (e) {
+ console.log(`❌ Error checking news structure: ${e.message}`);
+ failed++;
+ }
+
+ console.log('\n📰 Test 3: Check Modal Functionality');
+ try {
+ // Check if Bootstrap is loaded
+ const hasBootstrap = await page.evaluate(() => {
+ return typeof window.bootstrap !== 'undefined';
+ });
+ console.log(` Bootstrap loaded: ${hasBootstrap}`);
+
+ // Check for modal element
+ const hasModal = await page.$('#newsModal') !== null;
+ if (hasModal) {
+ console.log('✅ Modal element found');
+ passed++;
+ } else {
+ console.log('❌ Modal element not found');
+ failed++;
+ }
+ } catch (e) {
+ console.log(`❌ Error checking modal: ${e.message}`);
+ failed++;
+ }
+
+ console.log('\n📰 Test 4: Check API Connectivity');
+ try {
+ // Make API call
+ const response = await page.evaluate(async () => {
+ try {
+ const res = await fetch('/news/api/feed?user_id=test_user&limit=5');
+ return {
+ status: res.status,
+ ok: res.ok,
+ data: await res.json()
+ };
+ } catch (e) {
+ return { error: e.message };
+ }
+ });
+
+ if (response.ok) {
+ console.log('✅ API responded successfully');
+ console.log(` Status: ${response.status}`);
+ console.log(` News items: ${response.data.news_items?.length || 0}`);
+ passed++;
+ } else {
+ console.log(`❌ API error - Status: ${response.status}`);
+ failed++;
+ }
+ } catch (e) {
+ console.log(`❌ Error testing API: ${e.message}`);
+ failed++;
+ }
+
+ console.log('\n📰 Test 5: Check Vote Buttons');
+ try {
+ const voteButtons = await page.$$('.vote-button, .btn-upvote, .btn-downvote, [onclick*="vote"]');
+ if (voteButtons.length > 0) {
+ console.log(`✅ Found ${voteButtons.length} vote buttons`);
+ passed++;
+
+ // Try clicking first vote button
+ const firstButton = voteButtons[0];
+ await firstButton.click();
+ await new Promise(resolve => setTimeout(resolve, 1000));
+ console.log(' Clicked vote button');
+ } else {
+ console.log('⚠️ No vote buttons found');
+ }
+ } catch (e) {
+ console.log(`❌ Error with vote buttons: ${e.message}`);
+ failed++;
+ }
+
+ console.log('\n📰 Test 6: Check for JavaScript Errors');
+ const jsErrors = [];
+ page.on('pageerror', error => jsErrors.push(error.message));
+
+ // Reload to catch errors
+ await page.reload({ waitUntil: 'networkidle2' });
+ await new Promise(resolve => setTimeout(resolve, 2000));
+
+ if (jsErrors.length === 0) {
+ console.log('✅ No JavaScript errors');
+ passed++;
+ } else {
+ console.log(`❌ Found ${jsErrors.length} JavaScript errors`);
+ jsErrors.forEach(err => console.log(` - ${err}`));
+ failed++;
+ }
+
+ console.log('\n' + '─'.repeat(50));
+ console.log(`✅ Passed: ${passed}`);
+ console.log(`❌ Failed: ${failed}`);
+ console.log(`📊 Success rate: ${((passed / (passed + failed)) * 100).toFixed(1)}%`);
+
+ } catch (error) {
+ console.error('\n❌ Fatal error:', error.message);
+ } finally {
+ await browser.close();
+ }
+}
+
+// Run tests
+runBasicNewsTests().catch(console.error);
diff --git a/tests/ldr-news-dev-files/redundant-tests/test_news_clean_content.js b/tests/ldr-news-dev-files/redundant-tests/test_news_clean_content.js
new file mode 100644
index 0000000000..67c42eb105
--- /dev/null
+++ b/tests/ldr-news-dev-files/redundant-tests/test_news_clean_content.js
@@ -0,0 +1,65 @@
+const puppeteer = require('puppeteer');
+const fs = require('fs').promises;
+
+async function testNewsCleanContent() {
+ const browser = await puppeteer.launch({
+ headless: 'new',
+ args: ['--no-sandbox', '--disable-setuid-sandbox']
+ });
+
+ try {
+ const page = await browser.newPage();
+ await page.setViewport({ width: 1280, height: 800 });
+
+ // Disable cache
+ await page.setCacheEnabled(false);
+
+ console.log('Loading news page to check clean content...');
+ await page.goto('http://127.0.0.1:5000/news', {
+ waitUntil: 'networkidle2',
+ headers: {
+ 'Cache-Control': 'no-cache'
+ }
+ });
+
+ // Wait for news items
+ await page.waitForSelector('.news-item', { timeout: 10000 });
+
+ // Check content of first news item
+ const firstItemContent = await page.evaluate(() => {
+ const firstItem = document.querySelector('.news-item');
+ if (!firstItem) return null;
+
+ const headline = firstItem.querySelector('.news-headline')?.textContent;
+ const findings = firstItem.querySelector('.news-findings')?.textContent;
+ const summary = firstItem.querySelector('.news-summary')?.textContent;
+
+ return {
+ headline: headline?.trim(),
+ findingsStart: findings?.substring(0, 150).trim(),
+ summaryStart: summary?.substring(0, 150).trim(),
+ hasQuery: findings?.toLowerCase().includes('query:') || summary?.toLowerCase().includes('query:')
+ };
+ });
+
+ console.log('\nFirst news item content:');
+ console.log('Headline:', firstItemContent?.headline);
+ console.log('\nFindings start:', firstItemContent?.findingsStart);
+ console.log('\nContains "Query:"?', firstItemContent?.hasQuery ? '❌ YES (needs fixing)' : '✅ NO (good!)');
+
+ // Take screenshot
+ await fs.mkdir('screenshots', { recursive: true });
+ await page.screenshot({
+ path: 'screenshots/news_clean_content.png',
+ fullPage: true
+ });
+ console.log('\nScreenshot saved to screenshots/news_clean_content.png');
+
+ } catch (error) {
+ console.error('Test failed:', error);
+ } finally {
+ await browser.close();
+ }
+}
+
+testNewsCleanContent();
diff --git a/tests/ldr-news-dev-files/redundant-tests/test_news_enhanced.js b/tests/ldr-news-dev-files/redundant-tests/test_news_enhanced.js
new file mode 100644
index 0000000000..167c4e1e6e
--- /dev/null
+++ b/tests/ldr-news-dev-files/redundant-tests/test_news_enhanced.js
@@ -0,0 +1,114 @@
+const puppeteer = require('puppeteer');
+
+async function testEnhancedNews() {
+ console.log('🔍 Testing Enhanced News Features\n');
+
+ const browser = await puppeteer.launch({
+ headless: 'new',
+ args: ['--no-sandbox', '--disable-setuid-sandbox']
+ });
+
+ try {
+ const page = await browser.newPage();
+ await page.setViewport({ width: 1280, height: 800 });
+
+ console.log('📰 Loading news page...');
+ await page.goto('http://localhost:5000/news/', { waitUntil: 'networkidle2' });
+
+ // Wait for news items to load
+ await page.waitForSelector('.news-item', { timeout: 10000 });
+ await new Promise(resolve => setTimeout(resolve, 2000));
+
+ // Check enhanced features
+ const features = await page.evaluate(() => {
+ const firstItem = document.querySelector('.news-item');
+ if (!firstItem) return { error: 'No news items found' };
+
+ return {
+ // Check headline
+ headline: firstItem.querySelector('.news-headline')?.textContent || 'No headline',
+
+ // Check findings preview
+ hasFindings: !!firstItem.querySelector('.news-findings'),
+ findingsLength: firstItem.querySelector('.news-findings')?.textContent.length || 0,
+
+ // Check topics
+ topics: Array.from(firstItem.querySelectorAll('.topic-tag')).map(tag => tag.textContent),
+ topicCount: firstItem.querySelectorAll('.topic-tag').length,
+
+ // Check View Full Report button
+ hasViewButton: !!firstItem.querySelector('a[href*="/results/"]'),
+ viewButtonText: firstItem.querySelector('a[href*="/results/"]')?.textContent || 'No button',
+ viewButtonHref: firstItem.querySelector('a[href*="/results/"]')?.href || 'No href',
+
+ // Check card height
+ cardHeight: firstItem.offsetHeight,
+
+ // Check if card has proper structure
+ hasVoteButtons: firstItem.querySelectorAll('.vote-btn').length === 2,
+ hasActionButtons: !!firstItem.querySelector('.action-buttons')
+ };
+ });
+
+ console.log('\n📊 Enhanced Features Check:');
+ console.log(`✅ Headline: "${features.headline}"`);
+ console.log(`✅ Has findings preview: ${features.hasFindings}`);
+ console.log(`✅ Findings preview length: ${features.findingsLength} chars`);
+ console.log(`✅ Topics found: ${features.topicCount}`);
+ if (features.topics.length > 0) {
+ console.log(` Topics: ${features.topics.join(', ')}`);
+ }
+ console.log(`✅ View Full Report button: ${features.hasViewButton}`);
+ console.log(` Button text: "${features.viewButtonText}"`);
+ console.log(` Links to: ${features.viewButtonHref}`);
+ console.log(`✅ Card height: ${features.cardHeight}px (min should be 350px)`);
+ console.log(`✅ Has vote buttons: ${features.hasVoteButtons}`);
+ console.log(`✅ Has action buttons: ${features.hasActionButtons}`);
+
+ // Test topic click
+ console.log('\n🔘 Testing topic click...');
+ if (features.topicCount > 0) {
+ await page.click('.topic-tag');
+ await new Promise(resolve => setTimeout(resolve, 1000));
+
+ // Check if alert showed
+ const alertVisible = await page.evaluate(() => {
+ const alert = document.getElementById('news-alert');
+ return alert && alert.style.display !== 'none';
+ });
+ console.log(`✅ Topic click alert shown: ${alertVisible}`);
+ }
+
+ // Take screenshot
+ await page.screenshot({
+ path: 'tests/ui_tests/screenshots/news_enhanced.png',
+ fullPage: true
+ });
+ console.log('\n📸 Screenshot saved to: tests/ui_tests/screenshots/news_enhanced.png');
+
+ // Test API response for enhanced data
+ console.log('\n🔌 Testing API for enhanced data...');
+ const apiResponse = await page.evaluate(async () => {
+ const response = await fetch('/news/api/feed?user_id=test&limit=1');
+ const data = await response.json();
+ return data.news_items?.[0] || null;
+ });
+
+ if (apiResponse) {
+ console.log('\nAPI Response sample:');
+ console.log(`- Headline: "${apiResponse.headline}"`);
+ console.log(`- Original query length: ${apiResponse.original_query?.length || 0}`);
+ console.log(`- Topics: ${apiResponse.topics?.join(', ') || 'None'}`);
+ console.log(`- Has findings: ${!!apiResponse.findings}`);
+ }
+
+ console.log('\n✅ Enhanced news features test completed!');
+
+ } catch (error) {
+ console.error('❌ Test failed:', error.message);
+ } finally {
+ await browser.close();
+ }
+}
+
+testEnhancedNews().catch(console.error);
diff --git a/tests/ldr-news-dev-files/redundant-tests/test_news_error_debug.js b/tests/ldr-news-dev-files/redundant-tests/test_news_error_debug.js
new file mode 100644
index 0000000000..1def38da05
--- /dev/null
+++ b/tests/ldr-news-dev-files/redundant-tests/test_news_error_debug.js
@@ -0,0 +1,97 @@
+const puppeteer = require('puppeteer');
+
+async function debugNewsError() {
+ console.log('🔍 Debugging News JavaScript Error\n');
+
+ const browser = await puppeteer.launch({
+ headless: 'new',
+ args: ['--no-sandbox', '--disable-setuid-sandbox']
+ });
+
+ try {
+ const page = await browser.newPage();
+
+ // Capture console errors with more detail
+ page.on('console', msg => {
+ const type = msg.type();
+ if (type === 'error') {
+ console.log(`[JS ERROR]: ${msg.text()}`);
+ msg.args().forEach(async (arg, i) => {
+ const val = await arg.jsonValue().catch(() => 'Complex object');
+ console.log(` Arg ${i}:`, val);
+ });
+ }
+ });
+
+ page.on('pageerror', error => {
+ console.log('[Page Error]:', error.message);
+ console.log('[Stack]:', error.stack);
+ });
+
+ await page.setViewport({ width: 1280, height: 800 });
+
+ console.log('📰 Loading news page...');
+ await page.goto('http://localhost:5000/news/', {
+ waitUntil: 'networkidle2',
+ timeout: 30000
+ });
+
+ // Wait a bit
+ await new Promise(resolve => setTimeout(resolve, 2000));
+
+ // Try to manually call renderNewsItems and catch errors
+ console.log('\n🎨 Manually calling renderNewsItems...');
+ const renderResult = await page.evaluate(() => {
+ try {
+ if (typeof renderNewsItems === 'function') {
+ renderNewsItems();
+ return { success: true, message: 'Called successfully' };
+ } else {
+ return { success: false, error: 'renderNewsItems not found' };
+ }
+ } catch (e) {
+ return {
+ success: false,
+ error: e.toString(),
+ stack: e.stack,
+ name: e.name
+ };
+ }
+ });
+
+ console.log('Render result:', JSON.stringify(renderResult, null, 2));
+
+ // Check container content
+ const containerInfo = await page.evaluate(() => {
+ const container = document.getElementById('news-feed-content');
+ return {
+ exists: !!container,
+ innerHTML: container ? container.innerHTML.substring(0, 300) : 'no container',
+ childCount: container ? container.children.length : 0
+ };
+ });
+
+ console.log('\n📋 Container info:');
+ console.log(JSON.stringify(containerInfo, null, 2));
+
+ // Check if specific functions exist
+ const functionCheck = await page.evaluate(() => {
+ return {
+ renderMarkdown: typeof renderMarkdown,
+ windowUi: typeof window.ui,
+ windowUiRenderMarkdown: window.ui ? typeof window.ui.renderMarkdown : 'no window.ui',
+ marked: typeof marked
+ };
+ });
+
+ console.log('\n🔧 Function availability:');
+ console.log(JSON.stringify(functionCheck, null, 2));
+
+ } catch (error) {
+ console.error('❌ Test failed:', error.message);
+ } finally {
+ await browser.close();
+ }
+}
+
+debugNewsError().catch(console.error);
diff --git a/tests/ldr-news-dev-files/redundant-tests/test_news_features.js b/tests/ldr-news-dev-files/redundant-tests/test_news_features.js
new file mode 100644
index 0000000000..01cd18a233
--- /dev/null
+++ b/tests/ldr-news-dev-files/redundant-tests/test_news_features.js
@@ -0,0 +1,149 @@
+const puppeteer = require('puppeteer');
+
+async function testNewsFeatures() {
+ console.log('🚀 Testing News Features: Topic Filtering and Source Links\n');
+
+ const browser = await puppeteer.launch({
+ headless: 'new',
+ args: ['--no-sandbox', '--disable-setuid-sandbox']
+ });
+
+ try {
+ const page = await browser.newPage();
+
+ // Enable console logging
+ page.on('console', msg => {
+ if (msg.type() !== 'error') return; // Only show errors
+ console.log('Browser console:', msg.text());
+ });
+
+ console.log('1️⃣ Loading news page...');
+ await page.goto('http://127.0.0.1:5000/news', { waitUntil: 'networkidle2' });
+
+ // Wait for news to load
+ await page.waitForSelector('.news-item', { timeout: 10000 });
+
+ // Check for source links
+ console.log('\n2️⃣ Checking source links...');
+ const sourceLinks = await page.evaluate(() => {
+ const links = [];
+ document.querySelectorAll('.news-sources').forEach(sourceDiv => {
+ const sourceLinks = sourceDiv.querySelectorAll('.source-link');
+ sourceLinks.forEach(link => {
+ links.push({
+ title: link.textContent.trim(),
+ url: link.href
+ });
+ });
+ });
+ return links;
+ });
+
+ console.log(`Found ${sourceLinks.length} source links`);
+ if (sourceLinks.length > 0) {
+ console.log('First 3 source links:');
+ sourceLinks.slice(0, 3).forEach(link => {
+ console.log(` - ${link.title}: ${link.url}`);
+ });
+ }
+
+ // Check trending topics
+ console.log('\n3️⃣ Checking trending topics...');
+ const topics = await page.evaluate(() => {
+ return Array.from(document.querySelectorAll('#trending-topics .topic-tag'))
+ .map(tag => tag.textContent);
+ });
+
+ console.log(`Found ${topics.length} trending topics:`, topics);
+
+ // Test topic filtering
+ console.log('\n4️⃣ Testing topic filtering...');
+ if (topics.length > 0) {
+ const topicToFilter = topics[0];
+ console.log(`Clicking on topic: ${topicToFilter}`);
+
+ // Click the first topic
+ await page.click('#trending-topics .topic-tag:first-child');
+
+ // Wait a bit for filter to apply
+ await new Promise(resolve => setTimeout(resolve, 1000));
+
+ // Check if filter is active
+ const filterState = await page.evaluate(() => {
+ const filterBar = document.querySelector('.active-filter-bar');
+ const activeTopics = document.querySelectorAll('.topic-tag.active');
+ const visibleNewsItems = document.querySelectorAll('.news-item:not([style*="display: none"])');
+
+ return {
+ hasFilterBar: !!filterBar,
+ filterText: filterBar?.textContent || '',
+ activeTopicCount: activeTopics.length,
+ visibleItemCount: visibleNewsItems.length
+ };
+ });
+
+ console.log('Filter state:', filterState);
+
+ // Take screenshot
+ await page.screenshot({
+ path: 'screenshots/news_tests/topic_filter_active.png',
+ fullPage: true
+ });
+ console.log('📸 Screenshot saved: topic_filter_active.png');
+
+ // Clear filter
+ const clearButton = await page.$('.active-filter-bar button');
+ if (clearButton) {
+ console.log('\n5️⃣ Clearing filter...');
+ await clearButton.click();
+ await new Promise(resolve => setTimeout(resolve, 500));
+
+ const clearedState = await page.evaluate(() => {
+ return {
+ hasFilterBar: !!document.querySelector('.active-filter-bar'),
+ activeTopicCount: document.querySelectorAll('.topic-tag.active').length
+ };
+ });
+
+ console.log('Filter cleared:', clearedState);
+ }
+ }
+
+ // Check news card structure
+ console.log('\n6️⃣ Checking news card structure...');
+ const cardInfo = await page.evaluate(() => {
+ const firstCard = document.querySelector('.news-item');
+ if (!firstCard) return null;
+
+ return {
+ hasHeadline: !!firstCard.querySelector('.news-headline'),
+ hasFindings: !!firstCard.querySelector('.news-findings'),
+ hasTopics: !!firstCard.querySelector('.news-topics'),
+ hasSources: !!firstCard.querySelector('.news-sources'),
+ hasVoteButtons: !!firstCard.querySelector('.vote-buttons'),
+ hasViewButton: !!firstCard.querySelector('a[href*="/results/"]'),
+ topicCount: firstCard.querySelectorAll('.news-topics .topic-tag').length,
+ sourceCount: firstCard.querySelectorAll('.source-link').length
+ };
+ });
+
+ console.log('News card structure:', cardInfo);
+
+ // Take final screenshot
+ await page.screenshot({
+ path: 'screenshots/news_tests/news_with_features.png',
+ fullPage: false
+ });
+ console.log('\n📸 Final screenshot saved: news_with_features.png');
+
+ console.log('\n✅ All tests completed!');
+
+ } catch (error) {
+ console.error('❌ Test error:', error.message);
+ } finally {
+ await browser.close();
+ }
+}
+
+// Run the test
+testNewsFeatures();
diff --git a/tests/ldr-news-dev-files/redundant-tests/test_news_final.js b/tests/ldr-news-dev-files/redundant-tests/test_news_final.js
new file mode 100644
index 0000000000..da45003c87
--- /dev/null
+++ b/tests/ldr-news-dev-files/redundant-tests/test_news_final.js
@@ -0,0 +1,240 @@
+/**
+ * Final comprehensive test of news system
+ */
+
+const puppeteer = require('puppeteer');
+
+async function testNewsFinal() {
+ console.log('🧪 Final News System Test\n');
+
+ const browser = await puppeteer.launch({
+ headless: false,
+ args: ['--no-sandbox', '--disable-setuid-sandbox'],
+ devtools: false
+ });
+
+ const page = await browser.newPage();
+ const results = {
+ pageLoad: false,
+ feedAPI: false,
+ subscriptionCreate: false,
+ subscriptionList: false,
+ modalFunction: false,
+ feedDisplay: false,
+ voteFunction: false
+ };
+
+ try {
+ // 1. Page Load Test
+ console.log('1️⃣ Testing page load...');
+ await page.goto('http://localhost:5000/news/', { waitUntil: 'networkidle2' });
+ results.pageLoad = true;
+ console.log('✅ Page loaded successfully');
+
+ // 2. Feed API Test
+ console.log('\n2️⃣ Testing feed API...');
+ const feedTest = await page.evaluate(async () => {
+ try {
+ const response = await fetch('/news/api/feed?user_id=final_test&limit=5');
+ const data = await response.json();
+ return {
+ ok: response.ok,
+ hasItems: data.news_items && data.news_items.length > 0,
+ itemCount: data.news_items ? data.news_items.length : 0,
+ source: data.source
+ };
+ } catch (e) {
+ return { ok: false, error: e.message };
+ }
+ });
+
+ if (feedTest.ok) {
+ results.feedAPI = true;
+ console.log(`✅ Feed API working (${feedTest.itemCount} items from ${feedTest.source})`);
+ } else {
+ console.log(`❌ Feed API failed: ${feedTest.error}`);
+ }
+
+ // 3. Create Subscription Test
+ console.log('\n3️⃣ Testing subscription creation...');
+ const subTest = await page.evaluate(async () => {
+ try {
+ const response = await fetch('/news/api/subscribe', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ user_id: 'final_test',
+ query: 'Final test subscription',
+ subscription_type: 'search',
+ refresh_hours: 6
+ })
+ });
+ const data = await response.json();
+ return {
+ ok: response.ok,
+ status: data.status,
+ id: data.subscription_id
+ };
+ } catch (e) {
+ return { ok: false, error: e.message };
+ }
+ });
+
+ if (subTest.ok && subTest.status === 'success') {
+ results.subscriptionCreate = true;
+ console.log(`✅ Subscription created: ${subTest.id}`);
+ } else {
+ console.log(`❌ Subscription creation failed: ${subTest.error || 'Unknown error'}`);
+ }
+
+ // 4. List Subscriptions Test
+ console.log('\n4️⃣ Testing subscription list...');
+ const listTest = await page.evaluate(async () => {
+ try {
+ const response = await fetch('/news/api/subscriptions/final_test');
+ const data = await response.json();
+ return {
+ ok: response.ok,
+ count: data.subscriptions ? data.subscriptions.length : 0,
+ hasOurSub: data.subscriptions?.some(s => s.query === 'Final test subscription')
+ };
+ } catch (e) {
+ return { ok: false, error: e.message };
+ }
+ });
+
+ if (listTest.ok && listTest.hasOurSub) {
+ results.subscriptionList = true;
+ console.log(`✅ Subscription list working (${listTest.count} subscriptions)`);
+ } else {
+ console.log(`❌ Subscription list failed`);
+ }
+
+ // 5. Modal Functionality Test
+ console.log('\n5️⃣ Testing modal functionality...');
+ const modalTest = await page.evaluate(() => {
+ try {
+ showCreateSubscriptionModal();
+ const modal = document.getElementById('subscriptionModal');
+ const isOpen = modal && modal.classList.contains('show');
+
+ if (isOpen) {
+ closeSubscriptionModal();
+ const isClosed = !modal.classList.contains('show');
+ return { success: true, opened: isOpen, closed: isClosed };
+ }
+ return { success: false, error: 'Modal did not open' };
+ } catch (e) {
+ return { success: false, error: e.message };
+ }
+ });
+
+ if (modalTest.success) {
+ results.modalFunction = true;
+ console.log('✅ Modal functionality working');
+ } else {
+ console.log(`❌ Modal test failed: ${modalTest.error}`);
+ }
+
+ // 6. Feed Display Test
+ console.log('\n6️⃣ Testing feed display...');
+ await page.evaluate(() => loadNewsFeed());
+ await new Promise(r => setTimeout(r, 2000));
+
+ const displayTest = await page.evaluate(() => {
+ const container = document.getElementById('news-feed-content');
+ const cards = document.querySelectorAll('.news-card, .news-item');
+ const skeleton = document.querySelectorAll('.loading-skeleton');
+ const emptyState = document.querySelector('.empty-state');
+
+ return {
+ hasContainer: !!container,
+ cardCount: cards.length,
+ skeletonCount: skeleton.length,
+ hasEmptyState: !!emptyState,
+ containerHTML: container ? container.innerHTML.substring(0, 100) : null
+ };
+ });
+
+ if (displayTest.cardCount > 0 || displayTest.hasEmptyState) {
+ results.feedDisplay = true;
+ console.log(`✅ Feed display working (${displayTest.cardCount} cards)`);
+ } else {
+ console.log('❌ Feed display not showing content');
+ }
+
+ // 7. Vote Functionality Test (if we have cards)
+ if (displayTest.cardCount > 0) {
+ console.log('\n7️⃣ Testing vote functionality...');
+ const voteTest = await page.evaluate(async () => {
+ try {
+ // Get first card's ID (mock or real)
+ const firstCard = document.querySelector('.news-card, .news-item');
+ const cardId = firstCard?.dataset.cardId || 'test-card-1';
+
+ const response = await fetch('/news/api/vote', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ user_id: 'final_test',
+ card_id: cardId,
+ vote: 'up'
+ })
+ });
+
+ return {
+ ok: response.ok,
+ status: response.status
+ };
+ } catch (e) {
+ return { ok: false, error: e.message };
+ }
+ });
+
+ if (voteTest.ok) {
+ results.voteFunction = true;
+ console.log('✅ Vote functionality working');
+ } else {
+ console.log(`⚠️ Vote test skipped or failed: ${voteTest.error || 'No cards to vote on'}`);
+ }
+ }
+
+ // Summary
+ console.log('\n📊 TEST SUMMARY');
+ console.log('='.repeat(50));
+
+ const passed = Object.values(results).filter(v => v).length;
+ const total = Object.keys(results).length;
+ const passRate = ((passed / total) * 100).toFixed(1);
+
+ Object.entries(results).forEach(([test, passed]) => {
+ console.log(`${passed ? '✅' : '❌'} ${test}`);
+ });
+
+ console.log(`\nPass Rate: ${passed}/${total} (${passRate}%)`);
+
+ if (passed === total) {
+ console.log('\n🎉 All tests passed! News system is fully functional.');
+ } else {
+ console.log('\n⚠️ Some tests failed. Check server logs for details.');
+ }
+
+ // Take final screenshot
+ await page.screenshot({
+ path: 'news_final_test_screenshot.png',
+ fullPage: true
+ });
+ console.log('\n📸 Screenshot saved as news_final_test_screenshot.png');
+
+ console.log('\n✨ Test complete! Browser will close in 5 seconds...');
+ await new Promise(r => setTimeout(r, 5000));
+
+ } catch (error) {
+ console.error('❌ Test error:', error);
+ } finally {
+ await browser.close();
+ }
+}
+
+// Run test
+testNewsFinal().catch(console.error);
diff --git a/tests/ldr-news-dev-files/redundant-tests/test_news_final_check.js b/tests/ldr-news-dev-files/redundant-tests/test_news_final_check.js
new file mode 100644
index 0000000000..4634a804fe
--- /dev/null
+++ b/tests/ldr-news-dev-files/redundant-tests/test_news_final_check.js
@@ -0,0 +1,133 @@
+const puppeteer = require('puppeteer');
+
+async function finalNewsCheck() {
+ console.log('🔍 Final News System Check\n');
+
+ const browser = await puppeteer.launch({
+ headless: 'new',
+ args: ['--no-sandbox', '--disable-setuid-sandbox']
+ });
+
+ try {
+ const page = await browser.newPage();
+ await page.setViewport({ width: 1280, height: 800 });
+
+ // Load news page
+ console.log('📰 Loading news page...');
+ await page.goto('http://localhost:5000/news/', { waitUntil: 'networkidle2' });
+
+ // Wait for initial render
+ await new Promise(resolve => setTimeout(resolve, 3000));
+
+ // Get current state
+ const initialState = await page.evaluate(() => {
+ return {
+ newsItemsArray: typeof newsItems !== 'undefined' ? newsItems.length : 0,
+ newsItemElements: document.querySelectorAll('.news-item').length,
+ newsCardElements: document.querySelectorAll('.news-card').length,
+ containerContent: document.getElementById('news-feed-content')?.children.length || 0
+ };
+ });
+
+ console.log('📊 Initial state:');
+ console.log(`- newsItems array: ${initialState.newsItemsArray} items`);
+ console.log(`- DOM .news-item elements: ${initialState.newsItemElements}`);
+ console.log(`- DOM .news-card elements: ${initialState.newsCardElements}`);
+ console.log(`- Container children: ${initialState.containerContent}`);
+
+ // Force render of news items
+ console.log('\n🔄 Forcing renderNewsItems()...');
+ const renderResult = await page.evaluate(() => {
+ // Clear any existing content first
+ const container = document.getElementById('news-feed-content');
+ if (container) {
+ container.innerHTML = '';
+ }
+
+ // Check if renderNewsItems exists and call it
+ if (typeof renderNewsItems === 'function') {
+ try {
+ renderNewsItems();
+ return { success: true, message: 'renderNewsItems called' };
+ } catch (e) {
+ return { success: false, error: e.toString() };
+ }
+ } else {
+ // If it doesn't exist, try to render manually
+ if (typeof newsItems !== 'undefined' && Array.isArray(newsItems) && newsItems.length > 0) {
+ const container = document.getElementById('news-feed-content');
+ if (container) {
+ // Render each news item
+ const html = newsItems.map(item => `
+ <div class="news-item priority-medium" data-news-id="${item.id}">
+ <div class="news-headline">${item.headline}</div>
+ <div class="news-meta">
+ <span class="news-category">${item.category || 'General'}</span>
+ <span><i class="fas fa-clock"></i> ${item.time_ago || 'Recently'}</span>
+ </div>
+ <div class="news-summary">${item.summary || ''}</div>
+ </div>
+ `).join('');
+ container.innerHTML = html;
+ return { success: true, message: 'Manually rendered news items' };
+ }
+ }
+ return { success: false, error: 'renderNewsItems not found' };
+ }
+ });
+
+ console.log('Render result:', renderResult);
+
+ await new Promise(resolve => setTimeout(resolve, 1000));
+
+ // Check final state
+ const finalState = await page.evaluate(() => {
+ return {
+ newsItemElements: document.querySelectorAll('.news-item').length,
+ newsCardElements: document.querySelectorAll('.news-card').length,
+ containerHTML: document.getElementById('news-feed-content')?.innerHTML.substring(0, 200) || 'empty'
+ };
+ });
+
+ console.log('\n📈 Final state:');
+ console.log(`- DOM .news-item elements: ${finalState.newsItemElements}`);
+ console.log(`- DOM .news-card elements: ${finalState.newsCardElements}`);
+ console.log(`- Container preview: ${finalState.containerHTML}...`);
+
+ // Take screenshot
+ await page.screenshot({
+ path: 'tests/ui_tests/screenshots/news_final_check.png',
+ fullPage: true
+ });
+
+ // Test API directly
+ console.log('\n🔌 Testing API directly...');
+ const apiTest = await page.evaluate(async () => {
+ const response = await fetch('/news/api/feed?user_id=test&limit=5');
+ const data = await response.json();
+ return {
+ status: response.status,
+ itemCount: data.news_items?.length || 0,
+ source: data.source,
+ firstItem: data.news_items?.[0] || null
+ };
+ });
+
+ console.log('API Response:');
+ console.log(`- Status: ${apiTest.status}`);
+ console.log(`- Items: ${apiTest.itemCount}`);
+ console.log(`- Source: ${apiTest.source}`);
+ if (apiTest.firstItem) {
+ console.log(`- First item headline: "${apiTest.firstItem.headline}"`);
+ }
+
+ console.log('\n✅ Test completed!');
+
+ } catch (error) {
+ console.error('❌ Test failed:', error.message);
+ } finally {
+ await browser.close();
+ }
+}
+
+finalNewsCheck().catch(console.error);
diff --git a/tests/ldr-news-dev-files/redundant-tests/test_news_load_sequence.js b/tests/ldr-news-dev-files/redundant-tests/test_news_load_sequence.js
new file mode 100644
index 0000000000..ab83245e93
--- /dev/null
+++ b/tests/ldr-news-dev-files/redundant-tests/test_news_load_sequence.js
@@ -0,0 +1,103 @@
+const puppeteer = require('puppeteer');
+
+async function testLoadSequence() {
+ console.log('🔍 Testing News Page Load Sequence\n');
+
+ const browser = await puppeteer.launch({
+ headless: 'new',
+ args: ['--no-sandbox', '--disable-setuid-sandbox']
+ });
+
+ try {
+ const page = await browser.newPage();
+
+ // Track console logs
+ const logs = [];
+ page.on('console', msg => {
+ const text = msg.text();
+ logs.push(text);
+ console.log(`[Browser]: ${text}`);
+ });
+
+ await page.setViewport({ width: 1280, height: 800 });
+
+ // Navigate and wait for network idle
+ console.log('📰 Loading news page...\n');
+ await page.goto('http://localhost:5000/news/', {
+ waitUntil: 'networkidle2',
+ timeout: 30000
+ });
+
+ // Wait for JavaScript to execute
+ await new Promise(resolve => setTimeout(resolve, 3000));
+
+ // Check what happened
+ const pageState = await page.evaluate(() => {
+ const container = document.getElementById('news-feed-content');
+ const items = container ? container.querySelectorAll('.news-item, .news-card') : [];
+
+ return {
+ containerExists: !!container,
+ totalItems: items.length,
+ itemTypes: Array.from(items).map(item => ({
+ class: item.className,
+ id: item.dataset.newsId || item.dataset.researchId || 'no-id',
+ headline: item.querySelector('.news-headline, .news-title')?.innerText?.substring(0, 50) || 'no-headline'
+ })),
+ newsItemsArrayLength: typeof newsItems !== 'undefined' ? newsItems.length : 0,
+ firstNewsItem: typeof newsItems !== 'undefined' && newsItems.length > 0 ? {
+ id: newsItems[0].id,
+ headline: newsItems[0].headline
+ } : null
+ };
+ });
+
+ console.log('\n📊 Page State:');
+ console.log(`- Container exists: ${pageState.containerExists}`);
+ console.log(`- Total items displayed: ${pageState.totalItems}`);
+ console.log(`- newsItems array length: ${pageState.newsItemsArrayLength}`);
+
+ if (pageState.firstNewsItem) {
+ console.log(`- First array item: ${pageState.firstNewsItem.id} - "${pageState.firstNewsItem.headline}"`);
+ }
+
+ console.log('\n📋 Displayed items:');
+ pageState.itemTypes.forEach((item, i) => {
+ console.log(` ${i + 1}. [${item.class}] ${item.id}: "${item.headline}..."`);
+ });
+
+ // Check if renderNewsItems was called
+ const renderCheck = await page.evaluate(() => {
+ return {
+ renderNewsFunctionExists: typeof renderNewsItems === 'function',
+ loadNewsFeedExists: typeof loadNewsFeed === 'function'
+ };
+ });
+
+ console.log('\n🔧 Function availability:');
+ console.log(`- renderNewsItems exists: ${renderCheck.renderNewsFunctionExists}`);
+ console.log(`- loadNewsFeed exists: ${renderCheck.loadNewsFeedExists}`);
+
+ // Look for specific console logs
+ const apiLog = logs.find(log => log.includes('Loaded') && log.includes('news items from API'));
+ if (apiLog) {
+ console.log(`\n✅ Found API load log: "${apiLog}"`);
+ } else {
+ console.log('\n⚠️ No API load log found');
+ }
+
+ // Take screenshot
+ await page.screenshot({
+ path: 'tests/ui_tests/screenshots/news_load_sequence.png',
+ fullPage: true
+ });
+ console.log('\n📸 Screenshot saved');
+
+ } catch (error) {
+ console.error('❌ Test failed:', error.message);
+ } finally {
+ await browser.close();
+ }
+}
+
+testLoadSequence().catch(console.error);
diff --git a/tests/ldr-news-dev-files/redundant-tests/test_news_no_cache.js b/tests/ldr-news-dev-files/redundant-tests/test_news_no_cache.js
new file mode 100644
index 0000000000..d4ae312534
--- /dev/null
+++ b/tests/ldr-news-dev-files/redundant-tests/test_news_no_cache.js
@@ -0,0 +1,80 @@
+const puppeteer = require('puppeteer');
+const fs = require('fs').promises;
+
+async function testNewsNoCache() {
+ const browser = await puppeteer.launch({
+ headless: 'new',
+ args: ['--no-sandbox', '--disable-setuid-sandbox']
+ });
+
+ try {
+ const page = await browser.newPage();
+ await page.setViewport({ width: 1280, height: 800 });
+
+ // Disable all caching
+ await page.setCacheEnabled(false);
+
+ // Clear any application data
+ const client = await page.target().createCDPSession();
+ await client.send('Network.clearBrowserCache');
+ await client.send('Network.clearBrowserCookies');
+
+ console.log('Loading news page with completely fresh data...');
+
+ // Add timestamp to force fresh load
+ await page.goto(`http://127.0.0.1:5000/news?t=${Date.now()}`, {
+ waitUntil: 'networkidle2',
+ headers: {
+ 'Cache-Control': 'no-cache, no-store, must-revalidate',
+ 'Pragma': 'no-cache',
+ 'Expires': '0'
+ }
+ });
+
+ // Wait for API call to complete
+ await page.waitForResponse(response =>
+ response.url().includes('/news/api/feed'),
+ { timeout: 10000 }
+ );
+
+ // Wait a bit more for rendering
+ await new Promise(resolve => setTimeout(resolve, 2000));
+
+ // Check content of first news item
+ const firstItemContent = await page.evaluate(() => {
+ const firstItem = document.querySelector('.news-item');
+ if (!firstItem) return null;
+
+ const headline = firstItem.querySelector('.news-headline')?.textContent;
+ const findings = firstItem.querySelector('.news-findings')?.textContent;
+
+ return {
+ headline: headline?.trim(),
+ findingsStart: findings?.substring(0, 200).trim(),
+ hasQuery: findings?.toLowerCase().includes('query:'),
+ hasSummaryHeader: findings?.includes('Quick Research Summary')
+ };
+ });
+
+ console.log('\nFirst news item content:');
+ console.log('Headline:', firstItemContent?.headline);
+ console.log('\nFindings start:', firstItemContent?.findingsStart);
+ console.log('\nContains "Query:"?', firstItemContent?.hasQuery ? '❌ YES' : '✅ NO');
+ console.log('Contains "Quick Research Summary"?', firstItemContent?.hasSummaryHeader ? '❌ YES' : '✅ NO');
+
+ // Take screenshot
+ await fs.mkdir('screenshots', { recursive: true });
+ await page.screenshot({
+ path: 'screenshots/news_no_cache_final.png',
+ fullPage: true
+ });
+ console.log('\nScreenshot saved to screenshots/news_no_cache_final.png');
+
+ } catch (error) {
+ console.error('Test failed:', error);
+ } finally {
+ await browser.close();
+ }
+}
+
+testNewsNoCache();
diff --git a/tests/ldr-news-dev-files/redundant-tests/test_news_render_debug.js b/tests/ldr-news-dev-files/redundant-tests/test_news_render_debug.js
new file mode 100644
index 0000000000..d5e22ef7a4
--- /dev/null
+++ b/tests/ldr-news-dev-files/redundant-tests/test_news_render_debug.js
@@ -0,0 +1,137 @@
+const puppeteer = require('puppeteer');
+
+async function debugNewsRendering() {
+ console.log('🔍 Debugging News Rendering Issue\n');
+
+ const browser = await puppeteer.launch({
+ headless: 'new',
+ args: ['--no-sandbox', '--disable-setuid-sandbox']
+ });
+
+ try {
+ const page = await browser.newPage();
+
+ // Capture ALL console logs and errors
+ page.on('console', msg => {
+ const type = msg.type();
+ const text = msg.text();
+ if (type === 'error') {
+ console.log(`[JS ERROR]:`, text);
+ } else {
+ console.log(`[Browser ${type}]:`, text);
+ }
+ });
+
+ page.on('pageerror', error => {
+ console.log('[Page Error]:', error.message);
+ });
+
+ await page.setViewport({ width: 1280, height: 800 });
+
+ // Load news page
+ console.log('📰 Loading news page...');
+ const response = await page.goto('http://localhost:5000/news/', {
+ waitUntil: 'networkidle2',
+ timeout: 30000
+ });
+
+ console.log(`Page loaded with status: ${response.status()}`);
+
+ // Wait a bit for JavaScript to execute
+ await new Promise(resolve => setTimeout(resolve, 2000));
+
+ // Check if news-feed-content exists
+ const feedContentInfo = await page.evaluate(() => {
+ const element = document.getElementById('news-feed-content');
+ if (!element) return { exists: false };
+
+ return {
+ exists: true,
+ innerHTML: element.innerHTML.substring(0, 200),
+ childCount: element.children.length,
+ className: element.className,
+ style: element.getAttribute('style')
+ };
+ });
+
+ console.log('\n📋 news-feed-content element:');
+ console.log(JSON.stringify(feedContentInfo, null, 2));
+
+ // Check what's in the global scope
+ const globalFunctions = await page.evaluate(() => {
+ return {
+ loadNewsFeed: typeof loadNewsFeed,
+ renderNewsItems: typeof renderNewsItems,
+ newsItems: typeof newsItems !== 'undefined' ?
+ (Array.isArray(newsItems) ? `Array(${newsItems.length})` : typeof newsItems) :
+ 'undefined'
+ };
+ });
+
+ console.log('\n🌐 Global functions:');
+ console.log(JSON.stringify(globalFunctions, null, 2));
+
+ // Try to inspect the news items
+ const newsItemsData = await page.evaluate(() => {
+ if (typeof newsItems !== 'undefined' && Array.isArray(newsItems)) {
+ return {
+ count: newsItems.length,
+ firstItem: newsItems[0] || null,
+ hasFindings: newsItems.some(item => item.findings),
+ hasSummary: newsItems.some(item => item.summary)
+ };
+ }
+ return null;
+ });
+
+ console.log('\n📊 News items data:');
+ console.log(JSON.stringify(newsItemsData, null, 2));
+
+ // Check if the rendering function is being called
+ console.log('\n🎨 Checking rendering...');
+ await page.evaluate(() => {
+ console.log('About to check rendering function...');
+ if (typeof renderNewsItems === 'function') {
+ console.log('renderNewsItems exists, calling it...');
+ try {
+ renderNewsItems();
+ console.log('renderNewsItems called successfully');
+ } catch (e) {
+ console.error('Error calling renderNewsItems:', e);
+ }
+ } else {
+ console.error('renderNewsItems is not a function');
+ }
+ });
+
+ await new Promise(resolve => setTimeout(resolve, 1000));
+
+ // Check results after render attempt
+ const afterRenderInfo = await page.evaluate(() => {
+ const container = document.getElementById('news-feed-content');
+ return {
+ newsItemCount: document.querySelectorAll('.news-item').length,
+ containerHTML: container ? container.innerHTML.substring(0, 500) : 'no container',
+ hasEmptyState: container ? container.querySelector('.empty-state') !== null : false
+ };
+ });
+
+ console.log('\n📈 After render attempt:');
+ console.log(JSON.stringify(afterRenderInfo, null, 2));
+
+ // Take screenshot for visual debugging
+ await page.screenshot({
+ path: 'tests/ui_tests/screenshots/news_render_debug.png',
+ fullPage: true
+ });
+ console.log('\n📸 Screenshot saved');
+
+ } catch (error) {
+ console.error('❌ Test failed:', error.message);
+ console.error(error.stack);
+ } finally {
+ await browser.close();
+ }
+}
+
+debugNewsRendering().catch(console.error);
diff --git a/tests/ldr-news-dev-files/redundant-tests/test_news_screenshots.js b/tests/ldr-news-dev-files/redundant-tests/test_news_screenshots.js
new file mode 100644
index 0000000000..abda62a604
--- /dev/null
+++ b/tests/ldr-news-dev-files/redundant-tests/test_news_screenshots.js
@@ -0,0 +1,114 @@
+/**
+ * Visual regression test for news page
+ */
+
+const BaseTest = require('../../utils/BaseTest');
+const config = require('../../config/test.config');
+
+async function testNewsVisual() {
+ const test = new BaseTest('NewsVisual');
+
+ await test.run(async (t) => {
+ // Test different viewport sizes
+ const viewports = [
+ { name: 'desktop', width: 1920, height: 1080 },
+ { name: 'laptop', width: 1366, height: 768 },
+ { name: 'tablet', width: 768, height: 1024 },
+ { name: 'mobile', width: 375, height: 667 }
+ ];
+
+ for (const viewport of viewports) {
+ t.log(viewport.name, `Testing ${viewport.width}x${viewport.height} viewport`);
+
+ // Set viewport
+ await t.browserUtils.page.setViewport({
+ width: viewport.width,
+ height: viewport.height
+ });
+
+ // Navigate to news page
+ await t.newsPage.goto();
+ await t.wait(2000); // Wait for layout to stabilize
+
+ // Take screenshot of initial state
+ await t.screenshot(`${viewport.name}_initial`);
+
+ // Perform search
+ await t.newsPage.search('technology news');
+ await t.wait(3000);
+
+ // Screenshot with results
+ await t.screenshot(`${viewport.name}_with_results`);
+
+ // Check layout integrity
+ const metrics = await t.newsPage.getPageMetrics();
+ t.assert(metrics.errors === 0, `No errors in ${viewport.name} view`);
+
+ // Test hover states (desktop only)
+ if (viewport.width >= 1024) {
+ const cards = await t.browserUtils.page.$$('.news-card');
+ if (cards.length > 0) {
+ await cards[0].hover();
+ await t.wait(500);
+ await t.screenshot(`${viewport.name}_hover_state`);
+ }
+ }
+
+ // Test dark mode if available
+ const darkModeToggle = await t.browserUtils.page.$('[class*="dark-mode"], [class*="theme-toggle"]');
+ if (darkModeToggle) {
+ await darkModeToggle.click();
+ await t.wait(1000);
+ await t.screenshot(`${viewport.name}_dark_mode`);
+
+ // Toggle back
+ await darkModeToggle.click();
+ await t.wait(500);
+ }
+ }
+
+ // Test loading states
+ t.log('Loading', 'Testing loading states');
+ await t.browserUtils.page.setViewport(config.browser.defaultViewport);
+
+ // Trigger a slow search
+ await t.newsPage.search('comprehensive analysis of global events', 'comprehensive');
+
+ // Capture loading state quickly
+ await t.wait(100);
+ await t.screenshot('loading_state');
+
+ // Wait for completion
+ await t.newsPage.waitForNewsToLoad();
+ await t.screenshot('loaded_state');
+
+ // Test error states
+ t.log('Errors', 'Testing error states');
+
+ // Try invalid API call
+ try {
+ await t.apiUtils.post('/news/api/invalid_endpoint', {});
+ } catch (error) {
+ // Expected
+ }
+
+ // Check if error message appears
+ await t.wait(1000);
+ const alert = await t.newsPage.getAlertMessage();
+ if (alert) {
+ await t.screenshot('error_state');
+ t.success('Error state captured');
+ }
+
+ // Performance visualization
+ const performance = await t.measurePerformance();
+ t.log('Performance', `Visual tests completed. Load time: ${performance.loadTime}ms`);
+ });
+}
+
+// Run test if executed directly
+if (require.main === module) {
+ testNewsVisual().catch(console.error);
+}
+
+module.exports = testNewsVisual;
diff --git a/tests/ldr-news-dev-files/redundant-tests/test_news_status.js b/tests/ldr-news-dev-files/redundant-tests/test_news_status.js
new file mode 100644
index 0000000000..fd47816682
--- /dev/null
+++ b/tests/ldr-news-dev-files/redundant-tests/test_news_status.js
@@ -0,0 +1,68 @@
+const puppeteer = require('puppeteer');
+
+async function checkNewsSystemStatus() {
+ console.log('📊 LDR News System Status Check\n');
+
+ const browser = await puppeteer.launch({
+ headless: 'new',
+ args: ['--no-sandbox', '--disable-setuid-sandbox']
+ });
+
+ try {
+ const page = await browser.newPage();
+
+ // Test 1: API Feed
+ console.log('🔍 Checking API Feed...');
+ const feedResponse = await page.goto('http://localhost:5000/news/api/feed?user_id=test&limit=5');
+ const feedData = await feedResponse.json();
+ console.log(`✅ API Feed: ${feedData.news_items?.length || 0} items`);
+ console.log(` Source: ${feedData.source || 'unknown'}`);
+ console.log(` Strategy: ${feedData.search_strategy || 'default'}`);
+
+ // Test 2: Page Load
+ console.log('\n🔍 Checking News Page...');
+ await page.goto('http://localhost:5000/news/', { waitUntil: 'networkidle2' });
+
+ // Get page statistics
+ const pageStats = await page.evaluate(() => {
+ const cards = document.querySelectorAll('.card, .news-card');
+ const voteButtons = document.querySelectorAll('.vote-button, .btn-upvote, .btn-downvote');
+ const hasModal = document.querySelector('#newsModal') !== null;
+ const hasBootstrap = typeof window.bootstrap !== 'undefined';
+
+ return {
+ cardCount: cards.length,
+ voteButtonCount: voteButtons.length,
+ hasModal,
+ hasBootstrap,
+ pageTitle: document.title
+ };
+ });
+
+ console.log(`✅ Page loaded: "${pageStats.pageTitle}"`);
+ console.log(` News cards: ${pageStats.cardCount}`);
+ console.log(` Vote buttons: ${pageStats.voteButtonCount}`);
+ console.log(` Bootstrap loaded: ${pageStats.hasBootstrap}`);
+ console.log(` Modal present: ${pageStats.hasModal}`);
+
+ // Test 3: Subscription API
+ console.log('\n🔍 Checking Subscription API...');
+ const subResponse = await page.goto('http://localhost:5000/news/api/subscriptions/test_user');
+ const subData = await subResponse.json();
+ console.log(`✅ Subscriptions: ${subData.subscriptions?.length || 0} active`);
+
+ console.log('\n✅ News system is operational with the following status:');
+ console.log(' - API endpoints are working');
+ console.log(' - News feed is generating content');
+ console.log(' - UI is displaying news cards');
+ console.log(' - Vote functionality is present (but needs card storage)');
+ console.log(' - Modal needs to be added to template');
+
+ } catch (error) {
+ console.error('❌ Error:', error.message);
+ } finally {
+ await browser.close();
+ }
+}
+
+checkNewsSystemStatus().catch(console.error);
diff --git a/tests/ldr-news-dev-files/redundant-tests/test_news_ui_debug.js b/tests/ldr-news-dev-files/redundant-tests/test_news_ui_debug.js
new file mode 100644
index 0000000000..848a72d553
--- /dev/null
+++ b/tests/ldr-news-dev-files/redundant-tests/test_news_ui_debug.js
@@ -0,0 +1,129 @@
+const puppeteer = require('puppeteer');
+
+async function debugNewsUI() {
+ console.log('🔍 Debugging News UI Rendering\n');
+
+ const browser = await puppeteer.launch({
+ headless: 'new',
+ args: ['--no-sandbox', '--disable-setuid-sandbox']
+ });
+
+ try {
+ const page = await browser.newPage();
+
+ // Capture console logs
+ page.on('console', msg => {
+ console.log(`[Browser ${msg.type()}]:`, msg.text());
+ });
+
+ // Capture errors
+ page.on('pageerror', error => {
+ console.log('[Browser Error]:', error.message);
+ });
+
+ await page.setViewport({ width: 1280, height: 800 });
+
+ // Load news page
+ console.log('📰 Loading news page...');
+ await page.goto('http://localhost:5000/news/', { waitUntil: 'networkidle2' });
+
+ // Check if news.js loaded
+ const hasNewsJS = await page.evaluate(() => {
+ return typeof loadNewsFeed !== 'undefined';
+ });
+ console.log(`✅ news.js loaded: ${hasNewsJS}`);
+
+ // Check global variables
+ const globalState = await page.evaluate(() => {
+ return {
+ newsItems: typeof newsItems !== 'undefined' ? newsItems : 'undefined',
+ currentUser: typeof currentUser !== 'undefined' ? currentUser : 'undefined',
+ subscriptions: typeof subscriptions !== 'undefined' ? subscriptions : 'undefined'
+ };
+ });
+ console.log('\n📊 Global state:');
+ console.log('- newsItems:', Array.isArray(globalState.newsItems) ? `Array(${globalState.newsItems.length})` : globalState.newsItems);
+ console.log('- currentUser:', globalState.currentUser);
+ console.log('- subscriptions:', Array.isArray(globalState.subscriptions) ? `Array(${globalState.subscriptions.length})` : globalState.subscriptions);
+
+ // Check DOM elements
+ const domInfo = await page.evaluate(() => {
+ return {
+ feedContent: document.getElementById('news-feed-content') ? 'exists' : 'missing',
+ cardView: document.getElementById('news-card-view') ? 'exists' : 'missing',
+ newsItems: document.querySelectorAll('.news-item').length,
+ cards: document.querySelectorAll('.card').length,
+ errorMessages: document.querySelectorAll('.error-message').length,
+ loadingPlaceholder: document.querySelectorAll('.loading-placeholder').length
+ };
+ });
+ console.log('\n📋 DOM elements:');
+ console.log(JSON.stringify(domInfo, null, 2));
+
+ // Call loadNewsFeed manually and check result
+ console.log('\n🔄 Manually calling loadNewsFeed()...');
+ await page.evaluate(() => loadNewsFeed());
+ await new Promise(resolve => setTimeout(resolve, 2000));
+
+ // Check newsItems after manual load
+ const afterLoad = await page.evaluate(() => {
+ return {
+ newsItemsCount: newsItems ? newsItems.length : 0,
+ newsItemsSample: newsItems && newsItems.length > 0 ? newsItems[0] : null,
+ domNewsItems: document.querySelectorAll('.news-item').length,
+ domCards: document.querySelectorAll('.card').length,
+ cardViewHTML: document.getElementById('news-card-view')?.innerHTML.substring(0, 200) || 'no content'
+ };
+ });
+ console.log('\n📈 After manual loadNewsFeed:');
+ console.log('- newsItems array length:', afterLoad.newsItemsCount);
+ console.log('- First news item:', JSON.stringify(afterLoad.newsItemsSample, null, 2));
+ console.log('- DOM .news-item count:', afterLoad.domNewsItems);
+ console.log('- DOM .card count:', afterLoad.domCards);
+ console.log('- Card view HTML preview:', afterLoad.cardViewHTML);
+
+ // Check renderNewsItems function
+ console.log('\n🎨 Testing renderNewsItems()...');
+ await page.evaluate(() => {
+ // Add test data directly
+ newsItems = [{
+ id: 'test-123',
+ headline: 'Test Headline',
+ category: 'Test',
+ summary: 'Test summary',
+ impact_score: 5,
+ time_ago: 'Just now',
+ upvotes: 0,
+ downvotes: 0
+ }];
+ renderNewsItems();
+ });
+
+ await new Promise(resolve => setTimeout(resolve, 500));
+
+ const afterRender = await page.evaluate(() => {
+ return {
+ newsItemsCount: document.querySelectorAll('.news-item').length,
+ cardViewContent: document.getElementById('news-card-view')?.innerHTML.includes('Test Headline')
+ };
+ });
+ console.log('\n✅ After manual renderNewsItems with test data:');
+ console.log('- News items rendered:', afterRender.newsItemsCount);
+ console.log('- Test headline visible:', afterRender.cardViewContent);
+
+ // Take screenshot
+ await page.screenshot({
+ path: 'tests/ui_tests/screenshots/news_ui_debug.png',
+ fullPage: true
+ });
+ console.log('\n📸 Screenshot saved to: tests/ui_tests/screenshots/news_ui_debug.png');
+
+ } catch (error) {
+ console.error('❌ Debug failed:', error.message);
+ console.error(error.stack);
+ } finally {
+ await browser.close();
+ }
+}
+
+debugNewsUI().catch(console.error);
diff --git a/tests/ldr-news-dev-files/redundant-tests/test_news_visual_final.js b/tests/ldr-news-dev-files/redundant-tests/test_news_visual_final.js
new file mode 100644
index 0000000000..c714d292e0
--- /dev/null
+++ b/tests/ldr-news-dev-files/redundant-tests/test_news_visual_final.js
@@ -0,0 +1,58 @@
+const puppeteer = require('puppeteer');
+
+async function testNewsFinal() {
+ console.log('📸 Taking final screenshot of working news page\n');
+
+ const browser = await puppeteer.launch({
+ headless: 'new',
+ args: ['--no-sandbox', '--disable-setuid-sandbox']
+ });
+
+ try {
+ const page = await browser.newPage();
+ await page.setViewport({ width: 1280, height: 800 });
+
+ console.log('Loading news page...');
+ await page.goto('http://localhost:5000/news/', { waitUntil: 'networkidle2' });
+
+ // Wait for content to render
+ await page.waitForSelector('.news-item', { timeout: 5000 });
+
+ // Get stats
+ const stats = await page.evaluate(() => {
+ return {
+ newsItems: document.querySelectorAll('.news-item').length,
+ newsCards: document.querySelectorAll('.news-card').length,
+ totalItems: document.querySelectorAll('.news-item, .news-card').length,
+ firstHeadline: document.querySelector('.news-headline')?.textContent || 'No headline',
+ hasFindings: document.querySelectorAll('.news-findings').length
+ };
+ });
+
+ console.log('📊 Page Stats:');
+ console.log(`- News items: ${stats.newsItems}`);
+ console.log(`- News cards: ${stats.newsCards}`);
+ console.log(`- Total items: ${stats.totalItems}`);
+ console.log(`- First headline: "${stats.firstHeadline}"`);
+ console.log(`- Items with findings: ${stats.hasFindings}`);
+
+ // Take full page screenshot
+ await page.screenshot({
+ path: 'tests/ui_tests/screenshots/news_working_final.png',
+ fullPage: true
+ });
+
+ console.log('\n✅ Screenshot saved to: tests/ui_tests/screenshots/news_working_final.png');
+ console.log('\n🎉 News system is working correctly!');
+ console.log(' - News items are pulled from research history');
+ console.log(' - Markdown findings are rendered');
+ console.log(' - No JavaScript errors');
+
+ } catch (error) {
+ console.error('❌ Error:', error.message);
+ } finally {
+ await browser.close();
+ }
+}
+
+testNewsFinal().catch(console.error);
diff --git a/tests/ldr-news-dev-files/redundant-tests/test_news_with_data.js b/tests/ldr-news-dev-files/redundant-tests/test_news_with_data.js
new file mode 100644
index 0000000000..161e750585
--- /dev/null
+++ b/tests/ldr-news-dev-files/redundant-tests/test_news_with_data.js
@@ -0,0 +1,67 @@
+const puppeteer = require('puppeteer');
+
+async function testNewsWithData() {
+ const browser = await puppeteer.launch({
+ headless: true,
+ args: ['--no-sandbox', '--disable-setuid-sandbox']
+ });
+
+ try {
+ const page = await browser.newPage();
+
+ // Set viewport
+ await page.setViewport({ width: 1920, height: 1080 });
+
+ // Listen to console logs
+ page.on('console', msg => console.log(`[${msg.type()}] ${msg.text()}`));
+
+ // Listen for API calls
+ page.on('response', response => {
+ if (response.url().includes('/api/history') || response.url().includes('/api/report')) {
+ console.log(`[API Response] ${response.url()} - ${response.status()}`);
+ }
+ });
+
+ // Navigate to news page
+ console.log('Navigating to news page...');
+ await page.goto('http://localhost:5000/news/', {
+ waitUntil: 'networkidle2',
+ timeout: 30000
+ });
+
+ // Wait for the checkForCompletedNewsSearches to run
+ await new Promise(resolve => setTimeout(resolve, 5000));
+
+ // Check what's in the news feed now
+ const newsContent = await page.evaluate(() => {
+ const cards = document.querySelectorAll('.news-card');
+ const researchCards = document.querySelectorAll('[data-research-id]');
+
+ return {
+ totalCards: cards.length,
+ researchCards: researchCards.length,
+ cardDetails: Array.from(cards).map(card => ({
+ title: card.querySelector('.news-title')?.textContent,
+ researchId: card.getAttribute('data-research-id'),
+ summary: card.querySelector('.news-summary')?.textContent?.substring(0, 100)
+ }))
+ };
+ });
+
+ console.log('News cards found:', JSON.stringify(newsContent, null, 2));
+
+ // Take screenshot
+ await page.screenshot({
+ path: 'news_with_completed.png',
+ fullPage: false
+ });
+ console.log('Screenshot saved: news_with_completed.png');
+
+ } catch (error) {
+ console.error('Test error:', error);
+ } finally {
+ await browser.close();
+ }
+}
+
+testNewsWithData();