~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
"""
FastAPI router for news system page routes.
Ported from news/web.py Flask blueprint factory.
"""
from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
from loguru import logger
from .notes import _log_value_preview
from ...constants import DEFAULT_SEARCH_TOOL, get_available_strategies
from ...settings.exceptions import SettingsValueError
from ..dependencies.auth import require_auth
from ..template_config import templates
from typing import Annotated
router = APIRouter(prefix="/news", tags=["news_pages"])
@router.get("/")
def news_page(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Render the main news page."""
# news.html renders <option value="{{ s.name }}">{{ s.label }}</option>,
# so it needs the {name,label,description} dicts get_available_strategies
# returns — the source main used. The previous hardcoded string list
# ("topic_based", "news_aggregation", ...) was both the wrong shape
# (every option rendered blank) AND wrong names (those strategies don't
# exist; the real ones are "source-based", "focused-iteration", ...).
from ...constants import get_available_strategies
strategies = get_available_strategies()
return templates.TemplateResponse(
request=request,
name="pages/news.html",
context={"strategies": strategies},
)
@router.get("/subscriptions")
def subscriptions_page(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Render the subscriptions management page."""
return templates.TemplateResponse(
request=request,
name="pages/subscriptions.html",
context={},
)
@router.get("/subscriptions/new")
def new_subscription_page(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Render the create subscription page."""
default_settings = {
"iterations": 3,
"questions_per_iteration": 5,
"search_engine": DEFAULT_SEARCH_TOOL,
"model_provider": "ollama",
"model": "",
"search_strategy": "source-based",
# Issue #5204: scope key for the egress-aware search-engine dropdown.
# ``_load_user_settings`` overwrites this with the user's saved value;
# the hardcoded default is the safe-by-default ``adaptive`` for
# anonymous / no-DB paths.
"egress_scope": "adaptive",
# Required, not cosmetic: the template renders this through
# ``| tojson``, and Jinja's Undefined is not JSON-serialisable, so
# omitting it turns the not-found and error branches (which skip
# ``_load_user_settings``) into a 500 rather than a rendered page.
"custom_endpoint": "",
}
from ...database.session_context import get_user_db_session
with get_user_db_session(username) as db_session:
_load_user_settings(default_settings, db_session, username)
return templates.TemplateResponse(
request=request,
name="pages/news-subscription-form.html",
context={
"subscription": None,
"default_settings": default_settings,
"strategies": get_available_strategies(),
},
)
@router.get("/subscriptions/{subscription_id}/edit")
def edit_subscription_page(
request: Request,
subscription_id: str,
username: Annotated[str, Depends(require_auth)],
):
"""Render the edit subscription page."""
subscription = None
default_settings = {
"iterations": 3,
"questions_per_iteration": 5,
"search_engine": DEFAULT_SEARCH_TOOL,
"model_provider": "ollama",
"model": "",
"search_strategy": "source-based",
# Issue #5204: scope key for the egress-aware search-engine dropdown.
# ``_load_user_settings`` overwrites this with the user's saved value;
# the hardcoded default is the safe-by-default ``adaptive`` for
# anonymous / no-DB paths.
"egress_scope": "adaptive",
# Required, not cosmetic: the template renders this through
# ``| tojson``, and Jinja's Undefined is not JSON-serialisable, so
# omitting it turns the not-found and error branches (which skip
# ``_load_user_settings``) into a 500 rather than a rendered page.
"custom_endpoint": "",
}
try:
from ...news import api as news_api
subscription = news_api.get_subscription(
subscription_id, username=username
)
if not subscription:
return templates.TemplateResponse(
request=request,
name="pages/news-subscription-form.html",
context={
"subscription": None,
"error": "Subscription not found",
"default_settings": default_settings,
"strategies": get_available_strategies(),
},
)
from ...database.session_context import get_user_db_session
with get_user_db_session(username) as db_session:
_load_user_settings(default_settings, db_session, username)
except SettingsValueError:
# Not a subscription loading error: the app's handler names the
# invalid setting.
raise
except Exception:
logger.exception(
f"Error loading subscription {_log_value_preview(subscription_id)}"
)
return templates.TemplateResponse(
request=request,
name="pages/news-subscription-form.html",
context={
"subscription": None,
"error": "Error loading subscription",
"default_settings": default_settings,
"strategies": get_available_strategies(),
},
)
return templates.TemplateResponse(
request=request,
name="pages/news-subscription-form.html",
context={
"subscription": subscription,
"default_settings": default_settings,
"strategies": get_available_strategies(),
},
)
@router.get("/health")
def news_health_check(username: Annotated[str, Depends(require_auth)]):
"""Check if news system is healthy (authenticated users only).
The old public version probed the StorageManager with a hardcoded
`user_id="health_check"` sentinel — leaking infrastructure state
to unauthenticated callers AND creating a spurious DB row on every
invocation. `/api/v1/health` already exists as the public liveness
probe; gate this one behind auth and scope it to the caller.
"""
try:
from ...news.core.storage_manager import StorageManager
storage = StorageManager()
storage.get_user_feed(username, limit=1)
return {
"status": "healthy",
"enabled": True,
"database": "connected",
}
except Exception:
logger.exception("Health check failed")
return JSONResponse(
{
"status": "unhealthy",
"error": "An internal error has occurred.",
},
status_code=500,
)
def _load_user_settings(default_settings, db_session=None, username=None):
"""Load user settings and update default_settings dictionary."""
if not db_session:
return
try:
from ...utilities.db_utils import get_settings_manager
settings_manager = get_settings_manager(db_session, username)
default_settings.update(
{
"iterations": settings_manager.get_setting(
"search.iterations", 3
),
"questions_per_iteration": settings_manager.get_setting(
"search.questions_per_iteration", 5
),
"search_engine": settings_manager.get_setting(
"search.tool", DEFAULT_SEARCH_TOOL
),
"model_provider": settings_manager.get_setting(
"llm.provider", "ollama"
),
"model": settings_manager.get_setting("llm.model", ""),
"search_strategy": settings_manager.get_setting(
"search.search_strategy", "source-based"
),
"custom_endpoint": settings_manager.get_setting(
"llm.openai_endpoint.url", ""
),
# Issue #5204: the news-subscription form's search-engine
# dropdown is scope-aware — it loads the engine list with the
# user's saved egress scope so incompatible options render
# disabled. Pull the saved value so the template can build the
# egress-aware API URL.
"egress_scope": settings_manager.get_setting(
"policy.egress_scope", "adaptive"
),
}
)
except SettingsValueError:
# An invalid configured value must not prefill the form with
# defaults as if they were the saved settings.
raise
except Exception:
logger.warning("Could not load user settings")