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.

refactor(web): activate Ruff FAST002 for FastAPI dependencies (#6058)

LearningCircuit1ca2e4cbc80b
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 3e933859a2..09bb71535a 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -63,10 +63,18 @@ repos:
alias: fastapi-path-parameter-safety
name: Ruff - FastAPI path parameter safety
# FAST003 catches a {path_parameter} that a migrated handler forgot
- # to accept. FAST002 is intentionally omitted: it is a style migration
- # to Annotated, not a correctness gate for this branch.
+ # to accept. Keep it separate from the dependency-style gate below so
+ # each failure names the FastAPI contract that changed.
args: [--select, FAST003]
files: ^src/local_deep_research/web/(fastapi_app\.py|routers/[^/]+\.py)$
+ - id: ruff
+ alias: fastapi-annotated-dependencies
+ name: Ruff - FastAPI Annotated dependencies
+ # Ruff covers decorated/typed route parameters. The local AST hook
+ # below closes its gaps for untyped parameters and dependency-provider
+ # functions without importing the application.
+ args: [--select, FAST002]
+ files: ^src/local_deep_research/web/(fastapi_app\.py|routers/[^/]+\.py|dependencies/[^/]+\.py)$
# Run the formatter.
- id: ruff-format
- repo: https://github.com/rhysd/actionlint
@@ -225,6 +233,14 @@ repos:
files: ^src/local_deep_research/web/(fastapi_app\.py|templates/.*\.html)$
pass_filenames: false
description: "Ensure literal template url_for names exist in FastAPI's explicit _URL_MAP"
+ - id: check-fastapi-default-parameters
+ name: Check FastAPI parameters use Annotated
+ entry: .pre-commit-hooks/check-fastapi-default-parameters.py
+ language: script
+ files: ^src/local_deep_research/web/(fastapi_app\.py|routers/[^/]+\.py|dependencies/[^/]+\.py)$
+ types: [python]
+ description: "Cover FAST002 blind spots by rejecting FastAPI Depends,
+ Query, Form, and related marker calls used as Python defaults"
- id: check-css-class-prefix
name: Check CSS class names have ldr- prefix
entry: .pre-commit-hooks/check-css-class-prefix.py
diff --git a/.pre-commit-hooks/check-fastapi-default-parameters.py b/.pre-commit-hooks/check-fastapi-default-parameters.py
new file mode 100755
index 0000000000..6b0b61c0fa
--- /dev/null
+++ b/.pre-commit-hooks/check-fastapi-default-parameters.py
@@ -0,0 +1,233 @@
+#!/usr/bin/env python3
+"""Reject FastAPI parameter markers used as Python default values.
+
+Ruff's FAST002 intentionally focuses on decorated FastAPI routes and needs a
+type annotation before it can build ``Annotated``. Reusable dependency
+functions and untyped parameters can therefore retain ``= Depends(...)`` (or
+another FastAPI marker) while FAST002 reports a clean tree. This hook covers
+that narrow gap without importing the application or any third-party package.
+"""
+
+from __future__ import annotations
+
+import ast
+import sys
+from collections.abc import Iterable, Sequence
+from pathlib import Path
+from typing import NamedTuple
+
+FASTAPI_MARKERS = frozenset(
+ {
+ "Body",
+ "Cookie",
+ "Depends",
+ "File",
+ "Form",
+ "Header",
+ "Path",
+ "Query",
+ "Security",
+ }
+)
+FASTAPI_MODULES = frozenset({"fastapi", "fastapi.params"})
+
+
+class Diagnostic(NamedTuple):
+ path: Path
+ line: int
+ column: int
+ message: str
+
+ def render(self) -> str:
+ return f"{self.path}:{self.line}:{self.column}: {self.message}"
+
+
+class _Bindings(NamedTuple):
+ direct: dict[str, str]
+ modules: dict[str, str]
+ star_import_lines: tuple[int, ...]
+
+
+def _dotted_name(node: ast.AST) -> tuple[str, ...] | None:
+ parts: list[str] = []
+ while isinstance(node, ast.Attribute):
+ parts.append(node.attr)
+ node = node.value
+ if not isinstance(node, ast.Name):
+ return None
+ parts.append(node.id)
+ return tuple(reversed(parts))
+
+
+def _marker_name(node: ast.AST, bindings: _Bindings) -> str | None:
+ if isinstance(node, ast.Name):
+ return bindings.direct.get(node.id)
+
+ parts = _dotted_name(node)
+ if not parts or len(parts) < 2:
+ return None
+ module = bindings.modules.get(parts[0])
+ if module is None:
+ return None
+ expanded = (*module.split("."), *parts[1:])
+ marker = expanded[-1]
+ prefix = ".".join(expanded[:-1])
+ if prefix in FASTAPI_MODULES and marker in FASTAPI_MARKERS:
+ return marker
+ return None
+
+
+def _import_bindings(tree: ast.Module) -> _Bindings:
+ direct: dict[str, str] = {}
+ modules: dict[str, str] = {}
+ star_import_lines: list[int] = []
+
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ for alias in node.names:
+ if alias.name not in FASTAPI_MODULES:
+ continue
+ local = alias.asname or alias.name.split(".", 1)[0]
+ modules[local] = alias.name if alias.asname else "fastapi"
+ elif isinstance(node, ast.ImportFrom):
+ module = node.module or ""
+ if module not in FASTAPI_MODULES:
+ continue
+ for alias in node.names:
+ if alias.name == "*":
+ star_import_lines.append(node.lineno)
+ elif module == "fastapi" and alias.name == "params":
+ modules[alias.asname or alias.name] = "fastapi.params"
+ elif alias.name in FASTAPI_MARKERS:
+ direct[alias.asname or alias.name] = alias.name
+
+ # Also follow simple module-level aliases such as ``Inject = Depends``.
+ # Repeat to support short alias chains without attempting full data flow.
+ bindings = _Bindings(direct, modules, tuple(star_import_lines))
+ changed = True
+ while changed:
+ changed = False
+ for statement in tree.body:
+ if not isinstance(statement, (ast.Assign, ast.AnnAssign)):
+ continue
+ value = statement.value
+ targets = (
+ statement.targets
+ if isinstance(statement, ast.Assign)
+ else [statement.target]
+ )
+ marker = (
+ _marker_name(value, bindings) if value is not None else None
+ )
+ if marker is None:
+ continue
+ for target in targets:
+ if (
+ isinstance(target, ast.Name)
+ and direct.get(target.id) != marker
+ ):
+ direct[target.id] = marker
+ changed = True
+
+ return bindings
+
+
+def _parameter_defaults(
+ node: ast.FunctionDef | ast.AsyncFunctionDef,
+) -> Iterable[tuple[ast.arg, ast.expr]]:
+ positional = [*node.args.posonlyargs, *node.args.args]
+ padded = [None] * (len(positional) - len(node.args.defaults))
+ for argument, default in zip(
+ positional, [*padded, *node.args.defaults], strict=True
+ ):
+ if default is not None:
+ yield argument, default
+ for argument, default in zip(
+ node.args.kwonlyargs, node.args.kw_defaults, strict=True
+ ):
+ if default is not None:
+ yield argument, default
+
+
+def check_file(path: Path) -> tuple[Diagnostic, ...]:
+ try:
+ source = path.read_text(encoding="utf-8")
+ except (OSError, UnicodeError) as exc:
+ return (Diagnostic(path, 1, 1, f"cannot read Python source: {exc}"),)
+
+ try:
+ tree = ast.parse(source, filename=str(path))
+ except SyntaxError as exc:
+ return (
+ Diagnostic(
+ path,
+ exc.lineno or 1,
+ exc.offset or 1,
+ "cannot verify FastAPI defaults because the file has invalid syntax",
+ ),
+ )
+
+ bindings = _import_bindings(tree)
+ diagnostics = [
+ Diagnostic(
+ path,
+ line,
+ 1,
+ "FastAPI star imports prevent reliable marker resolution; import markers explicitly",
+ )
+ for line in bindings.star_import_lines
+ ]
+
+ for node in ast.walk(tree):
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ for argument, default in _parameter_defaults(node):
+ if not isinstance(default, ast.Call):
+ continue
+ marker = _marker_name(default.func, bindings)
+ if marker is None:
+ continue
+ diagnostics.append(
+ Diagnostic(
+ path,
+ default.lineno,
+ default.col_offset + 1,
+ f"parameter '{argument.arg}' uses {marker}(...) as a default; "
+ f"use Annotated[Type, {marker}(...)] instead",
+ )
+ )
+
+ return tuple(
+ sorted(
+ diagnostics, key=lambda item: (item.line, item.column, item.message)
+ )
+ )
+
+
+def check_paths(paths: Iterable[Path]) -> tuple[Diagnostic, ...]:
+ diagnostics = [item for path in paths for item in check_file(path)]
+ return tuple(
+ sorted(
+ diagnostics,
+ key=lambda item: (
+ str(item.path),
+ item.line,
+ item.column,
+ item.message,
+ ),
+ )
+ )
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ paths = [
+ Path(value) for value in (argv if argv is not None else sys.argv[1:])
+ ]
+ diagnostics = check_paths(paths)
+ for diagnostic in diagnostics:
+ print(diagnostic.render())
+ return int(bool(diagnostics))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/src/local_deep_research/web/dependencies/auth.py b/src/local_deep_research/web/dependencies/auth.py
index e81148c39e..65f508a84e 100644
--- a/src/local_deep_research/web/dependencies/auth.py
+++ b/src/local_deep_research/web/dependencies/auth.py
@@ -5,7 +5,7 @@ Replaces Flask's @login_required decorator and g.db_session / g.current_user
with explicit dependency injection.
"""
-from typing import Generator
+from typing import Annotated, Generator
from fastapi import Depends, HTTPException, Request
from loguru import logger
@@ -151,7 +151,7 @@ def _server_session_valid(request: Request, username: str) -> bool:
def get_db_session_dep(
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
) -> Generator[Session, None, None]:
"""Yield a database session for the authenticated user.
@@ -207,8 +207,8 @@ def get_db_session_dep(
def get_settings_manager_dep(
- db_session: Session = Depends(get_db_session_dep),
- username: str = Depends(require_auth),
+ db_session: Annotated[Session, Depends(get_db_session_dep)],
+ username: Annotated[str, Depends(require_auth)],
):
"""Yield a SettingsManager bound to the current user's DB session."""
return get_settings_manager(db_session, username)
diff --git a/src/local_deep_research/web/routers/api.py b/src/local_deep_research/web/routers/api.py
index ad71b0085a..87c0f99b5e 100644
--- a/src/local_deep_research/web/routers/api.py
+++ b/src/local_deep_research/web/routers/api.py
@@ -26,6 +26,7 @@ from ..services.resource_service import (
from local_deep_research.settings import SettingsManager
from ...security import safe_get, strip_settings_snapshot
from ..dependencies.json_body import json_body_error
+from typing import Annotated
# Create the router
router = APIRouter(prefix="/research/api", tags=["api"])
@@ -36,7 +37,9 @@ router = APIRouter(prefix="/research/api", tags=["api"])
@router.get("/settings/current-config")
-def get_current_config(request: Request, username: str = Depends(require_auth)):
+def get_current_config(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get the current configuration from database settings."""
try:
with get_user_db_session(username) as session:
@@ -75,7 +78,7 @@ def get_current_config(request: Request, username: str = Depends(require_auth)):
# API Routes
@router.post("/start")
async def api_start_research(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""
Start a new research process.
@@ -91,7 +94,9 @@ async def api_start_research(
@router.get("/status/{research_id}")
def api_research_status(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""
Get the status of a research process
@@ -142,7 +147,9 @@ def api_research_status(
@router.post("/terminate/{research_id}")
def api_terminate_research(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""
Terminate a research process
@@ -172,7 +179,9 @@ def api_terminate_research(
@router.get("/resources/{research_id}")
def api_get_resources(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""
Get resources for a specific research.
@@ -194,7 +203,9 @@ def api_get_resources(
@router.post("/resources/{research_id}")
async def api_add_resource(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""
Add a new resource to a research project
@@ -282,7 +293,7 @@ def api_delete_resource(
# non-numeric segment is passed straight through to the service layer
# instead of being rejected as a 422 by the router.
resource_id: int,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""
Delete a resource from a research project
@@ -372,7 +383,7 @@ def _probe_ollama_tags(base_url, timeout=5):
@router.get("/check/ollama_status")
def check_ollama_status(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""
Check if Ollama API is running
@@ -450,7 +461,9 @@ def check_ollama_status(
@router.get("/check/ollama_model")
-def check_ollama_model(request: Request, username: str = Depends(require_auth)):
+def check_ollama_model(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""
Check if the configured Ollama model is available
"""
diff --git a/src/local_deep_research/web/routers/api_v1.py b/src/local_deep_research/web/routers/api_v1.py
index 1d80af2807..9269b8d275 100644
--- a/src/local_deep_research/web/routers/api_v1.py
+++ b/src/local_deep_research/web/routers/api_v1.py
@@ -9,7 +9,7 @@ import inspect
import os
import threading
import time
-from typing import Any, Dict, Optional
+from typing import Any, Dict, Optional, Annotated
try:
import resource as _resource_mod
@@ -89,7 +89,8 @@ _ANALYZE_DOCUMENTS_PARAMS = frozenset(
async def require_api_access(
- request: Request, username: str = Depends(require_auth)
+ request: Request,
+ username: Annotated[str, Depends(require_auth)],
) -> str:
"""Port of main's api_access_control decorator.
@@ -119,7 +120,9 @@ async def require_api_access(
@router.get("/health")
-def health_check(username: str | None = Depends(get_session_username)):
+def health_check(
+ username: Annotated[str | None, Depends(get_session_username)],
+):
"""Health check endpoint (no auth required).
Always returns "ok" if the process can serve a request — but exposes
@@ -221,7 +224,7 @@ def health_check(username: str | None = Depends(get_session_username)):
@router.get("/")
@api_rate_limit
def api_documentation(
- request: Request, username: str = Depends(require_api_access)
+ request: Request, username: Annotated[str, Depends(require_api_access)]
):
"""Provide documentation on available API endpoints.
@@ -403,7 +406,7 @@ def _load_user_context_into_params(
@api_rate_limit
async def api_quick_summary(
request: Request,
- username: str = Depends(require_api_access),
+ username: Annotated[str, Depends(require_api_access)],
):
"""Generate a quick research summary via REST API."""
try:
@@ -500,7 +503,7 @@ async def api_quick_summary(
@api_rate_limit
async def api_generate_report(
request: Request,
- username: str = Depends(require_api_access),
+ username: Annotated[str, Depends(require_api_access)],
):
"""Generate a comprehensive research report via REST API."""
try:
@@ -588,7 +591,7 @@ async def api_generate_report(
@api_rate_limit
async def api_analyze_documents(
request: Request,
- username: str = Depends(require_api_access),
+ username: Annotated[str, Depends(require_api_access)],
):
"""Search and analyze documents in a local collection via REST API."""
try:
diff --git a/src/local_deep_research/web/routers/auth.py b/src/local_deep_research/web/routers/auth.py
index 73aa332a13..ffe7d0a71e 100644
--- a/src/local_deep_research/web/routers/auth.py
+++ b/src/local_deep_research/web/routers/auth.py
@@ -40,6 +40,7 @@ from ...security.url_validator import URLValidator
from ...security.account_lockout import get_account_lockout_manager
from ...security.password_validator import PasswordValidator
from ...security.log_sanitizer import sanitize_for_log
+from typing import Annotated
router = APIRouter(prefix="/auth", tags=["auth"])
@@ -118,7 +119,7 @@ def _disconnect_session_sockets(session_id: str) -> None:
@router.get("/login")
-def login_page(request: Request, next: str = Query("")):
+def login_page(request: Request, next: Annotated[str, Query()] = ""):
"""Login page (GET only)."""
config = load_server_config()
if request.session.get("username"):
@@ -139,10 +140,10 @@ def login_page(request: Request, next: str = Query("")):
@limiter.limit(LOGIN_RATE_LIMIT)
def login(
request: Request,
- username: str = Form(""),
- password: str = Form(""), # noqa: S107
- remember: str = Form("false"),
- next: str = Query(""),
+ username: Annotated[str, Form()] = "",
+ password: Annotated[str, Form()] = "", # noqa: S107
+ remember: Annotated[str, Form()] = "false",
+ next: Annotated[str, Query()] = "",
):
"""Login handler (POST only). Rate limited to prevent brute force."""
config = load_server_config()
@@ -502,7 +503,7 @@ def _log_step_duration(step_label: str, start: float, username: str) -> None:
@limiter.limit(VALIDATE_PASSWORD_RATE_LIMIT)
def validate_password(
request: Request,
- password: str = Form(""), # noqa: S107
+ password: Annotated[str, Form()] = "", # noqa: S107
):
"""Validate password strength via API (used by client-side forms).
@@ -540,10 +541,10 @@ def register_page(request: Request):
@limiter.limit(REGISTRATION_RATE_LIMIT)
def register(
request: Request,
- username: str = Form(""),
- password: str = Form(""), # noqa: S107
- confirm_password: str = Form(""), # noqa: S107
- acknowledge: str = Form("false"),
+ username: Annotated[str, Form()] = "",
+ password: Annotated[str, Form()] = "", # noqa: S107
+ confirm_password: Annotated[str, Form()] = "", # noqa: S107
+ acknowledge: Annotated[str, Form()] = "false",
):
"""Registration handler (POST only)."""
config = load_server_config()
@@ -981,7 +982,7 @@ def check_auth(request: Request):
@router.get("/change-password")
def change_password_page(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""
Change password page (GET only).
@@ -1005,10 +1006,10 @@ def change_password_page(
@limiter.limit(PASSWORD_CHANGE_RATE_LIMIT)
def change_password(
request: Request,
- current_password: str = Form(""), # noqa: S107
- new_password: str = Form(""), # noqa: S107
- confirm_password: str = Form(""), # noqa: S107
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
+ current_password: Annotated[str, Form()] = "", # noqa: S107
+ new_password: Annotated[str, Form()] = "", # noqa: S107
+ confirm_password: Annotated[str, Form()] = "", # noqa: S107
):
"""Change password handler (POST only).
@@ -1218,7 +1219,9 @@ def change_password(
@router.get("/integrity-check")
-def integrity_check(request: Request, username: str = Depends(require_auth)):
+def integrity_check(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""
Check database integrity for current user.
diff --git a/src/local_deep_research/web/routers/benchmark.py b/src/local_deep_research/web/routers/benchmark.py
index f6c447fe70..8bba99c536 100644
--- a/src/local_deep_research/web/routers/benchmark.py
+++ b/src/local_deep_research/web/routers/benchmark.py
@@ -18,6 +18,7 @@ from local_deep_research.settings import SettingsManager
from ...benchmarks.web_api.benchmark_service import benchmark_service
from ..dependencies.json_body import json_body_error
+from typing import Annotated
# Benchmark runs spawn full LLM + search loops (expensive enough that
# rate-limiting them is a DoS defense, not just good manners). Tight
@@ -73,7 +74,7 @@ def _validate_datasets_config(datasets_config):
@router.get("/")
-def index(request: Request, username: str = Depends(require_auth)):
+def index(request: Request, username: Annotated[str, Depends(require_auth)]):
"""Benchmark dashboard page."""
with get_user_db_session(username) as db_session:
@@ -103,7 +104,7 @@ def index(request: Request, username: str = Depends(require_auth)):
@router.get("/results")
-def results(request: Request, username: str = Depends(require_auth)):
+def results(request: Request, username: Annotated[str, Depends(require_auth)]):
"""Benchmark results history page."""
return templates.TemplateResponse(
request=request,
@@ -115,7 +116,7 @@ def results(request: Request, username: str = Depends(require_auth)):
@router.post("/api/start")
@_benchmark_start_limit
async def start_benchmark(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Start a new benchmark run."""
data = await request.json()
@@ -349,7 +350,7 @@ def _start_benchmark_sync(data, username, session_id):
@router.get("/api/running")
def get_running_benchmark(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Check if there's a running benchmark and return its ID."""
try:
@@ -392,7 +393,7 @@ def get_running_benchmark(
def get_benchmark_status(
request: Request,
benchmark_run_id: int,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Get status of a benchmark run."""
try:
@@ -426,7 +427,7 @@ def get_benchmark_status(
def cancel_benchmark(
request: Request,
benchmark_run_id: int,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Cancel a running benchmark."""
try:
@@ -453,7 +454,7 @@ def cancel_benchmark(
@router.get("/api/history")
def get_benchmark_history(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get list of recent benchmark runs."""
try:
@@ -600,7 +601,7 @@ def get_benchmark_history(
def get_benchmark_results(
request: Request,
benchmark_run_id: int,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Get detailed results for a benchmark run."""
try:
@@ -742,7 +743,7 @@ def get_benchmark_results(
def export_benchmark_results(
request: Request,
benchmark_run_id: int,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Get lightweight results for YAML export plus run-level provenance.
@@ -878,7 +879,9 @@ def export_benchmark_results(
@router.get("/api/configs")
-def get_saved_configs(request: Request, username: str = Depends(require_auth)):
+def get_saved_configs(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get list of saved benchmark configurations."""
try:
# Returns built-in default configs (saved configs not yet in DB)
@@ -928,7 +931,7 @@ def get_saved_configs(request: Request, username: str = Depends(require_auth)):
@router.post("/api/start-simple")
@_benchmark_start_limit
async def start_benchmark_simple(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Start a benchmark using current database settings."""
data = await request.json()
@@ -1103,7 +1106,7 @@ def _start_benchmark_simple_sync(data, username, session_id):
@router.post("/api/validate-config")
async def validate_config(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Validate a benchmark configuration.
@@ -1162,7 +1165,9 @@ async def validate_config(
@router.get("/api/search-quality")
@limiter.exempt
-def get_search_quality(request: Request, username: str = Depends(require_auth)):
+def get_search_quality(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get current search quality metrics from rate limiting data."""
try:
from ...database.models import RateLimitEstimate
@@ -1209,7 +1214,7 @@ def get_search_quality(request: Request, username: str = Depends(require_auth)):
def delete_benchmark_run(
request: Request,
benchmark_run_id: int,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Delete a benchmark run and all its results."""
try:
diff --git a/src/local_deep_research/web/routers/chat.py b/src/local_deep_research/web/routers/chat.py
index 4b54a9333c..385d647c23 100644
--- a/src/local_deep_research/web/routers/chat.py
+++ b/src/local_deep_research/web/routers/chat.py
@@ -62,6 +62,7 @@ from ..dependencies.auth import require_auth
from ..dependencies.rate_limit import limiter, _get_client_ip
from ..dependencies.template_helpers import render_template
from ..dependencies.threadpool import run_db_sync
+from typing import Annotated
router = APIRouter(tags=["chat"])
@@ -270,8 +271,8 @@ def _cleanup_chat_send_rows(
@router.get("/chat/{session_id}", include_in_schema=False)
def chat_page(
request: Request,
+ username: Annotated[str, Depends(require_auth)],
session_id: str | None = None,
- username: str = Depends(require_auth),
):
"""Render the chat page.
@@ -293,7 +294,7 @@ def chat_page(
# NAT/proxy share one bucket and can DoS each other for legitimate chat use.
@limiter.limit("20 per minute", key_func=_chat_user_key)
async def create_session(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Create a new chat session."""
data = await _json_object_body(request)
@@ -389,7 +390,7 @@ async def create_session(
async def generate_session_title(
request: Request,
session_id: str,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Regenerate the session title using the configured LLM.
@@ -450,7 +451,7 @@ async def generate_session_title(
@router.get("/api/chat/sessions")
async def list_sessions(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""List chat sessions for the current user.
@@ -497,7 +498,7 @@ async def list_sessions(
async def get_session(
request: Request,
session_id: str,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Get a specific chat session."""
@@ -530,7 +531,7 @@ async def get_session(
async def update_session(
request: Request,
session_id: str,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Update a chat session (title, archive, delete)."""
data = await _json_object_body(request)
@@ -638,7 +639,7 @@ async def update_session(
async def delete_session(
request: Request,
session_id: str,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Delete a chat session permanently."""
@@ -674,7 +675,7 @@ async def delete_session(
async def get_messages(
request: Request,
session_id: str,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Get messages for a chat session (cursor-paginated, ASC)."""
@@ -751,7 +752,7 @@ async def get_messages(
async def send_message(
request: Request,
session_id: str,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Send a message in a chat session, optionally triggering research.
@@ -1319,7 +1320,7 @@ async def delete_attempt(
request: Request,
session_id: str,
research_id: str,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Delete a single chat attempt (user message + research + response).
@@ -1373,7 +1374,7 @@ async def retry_attempt(
request: Request,
session_id: str,
research_id: str,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Retry a chat attempt: delete the old turn, re-submit same content.
diff --git a/src/local_deep_research/web/routers/context_overflow_api.py b/src/local_deep_research/web/routers/context_overflow_api.py
index 0ec8370f8b..a7b001e743 100644
--- a/src/local_deep_research/web/routers/context_overflow_api.py
+++ b/src/local_deep_research/web/routers/context_overflow_api.py
@@ -12,6 +12,7 @@ from ...database.session_context import get_user_db_session
from ...database.models import TokenUsage
from ...metrics.query_utils import get_context_overflow_truncation_summary
from ...settings import SettingsManager
+from typing import Annotated
#: Upper bound on ``page``. Beyond this the OFFSET is meaningless and a
#: crafted value overflows SQLite's signed 64-bit integer.
@@ -26,7 +27,7 @@ router = APIRouter(tags=["context_overflow_api"])
@router.get("/api/context-overflow")
def get_context_overflow_metrics(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get context overflow metrics for the current user."""
try:
@@ -376,7 +377,9 @@ def get_context_overflow_metrics(
@router.get("/api/research/{research_id}/context-overflow")
def get_research_context_overflow(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get context overflow metrics for a specific research."""
try:
diff --git a/src/local_deep_research/web/routers/followup.py b/src/local_deep_research/web/routers/followup.py
index a39f4d3e01..ce89cfe0d9 100644
--- a/src/local_deep_research/web/routers/followup.py
+++ b/src/local_deep_research/web/routers/followup.py
@@ -17,6 +17,7 @@ from ...followup_research.models import FollowUpRequest
from ...utilities.url_utils import is_safe_custom_llm_endpoint
from ..auth.password_utils import resolve_user_password
+from typing import Annotated
# Create the router
router = APIRouter(prefix="/api/followup", tags=["followup"])
@@ -28,7 +29,7 @@ router = APIRouter(prefix="/api/followup", tags=["followup"])
@router.post("/prepare")
async def prepare_followup(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""
Prepare a follow-up research by loading parent context.
@@ -138,7 +139,7 @@ async def prepare_followup(
@router.post("/start")
async def start_followup(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""
Start a follow-up research.
diff --git a/src/local_deep_research/web/routers/history.py b/src/local_deep_research/web/routers/history.py
index 93984e1207..a73120b579 100644
--- a/src/local_deep_research/web/routers/history.py
+++ b/src/local_deep_research/web/routers/history.py
@@ -27,6 +27,7 @@ from ..services.research_service import get_research_strategy
from .research import _research_not_found
from ...security import filter_research_metadata, strip_settings_snapshot
+from typing import Annotated
# Create the router for the history routes
router = APIRouter(prefix="/history", tags=["history"])
@@ -39,7 +40,9 @@ router = APIRouter(prefix="/history", tags=["history"])
@router.get("/")
-def history_page(request: Request, username: str = Depends(require_auth)):
+def history_page(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Render the history page"""
return templates.TemplateResponse(
request=request, name="pages/history.html", context={"request": request}
@@ -47,7 +50,9 @@ def history_page(request: Request, username: str = Depends(require_auth)):
@router.get("/api")
-def get_history(request: Request, username: str = Depends(require_auth)):
+def get_history(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get the research history JSON data"""
# Flask parsed these with `type=int`, which falls back to the default on
@@ -164,7 +169,9 @@ def get_history(request: Request, username: str = Depends(require_auth)):
@router.get("/status/{research_id}")
@limiter.exempt
def get_research_status(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
with get_user_db_session(username) as db_session:
@@ -217,7 +224,9 @@ def get_research_status(
@router.get("/details/{research_id}")
def get_research_details(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get detailed progress log for a specific research"""
@@ -302,7 +311,9 @@ def get_research_details(
@router.get("/report/{research_id}")
def get_report(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
with get_user_db_session(username) as db_session:
research = (
@@ -370,7 +381,9 @@ def get_report(
@router.get("/markdown/{research_id}")
def get_markdown(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get markdown export for a specific research"""
with get_user_db_session(username) as db_session:
@@ -406,7 +419,9 @@ def get_markdown(
@router.get("/logs/{research_id}")
def get_research_logs(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get logs for a specific research ID.
@@ -463,7 +478,9 @@ def get_research_logs(
@router.get("/log_count/{research_id}")
def get_log_count(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get the total number of logs for a specific research ID"""
# Verify ownership before exposing the count.
diff --git a/src/local_deep_research/web/routers/library.py b/src/local_deep_research/web/routers/library.py
index d64a89f306..1744f2dd79 100644
--- a/src/local_deep_research/web/routers/library.py
+++ b/src/local_deep_research/web/routers/library.py
@@ -48,6 +48,7 @@ from ...utilities.db_utils import get_settings_manager
from ...config.paths import get_library_directory
from ...web.exceptions import AuthenticationRequiredError
from ..dependencies.json_body import json_body_error
+from typing import Annotated
# Create the router
router = APIRouter(prefix="/library", tags=["library"])
@@ -128,7 +129,7 @@ def get_authenticated_user_password(
@router.get("/")
def library_page(
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Main library page showing downloaded documents."""
import math
@@ -243,7 +244,9 @@ def library_page(
@router.get("/document/{document_id}")
def document_details_page(
- request: Request, document_id, username: str = Depends(require_auth)
+ request: Request,
+ document_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Document details page showing all metadata and links."""
service = LibraryService(username)
@@ -269,7 +272,7 @@ def document_details_page(
@router.get("/download-manager")
def download_manager_page(
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Download manager page for selecting and downloading research PDFs."""
import math
@@ -335,7 +338,9 @@ def download_manager_page(
@router.get("/api/stats")
-def get_library_stats(request: Request, username: str = Depends(require_auth)):
+def get_library_stats(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get library statistics."""
service = LibraryService(username)
return service.get_library_stats()
@@ -343,7 +348,7 @@ def get_library_stats(request: Request, username: str = Depends(require_auth)):
@router.get("/api/collections/list")
def get_collections_list(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get list of all collections for dropdown selection."""
@@ -366,7 +371,9 @@ def get_collections_list(
@router.get("/api/documents")
-def get_documents(request: Request, username: str = Depends(require_auth)):
+def get_documents(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get documents with filtering."""
service = LibraryService(username)
@@ -404,7 +411,9 @@ def get_documents(request: Request, username: str = Depends(require_auth)):
@router.post("/api/document/{document_id}/favorite")
def toggle_favorite(
- request: Request, document_id, username: str = Depends(require_auth)
+ request: Request,
+ document_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Toggle favorite status of a document."""
service = LibraryService(username)
@@ -414,7 +423,9 @@ def toggle_favorite(
@router.get("/api/document/{document_id}/pdf-url")
def get_pdf_url(
- request: Request, document_id, username: str = Depends(require_auth)
+ request: Request,
+ document_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get URL for viewing PDF."""
# Return URL that will serve the PDF
@@ -543,7 +554,9 @@ def _serve_pdf(
@router.get("/document/{document_id}/pdf")
def view_pdf_page(
- request: Request, document_id, username: str = Depends(require_auth)
+ request: Request,
+ document_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Page for viewing PDF file - uses PDFStorageManager for retrieval."""
return _serve_pdf(request, document_id, username, html_errors=True)
@@ -551,7 +564,9 @@ def view_pdf_page(
@router.get("/api/document/{document_id}/pdf")
def serve_pdf_api(
- request: Request, document_id, username: str = Depends(require_auth)
+ request: Request,
+ document_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""API endpoint for serving PDF file (kept for backward compatibility).
@@ -565,7 +580,9 @@ def serve_pdf_api(
@router.get("/document/{document_id}/txt")
def view_text_page(
- request: Request, document_id, username: str = Depends(require_auth)
+ request: Request,
+ document_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Page for viewing text content."""
@@ -609,7 +626,9 @@ def view_text_page(
@router.get("/api/document/{document_id}/text")
def serve_text_api(
- request: Request, document_id, username: str = Depends(require_auth)
+ request: Request,
+ document_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""API endpoint for serving text content (kept for backward compatibility)."""
@@ -642,7 +661,9 @@ def serve_text_api(
@router.post("/api/open-folder")
-def open_folder(request: Request, username: str = Depends(require_auth)):
+def open_folder(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Open folder containing a document.
Security: This endpoint is disabled for server deployments.
@@ -664,7 +685,7 @@ def download_single_resource(
# non-numeric segment is passed straight through to the service layer
# instead of being rejected as a 422 by the router.
resource_id: int,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Download a single resource."""
user_password = get_authenticated_user_password(username)
@@ -699,7 +720,7 @@ def download_text_single(
# non-numeric segment is passed straight through to the service layer
# instead of being rejected as a 422 by the router.
resource_id: int,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Download a single resource as text file."""
try:
@@ -729,7 +750,9 @@ def download_text_single(
@router.post("/api/download-all-text")
-def download_all_text(request: Request, username: str = Depends(require_auth)):
+def download_all_text(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Download all undownloaded resources as text files."""
# Capture Flask session ID to avoid scoping issues in nested function
session_id = request.session.get("session_id")
@@ -868,7 +891,9 @@ def download_all_text(request: Request, username: str = Depends(require_auth)):
@router.post("/api/download-research/{research_id}")
async def download_research_pdfs(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Queue all PDFs from a research session for download."""
user_password = get_authenticated_user_password(username)
@@ -965,7 +990,7 @@ def _finalize_download_queue_item(db_session, queue_item_id, success):
@router.post("/api/download-bulk")
async def download_bulk(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Download PDFs or extract text from multiple research sessions."""
data = await request.json()
@@ -1290,7 +1315,9 @@ async def download_bulk(
@router.get("/api/research-list")
-def get_research_list(request: Request, username: str = Depends(require_auth)):
+def get_research_list(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get the lightweight research list used to populate a dropdown.
Deliberately NOT ``get_research_list_with_stats``: that runs a 3-table
@@ -1304,7 +1331,9 @@ def get_research_list(request: Request, username: str = Depends(require_auth)):
@router.post("/api/sync-library")
-def sync_library(request: Request, username: str = Depends(require_auth)):
+def sync_library(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Sync library database with filesystem."""
service = LibraryService(username)
return service.sync_library_with_filesystem()
@@ -1312,7 +1341,7 @@ def sync_library(request: Request, username: str = Depends(require_auth)):
@router.post("/api/mark-redownload")
async def mark_for_redownload(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Mark documents for re-download."""
data = await request.json()
@@ -1337,7 +1366,7 @@ async def mark_for_redownload(
@router.post("/api/queue-all-undownloaded")
def queue_all_undownloaded(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Queue all articles that haven't been downloaded yet."""
@@ -1506,7 +1535,9 @@ def queue_all_undownloaded(
@router.get("/api/get-research-sources/{research_id}")
def get_research_sources(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get all sources for a research with snippets."""
@@ -1567,7 +1598,7 @@ def get_research_sources(
@router.post("/api/check-downloads")
async def check_downloads(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Check download status for a list of URLs."""
data = await request.json()
@@ -1619,7 +1650,7 @@ async def check_downloads(
@router.post("/api/download-source")
async def download_source(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Download a single source from a research."""
user_password = get_authenticated_user_password(username)
diff --git a/src/local_deep_research/web/routers/library_delete.py b/src/local_deep_research/web/routers/library_delete.py
index ba842a47cd..87492066ac 100644
--- a/src/local_deep_research/web/routers/library_delete.py
+++ b/src/local_deep_research/web/routers/library_delete.py
@@ -30,6 +30,7 @@ from ...research_library.deletion.services.collection_deletion import (
from ...research_library.deletion.services.bulk_deletion import (
BulkDeletionService,
)
+from typing import Annotated
router = APIRouter(prefix="/library/api", tags=["delete"])
# NOTE: Routes use username (not .get()) intentionally.
@@ -122,7 +123,9 @@ async def _validate_document_ids(request: Request):
@router.delete("/document/{document_id}")
def delete_document(
- request: Request, document_id, username: str = Depends(require_auth)
+ request: Request,
+ document_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""
Delete a document and all related data.
@@ -152,7 +155,9 @@ def delete_document(
@router.delete("/document/{document_id}/blob")
def delete_document_blob(
- request: Request, document_id, username: str = Depends(require_auth)
+ request: Request,
+ document_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""
Delete PDF binary but keep document metadata and text content.
@@ -190,7 +195,9 @@ def delete_document_blob(
@router.get("/document/{document_id}/preview")
def get_document_deletion_preview(
- request: Request, document_id, username: str = Depends(require_auth)
+ request: Request,
+ document_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""
Get a preview of what will be deleted.
@@ -222,7 +229,7 @@ def remove_document_from_collection(
request: Request,
collection_id,
document_id,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""
Remove document from a collection.
@@ -259,7 +266,9 @@ def remove_document_from_collection(
@router.delete("/collections/{collection_id}")
def delete_collection(
- request: Request, collection_id, username: str = Depends(require_auth)
+ request: Request,
+ collection_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""
Delete a collection and clean up all related data.
@@ -298,7 +307,9 @@ def delete_collection(
@router.delete("/collections/{collection_id}/index")
def delete_collection_index(
- request: Request, collection_id, username: str = Depends(require_auth)
+ request: Request,
+ collection_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""
Delete only the RAG index for a collection, keeping the collection itself.
@@ -322,7 +333,9 @@ def delete_collection_index(
@router.get("/collections/{collection_id}/preview")
def get_collection_deletion_preview(
- request: Request, collection_id, username: str = Depends(require_auth)
+ request: Request,
+ collection_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""
Get a preview of what will be deleted.
@@ -351,7 +364,7 @@ def get_collection_deletion_preview(
@router.delete("/documents/bulk")
async def delete_documents_bulk(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""
Delete multiple documents at once.
@@ -383,7 +396,7 @@ async def delete_documents_bulk(
@router.delete("/documents/blobs")
async def delete_documents_blobs_bulk(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""
Delete PDF binaries for multiple documents.
@@ -414,7 +427,9 @@ async def delete_documents_blobs_bulk(
@router.delete("/collection/{collection_id}/documents/bulk")
async def remove_documents_from_collection_bulk(
- request: Request, collection_id, username: str = Depends(require_auth)
+ request: Request,
+ collection_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""
Remove multiple documents from a collection.
@@ -446,7 +461,7 @@ async def remove_documents_from_collection_bulk(
@router.post("/documents/preview")
async def get_bulk_deletion_preview(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""
Get a preview of what will be affected by a bulk operation.
diff --git a/src/local_deep_research/web/routers/library_search.py b/src/local_deep_research/web/routers/library_search.py
index 8daa425dbe..b030cf676b 100644
--- a/src/local_deep_research/web/routers/library_search.py
+++ b/src/local_deep_research/web/routers/library_search.py
@@ -16,6 +16,7 @@ from ...database.models.library import Collection, Document
from ...research_library.utils import handle_api_error
from ..dependencies.json_body import json_body_error
+from typing import Annotated
router = APIRouter(prefix="/library", tags=["search"])
@@ -26,7 +27,7 @@ router = APIRouter(prefix="/library", tags=["search"])
@router.get("/api/research-history/collection")
def get_research_history_collection(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""
Get the Research History collection info and indexing status.
@@ -110,7 +111,7 @@ def get_research_history_collection(
@router.post("/api/research-history/convert-all")
async def convert_all_research(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""
Convert all completed research entries into library Documents.
@@ -166,7 +167,9 @@ async def convert_all_research(
@router.post("/api/research/{research_id}/add-to-collection")
async def add_research_to_collection(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""
Add a research entry to a specific collection.
@@ -267,7 +270,9 @@ def _add_research_to_collection_sync(data, research_id, username, session_id):
@router.post("/api/collections/{collection_id}/search")
async def search_collection(
- request: Request, collection_id, username: str = Depends(require_auth)
+ request: Request,
+ collection_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Search any collection using semantic similarity.
diff --git a/src/local_deep_research/web/routers/metrics.py b/src/local_deep_research/web/routers/metrics.py
index d8dfa7dc37..c19a4abb1f 100644
--- a/src/local_deep_research/web/routers/metrics.py
+++ b/src/local_deep_research/web/routers/metrics.py
@@ -10,7 +10,7 @@ from ..dependencies.rate_limit import limiter, _user_key
from ..template_config import templates
from datetime import datetime, timedelta, UTC
-from typing import Any
+from typing import Any, Annotated
from urllib.parse import urlparse
from loguru import logger
@@ -776,7 +776,9 @@ def get_rate_limiting_analytics(period="30d", username=None):
@router.get("/")
-def metrics_dashboard(request: Request, username: str = Depends(require_auth)):
+def metrics_dashboard(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Render the metrics dashboard page."""
return templates.TemplateResponse(
request=request, name="pages/metrics.html", context={"request": request}
@@ -785,7 +787,7 @@ def metrics_dashboard(request: Request, username: str = Depends(require_auth)):
@router.get("/context-overflow")
def context_overflow_page(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Context overflow analytics page."""
return templates.TemplateResponse(
@@ -796,7 +798,9 @@ def context_overflow_page(
@router.get("/api/metrics")
-def api_metrics(request: Request, username: str = Depends(require_auth)):
+def api_metrics(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get overall metrics data."""
logger.debug("api_metrics endpoint called")
try:
@@ -916,7 +920,7 @@ def api_metrics(request: Request, username: str = Depends(require_auth)):
@router.get("/api/rate-limiting")
def get_rate_limiting_metrics(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get detailed rate limiting metrics."""
logger.info("DEBUG: get_rate_limiting_metrics endpoint called")
@@ -943,7 +947,7 @@ def get_rate_limiting_metrics(
@router.get("/api/rate-limiting/current")
def api_current_rate_limits(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get current rate limit estimates for all engines."""
try:
@@ -993,7 +997,9 @@ def api_current_rate_limits(
@router.get("/api/metrics/research/{research_id}/links")
def api_research_link_metrics(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get link analytics for a specific research."""
try:
@@ -1116,7 +1122,9 @@ def api_research_link_metrics(
@router.get("/api/metrics/research/{research_id}")
def api_research_metrics(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get metrics for a specific research."""
try:
@@ -1138,7 +1146,9 @@ def api_research_metrics(
@router.get("/api/metrics/research/{research_id}/timeline")
def api_research_timeline_metrics(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get timeline metrics for a specific research."""
try:
@@ -1160,7 +1170,9 @@ def api_research_timeline_metrics(
@router.get("/api/metrics/research/{research_id}/search")
def api_research_search_metrics(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get search metrics for a specific research."""
try:
@@ -1182,7 +1194,7 @@ def api_research_search_metrics(
@router.get("/api/metrics/enhanced")
def api_enhanced_metrics(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get enhanced Phase 1 tracking metrics."""
try:
@@ -1229,7 +1241,9 @@ def api_enhanced_metrics(
@router.get("/api/ratings/{research_id}")
def api_get_research_rating(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get rating for a specific research session."""
try:
@@ -1262,7 +1276,9 @@ def api_get_research_rating(
@router.post("/api/ratings/{research_id}")
async def api_save_research_rating(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Save or update rating for a specific research session."""
# Parsed outside the try/except below: a malformed body must raise
@@ -1372,7 +1388,9 @@ async def api_save_research_rating(
@router.get("/star-reviews")
-def star_reviews(request: Request, username: str = Depends(require_auth)):
+def star_reviews(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Display star reviews metrics page."""
return templates.TemplateResponse(
request=request,
@@ -1382,7 +1400,9 @@ def star_reviews(request: Request, username: str = Depends(require_auth)):
@router.get("/costs")
-def cost_analytics(request: Request, username: str = Depends(require_auth)):
+def cost_analytics(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Display cost analytics page."""
return templates.TemplateResponse(
request=request,
@@ -1392,7 +1412,9 @@ def cost_analytics(request: Request, username: str = Depends(require_auth)):
@router.get("/api/star-reviews")
-def api_star_reviews(request: Request, username: str = Depends(require_auth)):
+def api_star_reviews(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get star reviews analytics data."""
try:
period = request.query_params.get("period", "30d")
@@ -1823,7 +1845,9 @@ def api_star_reviews(request: Request, username: str = Depends(require_auth)):
@router.get("/api/pricing")
-def api_pricing(request: Request, username: str = Depends(require_auth)):
+def api_pricing(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get current LLM pricing data."""
try:
from ...metrics.pricing.pricing_fetcher import PricingFetcher
@@ -1846,7 +1870,9 @@ def api_pricing(request: Request, username: str = Depends(require_auth)):
@router.get("/api/pricing/{model_name}")
def api_model_pricing(
- request: Request, model_name, username: str = Depends(require_auth)
+ request: Request,
+ model_name,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get pricing for a specific model."""
try:
@@ -1880,7 +1906,7 @@ def api_model_pricing(
@router.post("/api/cost-calculation")
async def api_cost_calculation(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Calculate cost for token usage."""
# Parsed outside the try/except below: a malformed body must raise
@@ -1933,7 +1959,9 @@ async def api_cost_calculation(
@router.get("/api/research-costs/{research_id}")
def api_research_costs(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get cost analysis for a specific research session."""
try:
@@ -2010,7 +2038,9 @@ def api_research_costs(
@router.get("/api/cost-analytics")
-def api_cost_analytics(request: Request, username: str = Depends(require_auth)):
+def api_cost_analytics(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get cost analytics across all research sessions."""
try:
period = request.query_params.get("period", "30d")
@@ -2159,7 +2189,9 @@ def api_cost_analytics(request: Request, username: str = Depends(require_auth)):
@router.get("/links")
-def link_analytics(request: Request, username: str = Depends(require_auth)):
+def link_analytics(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Display link analytics page."""
return templates.TemplateResponse(
request=request,
@@ -2169,7 +2201,9 @@ def link_analytics(request: Request, username: str = Depends(require_auth)):
@router.get("/api/link-analytics")
-def api_link_analytics(request: Request, username: str = Depends(require_auth)):
+def api_link_analytics(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get link analytics data."""
try:
period = request.query_params.get("period", "30d")
@@ -2196,7 +2230,7 @@ def api_link_analytics(request: Request, username: str = Depends(require_auth)):
@router.get("/api/domain-classifications")
def api_get_domain_classifications(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get all domain classifications."""
classifier = None
@@ -2228,7 +2262,7 @@ def api_get_domain_classifications(
@router.get("/api/domain-classifications/summary")
def api_get_classifications_summary(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get summary of domain classifications by category."""
classifier = None
@@ -2253,7 +2287,7 @@ def api_get_classifications_summary(
@router.post("/api/domain-classifications/classify")
async def api_classify_domains(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Trigger classification of a specific domain or batch classification."""
data = await request.json()
@@ -2332,7 +2366,7 @@ async def api_classify_domains(
@router.get("/api/domain-classifications/progress")
def api_classification_progress(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get progress of domain classification task."""
try:
@@ -2408,7 +2442,9 @@ _journals_read_limit = limiter.shared_limit(
@router.get("/journals")
-def journal_quality(request: Request, username: str = Depends(require_auth)):
+def journal_quality(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Display journal quality dashboard."""
return templates.TemplateResponse(
request=request,
@@ -2419,7 +2455,7 @@ def journal_quality(request: Request, username: str = Depends(require_auth)):
@router.get("/api/journal-data/status")
def api_journal_data_status(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get status of downloadable journal data files."""
try:
@@ -2438,7 +2474,7 @@ def api_journal_data_status(
@router.post("/api/journal-data/download")
@_journal_data_limit
async def api_journal_data_download(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Trigger download/update of journal data files.
@@ -2599,7 +2635,7 @@ _MAX_PAGE = 10_000
@router.get("/api/journals")
@_journals_read_limit
def api_journal_quality(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get journal quality data with server-side pagination and filtering.
@@ -2823,7 +2859,7 @@ def _lookup_journal_llm_quality(
@router.get("/api/journals/user-research")
@_journals_read_limit
def api_user_research_journals(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get journals from the user's own research sessions.
@@ -2993,7 +3029,7 @@ def api_user_research_journals(
def api_research_journals(
request: Request,
research_id: str,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Get journals encountered in a single research session.
diff --git a/src/local_deep_research/web/routers/news_flask_api.py b/src/local_deep_research/web/routers/news_flask_api.py
index 1b0b66ae8c..f59b80348f 100644
--- a/src/local_deep_research/web/routers/news_flask_api.py
+++ b/src/local_deep_research/web/routers/news_flask_api.py
@@ -16,7 +16,7 @@ from ..dependencies.rate_limit import limiter
from ..dependencies.threadpool import run_db_sync
import uuid
-from typing import Any
+from typing import Any, Annotated
from loguru import logger
@@ -353,7 +353,7 @@ def _is_valid_uuid(value: str) -> bool:
@router.get("/feed")
def get_news_feed(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
) -> Any:
"""
Get personalized news feed for user.
@@ -453,7 +453,7 @@ def get_news_feed(
@router.post("/subscribe")
@_news_create_limit
async def create_subscription(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
) -> Any:
"""
Create a new subscription for user.
@@ -551,7 +551,7 @@ async def create_subscription(
@router.post("/vote")
async def vote_on_news(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
) -> Any:
"""
Submit vote on a news item.
@@ -603,7 +603,7 @@ async def vote_on_news(
@router.post("/feedback/batch")
async def get_batch_feedback(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
) -> Any:
"""
Get feedback (votes) for multiple news cards.
@@ -667,7 +667,9 @@ async def get_batch_feedback(
@router.post("/feedback/{card_id}")
@_news_feedback_limit
async def submit_feedback(
- card_id: str, request: Request, username: str = Depends(require_auth)
+ card_id: str,
+ request: Request,
+ username: Annotated[str, Depends(require_auth)],
) -> Any:
"""
Submit feedback (vote) for a news card.
@@ -719,7 +721,9 @@ async def submit_feedback(
@router.post("/research/{card_id}")
@_news_research_limit
async def research_news_item(
- card_id: str, request: Request, username: str = Depends(require_auth)
+ card_id: str,
+ request: Request,
+ username: Annotated[str, Depends(require_auth)],
) -> Any:
"""
Perform deeper research on a news item.
@@ -757,7 +761,7 @@ async def research_news_item(
@router.get("/subscriptions/current")
def get_current_user_subscriptions(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
) -> Any:
"""Get all subscriptions for current user."""
try:
@@ -796,7 +800,7 @@ def get_current_user_subscriptions(
def get_subscription(
subscription_id: str,
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
) -> Any:
"""Get a single subscription by ID."""
try:
@@ -835,7 +839,7 @@ def get_subscription(
async def update_subscription(
subscription_id: str,
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
) -> Any:
"""Update a subscription."""
try:
@@ -909,7 +913,7 @@ async def update_subscription(
def delete_subscription(
subscription_id: str,
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
) -> Any:
"""Delete a subscription."""
try:
@@ -939,7 +943,7 @@ def delete_subscription(
def run_subscription_now(
subscription_id: str,
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
) -> Any:
"""Manually trigger a subscription to run now."""
try:
@@ -1060,7 +1064,7 @@ def run_subscription_now(
def get_subscription_history(
subscription_id: str,
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
) -> Any:
"""Get research history for a subscription."""
try:
@@ -1101,7 +1105,7 @@ def get_subscription_history(
@router.post("/preferences")
@_news_preferences_limit
async def save_preferences(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
) -> Any:
"""Save user preferences for news."""
try:
@@ -1135,7 +1139,7 @@ async def save_preferences(
@router.get("/categories")
def get_categories(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
) -> Any:
"""Get news category distribution."""
from ...news.exceptions import NotImplementedException
@@ -1166,7 +1170,7 @@ def get_categories(
@router.get("/scheduler/status")
def get_scheduler_status(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
) -> Any:
"""Get activity-based scheduler status."""
try:
@@ -1264,8 +1268,8 @@ def get_scheduler_status(
@router.post("/scheduler/start")
def start_scheduler(
request: Request,
- username: str = Depends(require_auth),
- _gate: None = Depends(require_scheduler_control),
+ username: Annotated[str, Depends(require_auth)],
+ _gate: Annotated[None, Depends(require_scheduler_control)],
) -> Any:
"""Start the subscription scheduler."""
try:
@@ -1300,8 +1304,8 @@ def start_scheduler(
@router.post("/scheduler/stop")
def stop_scheduler(
request: Request,
- username: str = Depends(require_auth),
- _gate: None = Depends(require_scheduler_control),
+ username: Annotated[str, Depends(require_auth)],
+ _gate: Annotated[None, Depends(require_scheduler_control)],
) -> Any:
"""Stop the subscription scheduler."""
try:
@@ -1329,8 +1333,8 @@ def stop_scheduler(
@router.post("/scheduler/check-now")
def check_subscriptions_now(
request: Request,
- username: str = Depends(require_auth),
- _gate: None = Depends(require_scheduler_control),
+ username: Annotated[str, Depends(require_auth)],
+ _gate: Annotated[None, Depends(require_scheduler_control)],
) -> Any:
"""Manually trigger subscription checking."""
try:
@@ -1393,8 +1397,8 @@ def check_subscriptions_now(
@router.post("/scheduler/cleanup-now")
def trigger_cleanup(
request: Request,
- username: str = Depends(require_auth),
- _gate: None = Depends(require_scheduler_control),
+ username: Annotated[str, Depends(require_auth)],
+ _gate: Annotated[None, Depends(require_scheduler_control)],
) -> Any:
"""Manually trigger cleanup job."""
try:
@@ -1439,7 +1443,7 @@ def trigger_cleanup(
@router.get("/scheduler/users")
def get_active_users(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
) -> Any:
"""Get summary of active user sessions."""
try:
@@ -1465,7 +1469,7 @@ def get_active_users(
@router.get("/scheduler/stats")
def scheduler_stats(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
) -> Any:
"""Get scheduler statistics and state."""
try:
@@ -1534,7 +1538,7 @@ def scheduler_stats(
@router.post("/check-overdue")
def check_overdue_subscriptions(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Check and run all overdue subscriptions for the current user."""
try:
@@ -1681,7 +1685,9 @@ def check_overdue_subscriptions(
# Folder and subscription management routes
@router.get("/subscription/folders")
-def get_folders(request: Request, username: str = Depends(require_auth)):
+def get_folders(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get all folders for the current user"""
try:
user_id = username
@@ -1701,7 +1707,7 @@ def get_folders(request: Request, username: str = Depends(require_auth)):
@router.post("/subscription/folders")
async def create_folder(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Create a new folder"""
data, _body_err = await read_json_dict(
@@ -1749,7 +1755,7 @@ async def create_folder(
@router.put("/subscription/folders/{folder_id}")
async def update_folder(
- request: Request, folder_id, username: str = Depends(require_auth)
+ request: Request, folder_id, username: Annotated[str, Depends(require_auth)]
):
"""Update a folder"""
data, _body_err = await read_json_dict(
@@ -1782,7 +1788,7 @@ async def update_folder(
@router.delete("/subscription/folders/{folder_id}")
def delete_folder(
- request: Request, folder_id, username: str = Depends(require_auth)
+ request: Request, folder_id, username: Annotated[str, Depends(require_auth)]
):
"""Delete a folder"""
try:
@@ -1808,7 +1814,7 @@ def delete_folder(
@router.get("/subscription/subscriptions/organized")
def get_subscriptions_organized(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get subscriptions organized by folder"""
try:
@@ -1849,7 +1855,9 @@ def get_subscriptions_organized(
@router.put("/subscription/subscriptions/{subscription_id}")
async def update_subscription_folder(
- request: Request, subscription_id, username: str = Depends(require_auth)
+ request: Request,
+ subscription_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Update a subscription (mainly for folder assignment)"""
data, _body_err = await read_json_dict(
@@ -1983,7 +1991,7 @@ def _update_subscription_folder_sync(data, subscription_id, username):
@router.get("/subscription/stats")
def get_subscription_stats(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get subscription statistics"""
try:
@@ -2001,7 +2009,9 @@ def get_subscription_stats(
@router.get("/search-history")
-def get_search_history(request: Request, username: str = Depends(require_auth)):
+def get_search_history(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get search history for current user."""
try:
# Get search history from user's encrypted database
@@ -2029,7 +2039,7 @@ def get_search_history(request: Request, username: str = Depends(require_auth)):
@router.post("/search-history")
async def add_search_history(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Add a search to the history."""
data = await request.json()
@@ -2081,7 +2091,7 @@ async def add_search_history(
@router.delete("/search-history")
def clear_search_history(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Clear all search history for current user."""
try:
diff --git a/src/local_deep_research/web/routers/news_pages.py b/src/local_deep_research/web/routers/news_pages.py
index 44ef38f66f..8792c44a56 100644
--- a/src/local_deep_research/web/routers/news_pages.py
+++ b/src/local_deep_research/web/routers/news_pages.py
@@ -10,12 +10,15 @@ from loguru import logger
from ...constants import DEFAULT_SEARCH_TOOL, get_available_strategies
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: str = Depends(require_auth)):
+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
@@ -35,7 +38,9 @@ def news_page(request: Request, username: str = Depends(require_auth)):
@router.get("/subscriptions")
-def subscriptions_page(request: Request, username: str = Depends(require_auth)):
+def subscriptions_page(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Render the subscriptions management page."""
return templates.TemplateResponse(
request=request,
@@ -46,7 +51,7 @@ def subscriptions_page(request: Request, username: str = Depends(require_auth)):
@router.get("/subscriptions/new")
def new_subscription_page(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Render the create subscription page."""
@@ -89,7 +94,7 @@ def new_subscription_page(
def edit_subscription_page(
request: Request,
subscription_id: str,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Render the edit subscription page."""
@@ -162,7 +167,7 @@ def edit_subscription_page(
@router.get("/health")
-def news_health_check(username: str = Depends(require_auth)):
+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
diff --git a/src/local_deep_research/web/routers/notes.py b/src/local_deep_research/web/routers/notes.py
index 5407baf131..b152532e30 100644
--- a/src/local_deep_research/web/routers/notes.py
+++ b/src/local_deep_research/web/routers/notes.py
@@ -49,6 +49,7 @@ from ..template_config import templates
# _search_constants so the two route modules can't diverge. The router lives
# in web/routers/, so reach the file in web/routes/.
from ..routes._search_constants import MAX_SEARCH_LEN
+from typing import Annotated, Any
# Bound at import time (not looked up on the class at call time) because
# tests monkeypatch the ``NoteAIService`` name in this module.
@@ -179,7 +180,9 @@ async def _parse_json_off_loop(body):
return await asyncio.to_thread(json.loads, body)
-async def _notes_json_body(request: Request):
+async def _notes_json_body(
+ request: Request,
+) -> dict[str, Any] | JSONResponse:
"""Shared body gate for every mutating notes route.
Replaces the blueprint's two ``before_request`` hooks:
@@ -253,6 +256,12 @@ async def _notes_json_body(request: Request):
return data
+_NotesBody = Annotated[
+ dict[str, Any] | JSONResponse,
+ Depends(_notes_json_body),
+]
+
+
def _trigger_note_auto_index(note_id, service, username, session_id):
"""Trigger async auto-indexing for a note (non-blocking)."""
try:
@@ -286,7 +295,9 @@ def _trigger_note_auto_index(note_id, service, username, session_id):
@router.get("/")
-def notes_page(request: Request, username: str = Depends(require_auth)):
+def notes_page(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Render the notes list page."""
return templates.TemplateResponse(
request=request,
@@ -297,7 +308,9 @@ def notes_page(request: Request, username: str = Depends(require_auth)):
@router.get("/{note_id}")
def note_detail_page(
- request: Request, note_id: str, username: str = Depends(require_auth)
+ request: Request,
+ note_id: str,
+ username: Annotated[str, Depends(require_auth)],
):
"""Render the note detail page."""
return templates.TemplateResponse(
@@ -314,7 +327,9 @@ def note_detail_page(
@router.get("/api/notes")
@_notes_search_limit
-def list_notes(request: Request, username: str = Depends(require_auth)):
+def list_notes(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""
List notes with optional filtering.
@@ -409,8 +424,8 @@ def list_notes(request: Request, username: str = Depends(require_auth)):
@_notes_write_limit
def create_note(
request: Request,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""
Create a new note.
@@ -487,7 +502,7 @@ def create_note(
@router.get("/api/notes/semantic-search")
@_notes_search_limit
def semantic_search_notes(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""
Search notes using semantic similarity.
@@ -555,7 +570,9 @@ def semantic_search_notes(
@router.get("/api/notes/ask-context")
@_notes_search_limit
-def ask_context(request: Request, username: str = Depends(require_auth)):
+def ask_context(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Pre-flight context for the 'Ask your notes' box: the Notes collection
id + note/indexed counts, so the UI can warn when there's nothing to
search before starting a research run pinned to that collection.
@@ -571,7 +588,7 @@ def ask_context(request: Request, username: str = Depends(require_auth)):
@router.get("/api/notes/search-for-linking")
@_notes_search_limit
def search_notes_for_linking(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""
Search notes for the [[link]] autocomplete feature.
@@ -612,7 +629,9 @@ def search_notes_for_linking(
@router.get("/api/notes/{note_id}")
def get_note(
- request: Request, note_id: str, username: str = Depends(require_auth)
+ request: Request,
+ note_id: str,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get a specific note."""
try:
@@ -635,8 +654,8 @@ def get_note(
def update_note(
request: Request,
note_id: str,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""
Update a note.
@@ -714,7 +733,9 @@ def update_note(
@router.delete("/api/notes/{note_id}")
@_notes_write_limit
def delete_note(
- request: Request, note_id: str, username: str = Depends(require_auth)
+ request: Request,
+ note_id: str,
+ username: Annotated[str, Depends(require_auth)],
):
"""Delete a note."""
try:
@@ -739,7 +760,9 @@ def delete_note(
@router.get("/api/notes/{note_id}/collections")
def get_note_collections(
- request: Request, note_id: str, username: str = Depends(require_auth)
+ request: Request,
+ note_id: str,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get collections a note belongs to."""
try:
@@ -766,8 +789,8 @@ def get_note_collections(
def add_note_to_collection(
request: Request,
note_id: str,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""
Add a note to a collection.
@@ -820,7 +843,7 @@ def remove_note_from_collection(
request: Request,
note_id: str,
collection_id: str,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Remove a note from a collection."""
try:
@@ -858,7 +881,9 @@ def remove_note_from_collection(
@router.get("/api/notes/{note_id}/research")
def get_note_research(
- request: Request, note_id: str, username: str = Depends(require_auth)
+ request: Request,
+ note_id: str,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get research runs triggered from a note."""
try:
@@ -882,8 +907,8 @@ def get_note_research(
def link_research_to_note(
request: Request,
note_id: str,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""
Link a research run to a note.
@@ -951,8 +976,8 @@ def patch_note_research(
request: Request,
note_id: str,
research_id: str,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""Update a NoteResearch row (currently supports is_collapsed toggle).
@@ -998,8 +1023,8 @@ def patch_note_research(
def reorder_note_research(
request: Request,
note_id: str,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""Atomically reorder research items for a note.
@@ -1071,7 +1096,9 @@ def reorder_note_research(
@router.get("/api/research/{research_id}/notes")
@_notes_search_limit
def get_research_notes(
- request: Request, research_id: str, username: str = Depends(require_auth)
+ request: Request,
+ research_id: str,
+ username: Annotated[str, Depends(require_auth)],
):
"""List the notes linked to a research run.
@@ -1098,8 +1125,8 @@ def get_research_notes(
def create_research_note(
request: Request,
research_id: str,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""Create a note pre-linked to a research run (all-or-nothing).
@@ -1150,8 +1177,8 @@ def create_research_note(
def save_research_as_note(
request: Request,
research_id: str,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""Copy a COMPLETED research run's report into a new, linked note.
@@ -1365,7 +1392,9 @@ def _research_exists(username, research_id):
@router.get("/api/research/{research_id}/annotations")
@_notes_search_limit
def get_research_annotations(
- request: Request, research_id: str, username: str = Depends(require_auth)
+ request: Request,
+ research_id: str,
+ username: Annotated[str, Depends(require_auth)],
):
"""List a research run's inline annotations (anchored comment notes)."""
try:
@@ -1390,8 +1419,8 @@ def get_research_annotations(
def create_research_annotation(
request: Request,
research_id: str,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""Attach a comment to a passage of the research report.
@@ -1461,7 +1490,7 @@ def delete_research_annotation(
request: Request,
research_id: str,
note_id: str,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Remove an annotation: the comment note is deleted (standard delete
path — version cascade, vector purge) and its anchor row cascades."""
@@ -1485,7 +1514,9 @@ def delete_research_annotation(
@router.get("/api/documents/{document_id}/notes")
@_notes_search_limit
def get_document_notes(
- request: Request, document_id: str, username: str = Depends(require_auth)
+ request: Request,
+ document_id: str,
+ username: Annotated[str, Depends(require_auth)],
):
"""List the notes referencing a library document (its Notes panel)."""
try:
@@ -1507,8 +1538,8 @@ def get_document_notes(
def create_document_note(
request: Request,
document_id: str,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""Create a note referencing a library document (all-or-nothing).
@@ -1553,7 +1584,9 @@ def create_document_note(
@router.get("/api/documents/{document_id}/annotations")
@_notes_search_limit
def get_document_annotations(
- request: Request, document_id: str, username: str = Depends(require_auth)
+ request: Request,
+ document_id: str,
+ username: Annotated[str, Depends(require_auth)],
):
"""List a library document's inline annotations."""
try:
@@ -1579,8 +1612,8 @@ def get_document_annotations(
def create_document_annotation(
request: Request,
document_id: str,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""Attach a comment to a passage of a library document's text."""
if isinstance(body, JSONResponse):
@@ -1651,7 +1684,7 @@ def delete_document_annotation(
request: Request,
document_id: str,
note_id: str,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Remove a document annotation (deletes the comment note; the
anchor row cascades)."""
@@ -1679,8 +1712,8 @@ def delete_document_annotation(
def index_note_to_collection(
request: Request,
note_id: str,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""
Index a note into a collection for RAG search.
@@ -1753,7 +1786,9 @@ def index_note_to_collection(
@router.get("/api/notes/{note_id}/similar")
@_notes_search_limit
def get_similar_notes(
- request: Request, note_id: str, username: str = Depends(require_auth)
+ request: Request,
+ note_id: str,
+ username: Annotated[str, Depends(require_auth)],
):
"""
Find notes similar to the given note using embeddings.
@@ -1790,8 +1825,8 @@ def get_similar_notes(
def summarize_note(
request: Request,
note_id: str,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""Generate an AI summary of the note."""
if isinstance(body, JSONResponse):
@@ -1821,8 +1856,8 @@ def summarize_note(
def extract_research_questions(
request: Request,
note_id: str,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""Extract potential research questions from the note."""
if isinstance(body, JSONResponse):
@@ -1847,8 +1882,8 @@ def extract_research_questions(
@_notes_ai_limit
def suggest_tags(
request: Request,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""
Suggest tags for note content.
@@ -1929,8 +1964,8 @@ def suggest_tags(
def extract_key_concepts(
request: Request,
note_id: str,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""Extract key concepts, entities, and themes from the note."""
if isinstance(body, JSONResponse):
@@ -1959,7 +1994,9 @@ def extract_key_concepts(
@router.get("/api/notes/{note_id}/backlinks")
@_notes_search_limit
def get_backlinks(
- request: Request, note_id: str, username: str = Depends(require_auth)
+ request: Request,
+ note_id: str,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get notes that link to this note (backlinks)."""
try:
@@ -1985,7 +2022,9 @@ def get_backlinks(
@router.get("/api/notes/{note_id}/outgoing-links")
@_notes_search_limit
def get_outgoing_links(
- request: Request, note_id: str, username: str = Depends(require_auth)
+ request: Request,
+ note_id: str,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get notes that this note links to."""
try:
@@ -2010,7 +2049,9 @@ def get_outgoing_links(
@router.get("/api/notes/{note_id}/suggested-links")
@_notes_search_limit
def get_suggested_links(
- request: Request, note_id: str, username: str = Depends(require_auth)
+ request: Request,
+ note_id: str,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get AI-suggested notes to link to based on semantic similarity."""
try:
@@ -2041,8 +2082,8 @@ def get_suggested_links(
def accept_suggested_link(
request: Request,
note_id: str,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""Accept an AI-suggested link: insert [[Target Title]] into the note
content and flag the resulting NoteLink as auto_suggested=True.
@@ -2086,7 +2127,9 @@ def accept_suggested_link(
@router.get("/api/notes/{note_id}/unlinked-mentions")
@_notes_search_limit
def get_unlinked_mentions(
- request: Request, note_id: str, username: str = Depends(require_auth)
+ request: Request,
+ note_id: str,
+ username: Annotated[str, Depends(require_auth)],
):
"""Notes whose text mentions this note's title but don't yet link to it.
@@ -2116,8 +2159,8 @@ MAX_PASSAGE_LEN = 2000
def similar_passages(
request: Request,
note_id: str,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""Find note passages (chunks) semantically similar to a given snippet.
@@ -2164,8 +2207,8 @@ def similar_passages(
def fact_check_note(
request: Request,
note_id: str,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""Extract checkable factual claims from a note and synthesize a research
query for verifying them.
@@ -2329,8 +2372,8 @@ def grade_note_fact_check(
request: Request,
note_id: str,
research_id: str,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""Grade a note's claims against a COMPLETED research run's report.
@@ -2372,8 +2415,8 @@ def grade_note_fact_check(
@_notes_search_limit
def resolve_link(
request: Request,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""
Resolve a [[link]] text to a note.
@@ -2422,8 +2465,8 @@ def resolve_link(
@_notes_synthesize_limit
def preview_synthesis(
request: Request,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""
Preview what a synthesis would produce.
@@ -2491,8 +2534,8 @@ def preview_synthesis(
@_notes_synthesize_limit
def synthesize_notes(
request: Request,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""
Synthesize multiple notes into one.
@@ -2636,7 +2679,9 @@ def synthesize_notes(
@router.get("/api/notes/{note_id}/versions")
def get_note_versions(
- request: Request, note_id: str, username: str = Depends(require_auth)
+ request: Request,
+ note_id: str,
+ username: Annotated[str, Depends(require_auth)],
):
"""
Get version history for a note.
@@ -2749,7 +2794,9 @@ def get_note_versions(
@router.get("/api/notes/{note_id}/versions/semantic-diff")
@_notes_ai_limit
def get_semantic_diff(
- request: Request, note_id: str, username: str = Depends(require_auth)
+ request: Request,
+ note_id: str,
+ username: Annotated[str, Depends(require_auth)],
):
"""
Get AI-powered semantic diff between two versions.
@@ -2834,7 +2881,7 @@ def get_note_version(
request: Request,
note_id: str,
version_id: str,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Get a specific version of a note."""
from ...database.models import Document, NoteVersion
@@ -2895,8 +2942,8 @@ def restore_note_version(
request: Request,
note_id: str,
version_id: str,
- username: str = Depends(require_auth),
- body=Depends(_notes_json_body),
+ username: Annotated[str, Depends(require_auth)],
+ body: _NotesBody,
):
"""Restore a note to a previous version.
diff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.py
index 27a05f2350..40d2109d22 100644
--- a/src/local_deep_research/web/routers/rag.py
+++ b/src/local_deep_research/web/routers/rag.py
@@ -35,7 +35,7 @@ import queue
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, UTC
from pathlib import Path
-from typing import Any, Dict, Optional, Set, Tuple
+from typing import Any, Dict, Optional, Set, Tuple, Annotated
from tenacity import (
retry,
retry_if_exception,
@@ -417,7 +417,7 @@ def _format_test_embedding_error(exc: Exception, model: str) -> str:
@router.get("/api/config/supported-formats")
def get_supported_formats(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Return list of supported file formats for upload.
@@ -443,7 +443,7 @@ def get_supported_formats(
@router.get("/embedding-settings")
def embedding_settings_page(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Render the Embedding Settings page."""
return templates.TemplateResponse(
@@ -455,7 +455,9 @@ def embedding_settings_page(
@router.get("/document/{document_id}/chunks")
def view_document_chunks(
- request: Request, document_id, username: str = Depends(require_auth)
+ request: Request,
+ document_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""View all chunks for a document across all collections."""
from ...database.session_context import get_user_db_session
@@ -529,7 +531,9 @@ def view_document_chunks(
@router.get("/collections")
-def collections_page(request: Request, username: str = Depends(require_auth)):
+def collections_page(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Render the Collections page."""
return templates.TemplateResponse(
request=request,
@@ -545,7 +549,7 @@ def collections_page(request: Request, username: str = Depends(require_auth)):
# create form (fenced by tests/web/routers/test_route_ordering.py).
@router.get("/collections/create")
def collection_create_page(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Render the Create Collection page."""
return templates.TemplateResponse(
@@ -584,7 +588,9 @@ def _validated_collection_id(collection_id: str) -> str:
@router.get("/collections/{collection_id}")
def collection_details_page(
- request: Request, collection_id, username: str = Depends(require_auth)
+ request: Request,
+ collection_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Render the Collection Details page."""
collection_id = _validated_collection_id(collection_id)
@@ -602,7 +608,7 @@ def collection_details_page(
def collection_upload_page(
request: Request,
collection_id,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Render the Collection Upload page."""
collection_id = _validated_collection_id(collection_id)
@@ -638,7 +644,7 @@ def collection_upload_page(
@router.get("/api/rag/settings")
def get_current_settings(
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Get current RAG configuration from settings."""
from ...database.session_context import get_user_db_session
@@ -692,7 +698,7 @@ def get_current_settings(
@router.post("/api/rag/test-embedding")
async def test_embedding(
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Test an embedding configuration by generating a test embedding."""
from ...database.session_context import get_user_db_session
@@ -803,7 +809,7 @@ async def test_embedding(
@router.get("/api/rag/models")
def get_available_models(
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Get list of available embedding providers and models."""
from ...database.session_context import get_user_db_session
@@ -990,7 +996,9 @@ def get_available_models(
@router.get("/api/rag/info")
-def get_index_info(request: Request, username: str = Depends(require_auth)):
+def get_index_info(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get information about the current RAG index."""
from ...database.library_init import get_default_library_id
@@ -1024,7 +1032,9 @@ def get_index_info(request: Request, username: str = Depends(require_auth)):
@router.get("/api/rag/stats")
-def get_rag_stats(request: Request, username: str = Depends(require_auth)):
+def get_rag_stats(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get RAG statistics for a collection."""
from ...database.library_init import get_default_library_id
@@ -1044,7 +1054,7 @@ def get_rag_stats(request: Request, username: str = Depends(require_auth)):
@router.post("/api/rag/index-document")
async def index_document(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Index a single document in a collection."""
from ...database.library_init import get_default_library_id
@@ -1102,7 +1112,7 @@ async def index_document(
@router.post("/api/rag/remove-document")
async def remove_document(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Remove a document from RAG in a collection."""
from ...database.library_init import get_default_library_id
@@ -1153,7 +1163,7 @@ async def remove_document(
@router.get("/api/rag/index-all")
def index_all(
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Index all documents in a collection with Server-Sent Events progress."""
from ...database.session_context import get_user_db_session
@@ -1358,7 +1368,7 @@ def index_all(
@router.post("/api/rag/configure")
async def configure_rag(
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""
Change RAG configuration (embedding model, chunk size, etc.).
@@ -1610,7 +1620,9 @@ async def configure_rag(
@router.get("/api/rag/documents")
-def get_documents(request: Request, username: str = Depends(require_auth)):
+def get_documents(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get library documents with their RAG status for the default Library collection (paginated)."""
from ...database.session_context import get_user_db_session
from ...database.library_init import get_default_library_id
@@ -1752,7 +1764,9 @@ def get_documents(request: Request, username: str = Depends(require_auth)):
@router.get("/api/collections")
-def get_collections(request: Request, username: str = Depends(require_auth)):
+def get_collections(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get all document collections for the current user."""
from ...database.session_context import get_user_db_session
@@ -1838,7 +1852,7 @@ def get_collections(request: Request, username: str = Depends(require_auth)):
@router.post("/api/collections")
async def create_collection(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Create a new document collection."""
data = await request.json()
@@ -1981,7 +1995,9 @@ def _create_collection_sync(data, username):
@router.put("/api/collections/{collection_id}")
async def update_collection(
- request: Request, collection_id, username: str = Depends(require_auth)
+ request: Request,
+ collection_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Update a collection's details."""
data = await request.json()
@@ -2188,7 +2204,7 @@ def _try_pdf_upgrade(
async def upload_to_collection(
request: Request,
collection_id,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Upload files to a collection.
@@ -2806,7 +2822,9 @@ def _upload_to_collection_sync(
@router.get("/api/collections/{collection_id}/documents")
def get_collection_documents(
- request: Request, collection_id, username: str = Depends(require_auth)
+ request: Request,
+ collection_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get all documents in a collection."""
from ...database.session_context import get_user_db_session
@@ -3163,7 +3181,9 @@ def _query_documents_to_index(db_session, collection_id, force_reindex):
@router.get("/api/collections/{collection_id}/index")
def index_collection(
- request: Request, collection_id, username: str = Depends(require_auth)
+ request: Request,
+ collection_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Index all documents in a collection with Server-Sent Events progress."""
from ...database.session_context import get_user_db_session
@@ -4136,7 +4156,9 @@ def _is_task_cancelled(username: str, db_password: str, task_id: str) -> bool:
@router.post("/api/collections/{collection_id}/index/start")
async def start_background_index(
- request: Request, collection_id, username: str = Depends(require_auth)
+ request: Request,
+ collection_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Start background indexing for a collection."""
from ...database.session_passwords import session_password_store
@@ -4305,7 +4327,9 @@ def _start_background_index_sync(
@router.get("/api/collections/{collection_id}/index/status")
@limiter.exempt
def get_index_status(
- request: Request, collection_id, username: str = Depends(require_auth)
+ request: Request,
+ collection_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get the current indexing status for a collection."""
from ...database.session_context import get_user_db_session
@@ -4393,7 +4417,9 @@ def get_index_status(
@router.post("/api/collections/{collection_id}/index/cancel")
def cancel_indexing(
- request: Request, collection_id, username: str = Depends(require_auth)
+ request: Request,
+ collection_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Cancel an active indexing task for a collection."""
from ...database.session_context import get_user_db_session
diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.py
index b197ef1bce..73070815f8 100644
--- a/src/local_deep_research/web/routers/research.py
+++ b/src/local_deep_research/web/routers/research.py
@@ -26,7 +26,7 @@ from loguru import logger
from ...settings.logger import log_settings
from sqlalchemy import case, func
from sqlalchemy.orm import Session
-from typing import Optional
+from typing import Optional, Annotated
# Security imports
from ...config.constants import DEFAULT_OLLAMA_URL
@@ -137,7 +137,9 @@ def redirect_static(path: str):
@router.get("/progress/{research_id}")
def progress_page(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Render the research progress page"""
return templates.TemplateResponse(
@@ -149,7 +151,9 @@ def progress_page(
@router.get("/details/{research_id}")
def research_details_page(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Render the research details page"""
return templates.TemplateResponse(
@@ -159,7 +163,9 @@ def research_details_page(
@router.get("/results/{research_id}")
def results_page(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Render the research results page"""
return templates.TemplateResponse(
@@ -168,7 +174,9 @@ def results_page(
@router.get("/history")
-def history_page(request: Request, username: str = Depends(require_auth)):
+def history_page(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Render the history page"""
return templates.TemplateResponse(
request=request, name="pages/history.html", context={"request": request}
@@ -725,7 +733,7 @@ def _queue_research(
# research queue (#3135).
@api_rate_limit
async def start_research(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""
Async wrapper that does the only legitimate await (parsing the JSON
@@ -1390,7 +1398,9 @@ def _start_research_sync(
@router.post("/api/terminate/{research_id}")
def terminate_research(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Terminate an in-progress research process"""
@@ -1539,7 +1549,9 @@ def terminate_research(
@router.delete("/api/delete/{research_id}")
def delete_research(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Delete a research record"""
@@ -1638,7 +1650,9 @@ def delete_research(
@router.post("/api/clear_history")
-def clear_history(request: Request, username: str = Depends(require_auth)):
+def clear_history(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Clear all research history"""
try:
@@ -1720,7 +1734,9 @@ def clear_history(request: Request, username: str = Depends(require_auth)):
@router.post("/open_file_location")
-def open_file_location(request: Request, username: str = Depends(require_auth)):
+def open_file_location(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Open a file location in the system file explorer.
Security: This endpoint is disabled for server deployments.
@@ -1737,7 +1753,7 @@ def open_file_location(request: Request, username: str = Depends(require_auth)):
@router.post("/api/save_raw_config")
async def save_raw_config(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Save raw configuration"""
data = await request.json()
@@ -1851,7 +1867,9 @@ async def save_raw_config(
@router.get("/api/history")
-def get_history(request: Request, username: str = Depends(require_auth)):
+def get_history(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get research history.
NOTE: Returns a raw list of items. The newer canonical endpoint
@@ -1973,7 +1991,9 @@ def get_history(request: Request, username: str = Depends(require_auth)):
@router.get("/api/research/{research_id}")
def get_research_details(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get full details of a research using ORM"""
@@ -2009,7 +2029,9 @@ def get_research_details(
@router.get("/api/research/{research_id}/logs")
def get_research_logs(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get logs for a specific research.
@@ -2177,7 +2199,9 @@ _log_export_limit = limiter.shared_limit(
@router.get("/api/research/{research_id}/logs/export")
@_log_export_limit
def export_research_logs(
- request: Request, research_id: str, username: str = Depends(require_auth)
+ request: Request,
+ research_id: str,
+ username: Annotated[str, Depends(require_auth)],
):
"""Stream every persisted log row for a research as newline-delimited JSON.
@@ -2313,7 +2337,9 @@ def export_research_logs(
@router.get("/api/report/{research_id}")
def get_research_report(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get the research report content"""
@@ -2393,7 +2419,10 @@ def get_research_report(
@router.post("/api/v1/research/{research_id}/export/{format}")
def export_research_report(
- request: Request, research_id, format, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ format,
+ username: Annotated[str, Depends(require_auth)],
):
"""Export research report to different formats (LaTeX, Quarto, RIS, PDF, ODT, etc.)"""
try:
@@ -2508,7 +2537,9 @@ def export_research_report(
@router.get("/api/research/{research_id}/status")
@limiter.exempt
def get_research_status(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get the status of a research process"""
@@ -2648,7 +2679,9 @@ def get_research_status(
@router.get("/api/queue/status")
-def get_queue_status(request: Request, username: str = Depends(require_auth)):
+def get_queue_status(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get the current queue status for the user"""
from ..queue import QueueManager
@@ -2671,7 +2704,9 @@ def get_queue_status(request: Request, username: str = Depends(require_auth)):
@router.get("/api/queue/{research_id}/position")
def get_queue_position(
- request: Request, research_id, username: str = Depends(require_auth)
+ request: Request,
+ research_id,
+ username: Annotated[str, Depends(require_auth)],
):
"""Get the queue position for a specific research"""
@@ -2695,7 +2730,9 @@ def get_queue_position(
@router.get("/api/config/limits")
-def get_upload_limits(request: Request, username: str = Depends(require_auth)):
+def get_upload_limits(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""
Get file upload configuration limits.
@@ -2717,8 +2754,8 @@ def get_upload_limits(request: Request, username: str = Depends(require_auth)):
@upload_rate_limit_ip
async def upload_pdf(
request: Request,
+ username: Annotated[str, Depends(require_auth)],
files: list = None,
- username: str = Depends(require_auth),
):
"""
Upload and extract text from PDF files with comprehensive security validation.
diff --git a/src/local_deep_research/web/routers/scheduler.py b/src/local_deep_research/web/routers/scheduler.py
index 6d5c99990d..074348a56d 100644
--- a/src/local_deep_research/web/routers/scheduler.py
+++ b/src/local_deep_research/web/routers/scheduler.py
@@ -9,6 +9,7 @@ from ..dependencies.auth import require_auth
from loguru import logger
from ...scheduler.background import get_background_job_scheduler
+from typing import Annotated
# Create the router
router = APIRouter(tags=["document_scheduler"])
@@ -21,7 +22,7 @@ router = APIRouter(tags=["document_scheduler"])
@router.get("/api/scheduler/status")
def get_scheduler_status(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get the current status of the document scheduler for the current user."""
try:
@@ -35,7 +36,9 @@ def get_scheduler_status(
@router.post("/api/scheduler/run-now")
-def trigger_manual_run(request: Request, username: str = Depends(require_auth)):
+def trigger_manual_run(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Trigger a manual processing run of the document scheduler for the current user."""
try:
scheduler = get_background_job_scheduler()
diff --git a/src/local_deep_research/web/routers/settings.py b/src/local_deep_research/web/routers/settings.py
index 902544e71d..fdc939240b 100644
--- a/src/local_deep_research/web/routers/settings.py
+++ b/src/local_deep_research/web/routers/settings.py
@@ -56,7 +56,7 @@ import math
import platform
import time
from types import SimpleNamespace
-from typing import Any, Optional, Tuple
+from typing import Any, Optional, Tuple, Annotated
from datetime import UTC, datetime, timedelta, timezone
import requests
@@ -683,7 +683,9 @@ def _new_key_rejection_reason(key) -> str:
@router.get("/")
-def settings_page(request: Request, username: str = Depends(require_auth)):
+def settings_page(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Main settings dashboard with links to specialized config pages"""
return templates.TemplateResponse(
request=request,
@@ -1199,7 +1201,7 @@ def _save_all_settings_sync(form_data: dict, username: str):
@settings_limit
async def save_all_settings(
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Handle saving all settings at once from the unified settings page.
@@ -1221,7 +1223,7 @@ async def save_all_settings(
@settings_limit
def reset_to_defaults(
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Reset all settings to their default values.
@@ -1498,7 +1500,7 @@ def _save_settings_sync(form_data: dict, username: str) -> dict:
@settings_limit
async def save_settings(
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Save all settings from the form using POST method — fallback when
JavaScript is disabled. Body work offloaded to threadpool."""
@@ -1559,7 +1561,7 @@ async def save_settings(
@router.get("/api")
def api_get_all_settings(
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Get all settings"""
try:
@@ -1632,7 +1634,7 @@ def api_get_all_settings(
@settings_limit
def api_import_settings(
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Import settings from defaults file"""
try:
@@ -1676,7 +1678,7 @@ def api_import_settings(
@router.get("/api/categories")
def api_get_categories(
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Get all setting categories"""
try:
@@ -1694,7 +1696,9 @@ def api_get_categories(
@router.get("/api/types")
-def api_get_types(request: Request, username: str = Depends(require_auth)):
+def api_get_types(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get all setting types"""
try:
# Get all setting types
@@ -1709,7 +1713,7 @@ def api_get_types(request: Request, username: str = Depends(require_auth)):
@router.get("/api/ui_elements")
def api_get_ui_elements(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get all UI element types"""
try:
@@ -1737,7 +1741,7 @@ def api_get_ui_elements(
@router.get("/api/available-models")
def api_get_available_models(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get available LLM models from various providers"""
endpoint_start = time.perf_counter()
@@ -2263,7 +2267,7 @@ def _classify_options_for_egress(
@router.get("/api/available-search-engines")
def api_get_available_search_engines(
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Get available search engines.
@@ -2468,7 +2472,7 @@ def api_get_available_search_engines(
@router.get("/api/search-favorites")
def api_get_search_favorites(
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Get the list of favorite search engines for the current user"""
try:
@@ -2490,7 +2494,7 @@ def api_get_search_favorites(
@settings_limit
async def api_update_search_favorites(
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Update the list of favorite search engines for the current user"""
data = await request.json()
@@ -2543,7 +2547,7 @@ async def api_update_search_favorites(
@settings_limit
async def api_toggle_search_favorite(
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Toggle a search engine as favorite"""
data = await request.json()
@@ -2607,14 +2611,16 @@ async def api_toggle_search_favorite(
# Legacy routes for backward compatibility - these will redirect to the new routes
@router.get("/main")
-def main_config_page(request: Request, username: str = Depends(require_auth)):
+def main_config_page(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Redirect to app settings page"""
return RedirectResponse(url="/settings/", status_code=302)
@router.get("/collections")
def collections_config_page(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Redirect to app settings page"""
return RedirectResponse(url="/settings/", status_code=302)
@@ -2622,7 +2628,7 @@ def collections_config_page(
@router.get("/api_keys")
def api_keys_config_page(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Redirect to LLM settings page"""
return RedirectResponse(url="/settings/", status_code=302)
@@ -2630,20 +2636,24 @@ def api_keys_config_page(
@router.get("/search_engines")
def search_engines_config_page(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Redirect to search settings page"""
return RedirectResponse(url="/settings/", status_code=302)
@router.get("/llm")
-def llm_config_page(request: Request, username: str = Depends(require_auth)):
+def llm_config_page(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Redirect to LLM settings page"""
return RedirectResponse(url="/settings/", status_code=302)
@router.post("/open_file_location")
-def open_file_location(request: Request, username: str = Depends(require_auth)):
+def open_file_location(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Open the location of a configuration file.
Security: This endpoint is disabled for server deployments.
@@ -2665,7 +2675,7 @@ def open_file_location(request: Request, username: str = Depends(require_auth)):
@settings_limit
def fix_corrupted_settings(
request: Request,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Fix corrupted settings in the database"""
try:
@@ -2844,7 +2854,9 @@ def fix_corrupted_settings(
@router.get("/api/warnings")
-def api_get_warnings(request: Request, username: str = Depends(require_auth)):
+def api_get_warnings(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get current warnings based on settings"""
try:
warnings = calculate_warnings(username=username)
@@ -2858,7 +2870,7 @@ def api_get_warnings(request: Request, username: str = Depends(require_auth)):
@router.get("/api/backup-status")
def api_get_backup_status(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get backup status for the current user."""
try:
@@ -2925,7 +2937,7 @@ def api_get_backup_status(
@router.get("/api/ollama-status")
def check_ollama_status(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Check if Ollama is running and available"""
try:
@@ -2964,7 +2976,7 @@ def check_ollama_status(
@router.get("/api/rate-limiting/status")
def api_get_rate_limiting_status(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get current rate limiting status and statistics"""
try:
@@ -3027,7 +3039,9 @@ def api_get_rate_limiting_status(
@router.post("/api/rate-limiting/engines/{engine_type}/reset")
def api_reset_engine_rate_limiting(
- request: Request, engine_type, username: str = Depends(require_auth)
+ request: Request,
+ engine_type,
+ username: Annotated[str, Depends(require_auth)],
):
"""Reset (forget) the learned rate-limit estimate for a specific engine.
@@ -3065,7 +3079,7 @@ def _cleanup_rate_limit_estimates_sync(username: str, cutoff: float) -> None:
@router.post("/api/rate-limiting/cleanup")
async def api_cleanup_rate_limiting(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Clean up old rate limiting data.
@@ -3118,7 +3132,9 @@ async def api_cleanup_rate_limiting(
@router.get("/api/bulk")
-def get_bulk_settings(request: Request, username: str = Depends(require_auth)):
+def get_bulk_settings(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Get multiple settings at once for performance."""
try:
# Get requested settings from query parameters
@@ -3172,7 +3188,7 @@ def get_bulk_settings(request: Request, username: str = Depends(require_auth)):
@router.get("/api/data-location")
def api_get_data_location(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get information about data storage location and security"""
try:
@@ -3312,8 +3328,8 @@ notification_test_limit = limiter.shared_limit(
@notification_test_limit
async def api_test_notification_url(
request: Request,
- data: dict = Depends(_notification_test_body),
- username: str = Depends(require_auth),
+ data: Annotated[dict, Depends(_notification_test_body)],
+ username: Annotated[str, Depends(require_auth)],
):
"""
Test a submitted notification URL or the calling user's stored URL.
@@ -3417,7 +3433,7 @@ async def api_test_notification_url(
def api_get_db_setting(
request: Request,
key,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Get a specific setting by key from DB, falling back to defaults.
@@ -3530,7 +3546,7 @@ def api_get_db_setting(
async def api_update_setting(
request: Request,
key,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Update a setting"""
data = await request.json()
@@ -3928,7 +3944,7 @@ def _api_update_setting_sync(data, key, username):
def api_delete_setting(
request: Request,
key,
- username: str = Depends(require_auth),
+ username: Annotated[str, Depends(require_auth)],
):
"""Delete a setting"""
try:
diff --git a/src/local_deep_research/web/routers/unified_search.py b/src/local_deep_research/web/routers/unified_search.py
index eb54b22648..18365ff10b 100644
--- a/src/local_deep_research/web/routers/unified_search.py
+++ b/src/local_deep_research/web/routers/unified_search.py
@@ -34,6 +34,7 @@ from ..template_config import templates
# shared with notes_routes via _search_constants so the two route modules
# can't diverge.
from ..routes._search_constants import MAX_SEARCH_LEN
+from typing import Annotated
# Keyword-leg preview length: column-projected ``substr`` so the full
# text_content (which can be megabytes for extracted PDFs) is never
@@ -154,7 +155,7 @@ def _validated_query_and_limit(request: Request):
@router.get("/")
def unified_search_page(
- request: Request, username: str = Depends(require_auth)
+ request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Render the unified Search page."""
return templates.TemplateResponse(
@@ -171,7 +172,9 @@ def unified_search_page(
@router.get("/api/keyword")
@_unified_search_limit
-def keyword_search(request: Request, username: str = Depends(require_auth)):
+def keyword_search(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Keyword leg: ILIKE over Document.title + text_content, ALL source types.
Query params:
@@ -293,7 +296,9 @@ def keyword_search(request: Request, username: str = Depends(require_auth)):
@router.get("/api/semantic")
@_unified_search_limit
-def semantic_search(request: Request, username: str = Depends(require_auth)):
+def semantic_search(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Semantic leg: FAISS search over the system collections.
Query params:
diff --git a/src/local_deep_research/web/routers/zotero.py b/src/local_deep_research/web/routers/zotero.py
index 10388bfcff..9753a71ea7 100644
--- a/src/local_deep_research/web/routers/zotero.py
+++ b/src/local_deep_research/web/routers/zotero.py
@@ -31,6 +31,7 @@ from ...research_library.zotero import (
from ...security import sanitize_error_for_client
from ..dependencies.auth import require_auth
from ..template_config import templates
+from typing import Annotated
router = APIRouter(prefix="/library", tags=["zotero"])
@@ -82,7 +83,9 @@ def _session_expired_response() -> JSONResponse:
@router.get("/zotero")
-def zotero_page(request: Request, username: str = Depends(require_auth)):
+def zotero_page(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Render the Zotero integration page."""
return templates.TemplateResponse(
request=request,
@@ -92,7 +95,9 @@ def zotero_page(request: Request, username: str = Depends(require_auth)):
@router.get("/api/zotero/config")
-def get_config(request: Request, username: str = Depends(require_auth)):
+def get_config(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Return a non-secret summary of the Zotero configuration."""
password = _db_password(request, username) # gitleaks:allow
if not password:
@@ -120,7 +125,9 @@ def get_config(request: Request, username: str = Depends(require_auth)):
@router.post("/api/zotero/test")
-def test_connection(request: Request, username: str = Depends(require_auth)):
+def test_connection(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Validate the configured Zotero credentials."""
password = _db_password(request, username) # gitleaks:allow
if not password:
@@ -159,7 +166,9 @@ def _not_configured_response() -> JSONResponse:
@router.get("/api/zotero/collections")
-def list_collections(request: Request, username: str = Depends(require_auth)):
+def list_collections(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""List the user's Zotero collections (key + name)."""
password = _db_password(request, username) # gitleaks:allow
if not password:
@@ -176,7 +185,9 @@ def list_collections(request: Request, username: str = Depends(require_auth)):
@router.get("/api/zotero/groups")
-def list_groups(request: Request, username: str = Depends(require_auth)):
+def list_groups(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""List the groups the configured API key can access (id + name)."""
password = _db_password(request, username) # gitleaks:allow
if not password:
@@ -193,7 +204,7 @@ def list_groups(request: Request, username: str = Depends(require_auth)):
@router.post("/api/zotero/sync")
-def sync_now(request: Request, username: str = Depends(require_auth)):
+def sync_now(request: Request, username: Annotated[str, Depends(require_auth)]):
"""Trigger a background sync of the configured collections.
Runs in a daemon thread using the current session's password and returns
@@ -251,7 +262,9 @@ def sync_now(request: Request, username: str = Depends(require_auth)):
@router.get("/api/zotero/status")
-def get_status(request: Request, username: str = Depends(require_auth)):
+def get_status(
+ request: Request, username: Annotated[str, Depends(require_auth)]
+):
"""Return stored sync state for all configured collections."""
password = _db_password(request, username) # gitleaks:allow
if not password:
diff --git a/tests/deployment/test_deployment_surface_contracts.py b/tests/deployment/test_deployment_surface_contracts.py
index 7b844e37e8..c3d3967dcf 100644
--- a/tests/deployment/test_deployment_surface_contracts.py
+++ b/tests/deployment/test_deployment_surface_contracts.py
@@ -736,8 +736,8 @@ class TestHealthCheck:
assert re.search(
r'@router\.get\("/health"\)\s*\n'
- r"def health_check\(\s*username: str \| None = "
- r"Depends\(get_session_username\)",
+ r"def health_check\(\s*\n?\s*username: Annotated\[str \| None, "
+ r"Depends\(get_session_username\)\],?",
api_v1,
), (
f"{PUBLIC_HEALTH_PATH} must keep an OPTIONAL session dependency; "
@@ -745,8 +745,8 @@ class TestHealthCheck:
)
assert re.search(
r'@router\.get\("/health"\)\s*\n'
- r"def news_health_check\(\s*username: str = "
- r"Depends\(require_auth\)",
+ r"def news_health_check\(\s*username: Annotated\[str, "
+ r"Depends\(require_auth\)\]",
news,
), f"{NEWS_HEALTH_PATH} is expected to stay auth-gated"
diff --git a/tests/hooks/test_check_fastapi_default_parameters.py b/tests/hooks/test_check_fastapi_default_parameters.py
new file mode 100644
index 0000000000..8c5cd0dd40
--- /dev/null
+++ b/tests/hooks/test_check_fastapi_default_parameters.py
@@ -0,0 +1,172 @@
+"""Tests for the FastAPI default-parameter pre-commit guard."""
+
+import importlib.util
+import sys
+from pathlib import Path
+from types import ModuleType
+
+import pytest
+import yaml
+
+ROOT = Path(__file__).resolve().parents[2]
+HOOK_PATH = ROOT / ".pre-commit-hooks" / "check-fastapi-default-parameters.py"
+MODULE = "check_fastapi_default_parameters"
+
+
+def hook() -> ModuleType:
+ assert HOOK_PATH.is_file(), f"hook is missing: {HOOK_PATH}"
+ spec = importlib.util.spec_from_file_location(MODULE, HOOK_PATH)
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+def _check(hook: ModuleType, tmp_path: Path, source: str):
+ path = tmp_path / "sample.py"
+ path.write_text(source, encoding="utf-8")
+ return hook.check_file(path)
+
+
+def test_current_fastapi_source_has_no_marker_defaults(hook):
+ web = ROOT / "src" / "local_deep_research" / "web"
+ paths = [web / "fastapi_app.py"]
+ paths.extend(sorted((web / "routers").glob("*.py")))
+ paths.extend(sorted((web / "dependencies").glob("*.py")))
+
+ assert hook.check_paths(paths) == ()
+
+
+def test_catches_typed_untyped_and_keyword_only_defaults(hook, tmp_path):
+ diagnostics = _check(
+ hook,
+ tmp_path,
+ "from fastapi import Depends, Form, Query\n"
+ "def route(user: str = Depends(auth), query=Query(None), /, *, "
+ "form=Form('')):\n"
+ " pass\n",
+ )
+
+ assert len(diagnostics) == 3
+ assert [
+ item.message.split(" uses ", 1)[1].split("(", 1)[0]
+ for item in diagnostics
+ ] == [
+ "Depends",
+ "Query",
+ "Form",
+ ]
+
+
+def test_catches_module_imports_renames_and_simple_aliases(hook, tmp_path):
+ diagnostics = _check(
+ hook,
+ tmp_path,
+ "import fastapi as fa\n"
+ "import fastapi.params as fp\n"
+ "from fastapi import Depends as Inject\n"
+ "from fastapi import params as params_alias\n"
+ "Alias = Inject\n"
+ "def route(a=fa.Query(None), b=fp.Body(None), c=Alias(auth), *, "
+ "d=params_alias.Header(None)):\n"
+ " pass\n",
+ )
+
+ assert len(diagnostics) == 4
+ messages = "\n".join(item.message for item in diagnostics)
+ for marker in ("Query", "Body", "Depends", "Header"):
+ assert f"uses {marker}(...)" in messages
+
+
+def test_annotated_parameters_and_decorator_dependencies_pass(hook, tmp_path):
+ diagnostics = _check(
+ hook,
+ tmp_path,
+ "from typing import Annotated\n"
+ "from fastapi import Depends, Query\n"
+ "@router.get('/items', dependencies=[Depends(auth)])\n"
+ "def route(user: Annotated[str, Depends(auth)], "
+ "query: Annotated[str | None, Query()] = None):\n"
+ " return user, query\n",
+ )
+
+ assert diagnostics == ()
+
+
+def test_same_named_non_fastapi_calls_are_not_flagged(hook, tmp_path):
+ diagnostics = _check(
+ hook,
+ tmp_path,
+ "from pathlib import Path\n"
+ "def Depends(value):\n"
+ " return value\n"
+ "def helper(path=Path('.'), value=Depends('local')):\n"
+ " return path, value\n",
+ )
+
+ assert diagnostics == ()
+
+
+def test_fastapi_star_import_fails_closed(hook, tmp_path):
+ diagnostics = _check(
+ hook,
+ tmp_path,
+ "from fastapi import *\ndef route(value=Depends(auth)):\n pass\n",
+ )
+
+ assert len(diagnostics) == 1
+ assert (
+ "star imports prevent reliable marker resolution"
+ in diagnostics[0].message
+ )
+
+
+def test_invalid_python_fails_closed(hook, tmp_path):
+ diagnostics = _check(hook, tmp_path, "def broken(:\n")
+
+ assert len(diagnostics) == 1
+ assert "invalid syntax" in diagnostics[0].message
+
+
+def test_main_reports_location_and_returns_nonzero(hook, tmp_path, capsys):
+ path = tmp_path / "bad.py"
+ path.write_text(
+ "from fastapi import Depends\ndef route(value=Depends(auth)):\n pass\n",
+ encoding="utf-8",
+ )
+
+ assert hook.main([str(path)]) == 1
+ output = capsys.readouterr().out
+ assert f"{path}:2:" in output
+ assert "parameter 'value' uses Depends(...)" in output
+
+
+def test_precommit_configuration_wires_the_guard():
+ config = yaml.safe_load((ROOT / ".pre-commit-config.yaml").read_text())
+ hooks = {
+ hook["id"]: hook
+ for repository in config["repos"]
+ if repository["repo"] == "local"
+ for hook in repository["hooks"]
+ }
+
+ configured = hooks["check-fastapi-default-parameters"]
+ assert configured["entry"] == str(HOOK_PATH.relative_to(ROOT))
+ assert configured["language"] == "script"
+ assert "routers/" in configured["files"]
+ assert "dependencies/" in configured["files"]
+
+ ruff_repository = next(
+ repository
+ for repository in config["repos"]
+ if repository["repo"] == "https://github.com/astral-sh/ruff-pre-commit"
+ )
+ fast002 = next(
+ item
+ for item in ruff_repository["hooks"]
+ if item.get("alias") == "fastapi-annotated-dependencies"
+ )
+ assert fast002["args"] == ["--select", "FAST002"]
+ assert "dependencies/" in fast002["files"]
diff --git a/tests/research_library/routes/test_rag_routes_deep_main_port.py b/tests/research_library/routes/test_rag_routes_deep_main_port.py
index 4b59bf1a04..899936dca6 100644
--- a/tests/research_library/routes/test_rag_routes_deep_main_port.py
+++ b/tests/research_library/routes/test_rag_routes_deep_main_port.py
@@ -1169,23 +1169,37 @@ class TestViewDocumentChunks:
def test_requires_authentication(self):
"""Main asserted an unauthenticated GET returns 401/302. Under
- FastAPI the gate is the ``Depends(require_auth)`` default on the
- handler's ``username`` parameter, so it is pinned structurally --
- an HTTP assertion would only re-test the shared dependency, while
- this goes red if the decorator/parameter is dropped from THIS route.
+ FastAPI the gate is the ``Depends(require_auth)`` on the handler's
+ ``username`` parameter, so it is pinned structurally -- an HTTP
+ assertion would only re-test the shared dependency, while this goes
+ red if the decorator/parameter is dropped from THIS route.
+
+ The FAST002 conversion spells this ``Annotated[str,
+ Depends(require_auth)]`` rather than a bare ``= Depends(require_auth)``
+ default, so the ``Depends(...)`` instance lives in the annotation's
+ ``Annotated`` metadata, not ``Parameter.default``.
"""
import inspect
+ import typing
from local_deep_research.web.dependencies.auth import require_auth
from local_deep_research.web.routers.rag import view_document_chunks
- default = (
+ annotation = (
inspect.signature(view_document_chunks)
.parameters["username"]
- .default
+ .annotation
)
- assert default is not inspect.Parameter.empty
- assert default.dependency is require_auth
+ assert annotation is not inspect.Parameter.empty
+ args = typing.get_args(annotation)
+ depends_metadata = [
+ meta for meta in args[1:] if hasattr(meta, "dependency")
+ ]
+ assert len(depends_metadata) == 1, (
+ f"expected exactly one Depends() in Annotated metadata, got "
+ f"{args[1:]!r}"
+ )
+ assert depends_metadata[0].dependency is require_auth
def test_document_not_found(self):
"""An unknown document id yields 404. Note the branch returns
diff --git a/tests/security/test_cross_user_isolation_census.py b/tests/security/test_cross_user_isolation_census.py
index 8cc17b9277..66f0ab71fb 100644
--- a/tests/security/test_cross_user_isolation_census.py
+++ b/tests/security/test_cross_user_isolation_census.py
@@ -230,20 +230,24 @@ def _module_name(path: Path) -> str:
def _params(fn: ast.FunctionDef | ast.AsyncFunctionDef):
- """Yield ``(name, default_node_or_None)`` for every declared parameter."""
+ """Yield ``(name, default_node_or_None, annotation_node_or_None)`` for
+ every declared parameter.
+ """
a = fn.args
positional = a.posonlyargs + a.args
defaults = [None] * (len(positional) - len(a.defaults)) + list(a.defaults)
- yield from zip([p.arg for p in positional], defaults)
- yield from zip([p.arg for p in a.kwonlyargs], a.kw_defaults)
+ for p, d in zip(positional, defaults):
+ yield p.arg, d, p.annotation
+ for p, d in zip(a.kwonlyargs, a.kw_defaults):
+ yield p.arg, d, p.annotation
def _depends_target(default) -> str | None:
- """Return the callable name inside ``Depends(...)``, if this is one."""
+ """Return the callable name inside ``Depends(...)``/``Security(...)``."""
if (
isinstance(default, ast.Call)
and isinstance(default.func, ast.Name)
- and default.func.id == "Depends"
+ and default.func.id in ("Depends", "Security")
):
arg = default.args[0] if default.args else None
if isinstance(arg, ast.Name):
@@ -253,6 +257,48 @@ def _depends_target(default) -> str | None:
return None
+def _annotated_metadata(annotation):
+ """Yield each metadata expression inside ``Annotated[T, meta, ...]``.
+
+ Handles both the bare-name (``Annotated[...]``) and qualified
+ (``typing.Annotated[...]``) spellings. ``ast.Subscript.slice`` is the
+ expression directly on the Python versions this project targets (3.9+),
+ so a multi-element subscript is an ``ast.Tuple``.
+ """
+ if not isinstance(annotation, ast.Subscript):
+ return
+ head = annotation.value
+ is_annotated = (isinstance(head, ast.Name) and head.id == "Annotated") or (
+ isinstance(head, ast.Attribute) and head.attr == "Annotated"
+ )
+ if not is_annotated:
+ return
+ sl = annotation.slice
+ elts = sl.elts if isinstance(sl, ast.Tuple) else [sl]
+ # elts[0] is the wrapped type; everything after it is metadata.
+ yield from elts[1:]
+
+
+def _depends_targets(default, annotation) -> list:
+ """Every ``Depends(...)``/``Security(...)`` callable name for one
+ parameter, whichever spelling is used.
+
+ A handler may express its dependency either the legacy way
+ (``x: T = Depends(f)``) or via ``Annotated``
+ (``x: Annotated[T, Depends(f)]``) — both must be detected or the census
+ silently blinds itself to every ``Annotated``-spelled route.
+ """
+ targets = []
+ t = _depends_target(default)
+ if t is not None:
+ targets.append(t)
+ for meta in _annotated_metadata(annotation):
+ t = _depends_target(meta)
+ if t is not None:
+ targets.append(t)
+ return targets
+
+
def _router_prefix(tree: ast.Module) -> str:
for node in tree.body:
if (
@@ -408,9 +454,9 @@ def _auth_dependency_names(router_tree: ast.Module) -> set:
for name, fn in list(local.items()) + list(shared.items()):
if name in resolved:
continue
- for _, default in _params(fn):
- target = _depends_target(default)
- if target in resolved:
+ for _, default, annotation in _params(fn):
+ targets = _depends_targets(default, annotation)
+ if any(t in resolved for t in targets):
resolved.add(name)
changed = True
break
@@ -435,8 +481,10 @@ def _routes_in(tree: ast.Module, module_label: str) -> list:
continue
auth_params = frozenset(
name
- for name, default in _params(node)
- if _depends_target(default) in auth_names
+ for name, default, annotation in _params(node)
+ if any(
+ t in auth_names for t in _depends_targets(default, annotation)
+ )
)
for dec in decorators:
path = (
@@ -616,12 +664,12 @@ def identity_from_request_input(route: Route) -> list:
``request.query_params`` / ``path_params`` / ``headers`` / ``cookies``.
"""
problems = []
- for name, default in _params(route.node):
+ for name, default, annotation in _params(route.node):
if name not in IDENTITY_PARAMS:
continue
if name in route.auth_params:
continue
- if _depends_target(default) is not None:
+ if _depends_targets(default, annotation):
continue
detail = ast.unparse(default) if default is not None else "<no default>"
problems.append(("parameter", name, detail, route.lineno))
@@ -773,16 +821,27 @@ def test_census_covers_every_mounted_router():
def test_route_decorators_use_only_the_idioms_the_census_understands():
"""The census reads auth off the handler SIGNATURE.
- Two idioms would make it blind: a router- or route-level
- ``dependencies=[Depends(require_auth)]`` (auth not in the signature) and
- ``Annotated[str, Depends(require_auth)]`` (auth not in the default). This
- branch uses neither. If that changes, the analyzer must be taught the new
- shape — failing here is the signal to do it, rather than letting routes
- quietly drop out of the authenticated set.
+ It understands a dependency spelled either the legacy way
+ (``x: T = Depends(require_auth)``) or inline via ``Annotated``
+ (``x: Annotated[T, Depends(require_auth)]``) — see ``_depends_targets``.
+ One idiom would still make it blind: a router- or route-level
+ ``dependencies=[Depends(require_auth)]``, which puts the dependency on
+ the decorator instead of any parameter, so there is nothing in the
+ signature to read at all. This branch uses neither dependencies= on a
+ route/router nor any other unrecognised spelling. If that changes, the
+ analyzer must be taught the new shape — failing here is the signal to do
+ it, rather than letting routes quietly drop out of the authenticated
+ set.
+
+ (Note: an ``Annotated`` dependency expressed through a module-level
+ *alias* referenced by bare name — e.g. notes.py's ``body: _NotesBody``
+ — is intentionally NOT flagged here: ``_NotesBody`` wraps a body-shape
+ validator, not an auth dependency, and every notes.py route also
+ declares ``Depends(require_auth)`` on its own ``username`` parameter, so
+ the alias carries no auth information the census needs.)
"""
blind_spots = []
for path in sorted(ROUTERS_DIR.glob("*.py")):
- source = path.read_text(encoding="utf-8")
tree = _parse(path)
for node in ast.walk(tree):
if isinstance(node, ast.Call) and any(
@@ -798,17 +857,6 @@ def test_route_decorators_use_only_the_idioms_the_census_understands():
blind_spots.append(
f"{path.name}:{node.lineno} dependencies= on {name}()"
)
- if "Annotated" in source and "Depends" in source:
- for node in ast.walk(tree):
- if (
- isinstance(node, ast.Subscript)
- and isinstance(node.value, ast.Name)
- and node.value.id == "Annotated"
- and "Depends" in ast.unparse(node)
- ):
- blind_spots.append(
- f"{path.name}:{node.lineno} Annotated[..., Depends(...)]"
- )
assert not blind_spots, _report(
"Auth is declared in a way this census cannot see. Teach the "
"analyzer these shapes before merging:",
@@ -1095,7 +1143,7 @@ def test_analytics_helpers_never_query_without_a_username():
if not opens:
continue
helpers_checked += 1
- declared = {name for name, _ in _params(node)}
+ declared = {name for name, _, _ in _params(node)}
if "username" not in declared:
violations.append(
f"metrics.py:{node.lineno} {node.name}() opens a database "
diff --git a/tests/security/test_unauthenticated_reachability_census.py b/tests/security/test_unauthenticated_reachability_census.py
index 6b6ea80ca6..e4f2c50bf2 100644
--- a/tests/security/test_unauthenticated_reachability_census.py
+++ b/tests/security/test_unauthenticated_reachability_census.py
@@ -125,12 +125,16 @@ def _module_name(path: Path) -> str:
def _params(fn):
- """Yield ``(name, default_node_or_None)`` for every declared parameter."""
+ """Yield ``(name, default_node_or_None, annotation_node_or_None)`` for
+ every declared parameter.
+ """
a = fn.args
positional = a.posonlyargs + a.args
defaults = [None] * (len(positional) - len(a.defaults)) + list(a.defaults)
- yield from zip([p.arg for p in positional], defaults)
- yield from zip([p.arg for p in a.kwonlyargs], a.kw_defaults)
+ for p, d in zip(positional, defaults):
+ yield p.arg, d, p.annotation
+ for p, d in zip(a.kwonlyargs, a.kw_defaults):
+ yield p.arg, d, p.annotation
def _depends_target(default) -> str | None:
@@ -148,6 +152,48 @@ def _depends_target(default) -> str | None:
return None
+def _annotated_metadata(annotation):
+ """Yield each metadata expression inside ``Annotated[T, meta, ...]``.
+
+ Handles both the bare-name (``Annotated[...]``) and qualified
+ (``typing.Annotated[...]``) spellings. ``ast.Subscript.slice`` is the
+ expression directly on the Python versions this project targets (3.9+),
+ so a multi-element subscript is an ``ast.Tuple``.
+ """
+ if not isinstance(annotation, ast.Subscript):
+ return
+ head = annotation.value
+ is_annotated = (isinstance(head, ast.Name) and head.id == "Annotated") or (
+ isinstance(head, ast.Attribute) and head.attr == "Annotated"
+ )
+ if not is_annotated:
+ return
+ sl = annotation.slice
+ elts = sl.elts if isinstance(sl, ast.Tuple) else [sl]
+ # elts[0] is the wrapped type; everything after it is metadata.
+ yield from elts[1:]
+
+
+def _depends_targets(default, annotation) -> list:
+ """Every ``Depends(...)``/``Security(...)`` callable name for one
+ parameter, whichever spelling is used.
+
+ A handler may express its dependency either the legacy way
+ (``x: T = Depends(f)``) or via ``Annotated``
+ (``x: Annotated[T, Depends(f)]``) — both must be detected or the census
+ silently blinds itself to every ``Annotated``-spelled route.
+ """
+ targets = []
+ t = _depends_target(default)
+ if t is not None:
+ targets.append(t)
+ for meta in _annotated_metadata(annotation):
+ t = _depends_target(meta)
+ if t is not None:
+ targets.append(t)
+ return targets
+
+
def _imports_of(tree: ast.Module, current_module: str) -> dict:
"""Map local binding name -> ``(absolute module, original name)``.
@@ -244,9 +290,9 @@ def auth_closure() -> frozenset:
for key, fn in functions.items():
if key in resolved:
continue
- for _, default in _params(fn):
- target = _depends_target(default)
- if target and _resolve(key[0], target) in resolved:
+ for _, default, annotation in _params(fn):
+ targets = _depends_targets(default, annotation)
+ if any(_resolve(key[0], t) in resolved for t in targets):
resolved.add(key)
changed = True
break
@@ -337,8 +383,8 @@ def routes_from_tree(
continue
deps = tuple(
t
- for _, default in _params(node)
- if (t := _depends_target(default)) is not None
+ for _, default, annotation in _params(node)
+ for t in _depends_targets(default, annotation)
)
decorators = _decorator_names(node)
authed = _requires_auth(module, deps, imports)
diff --git a/tests/web/dependencies/test_dependency_resolution_contracts.py b/tests/web/dependencies/test_dependency_resolution_contracts.py
index 3738cf82a4..ead461aa96 100644
--- a/tests/web/dependencies/test_dependency_resolution_contracts.py
+++ b/tests/web/dependencies/test_dependency_resolution_contracts.py
@@ -200,19 +200,51 @@ def _params_with_defaults(node):
return pairs
+def _annotated_metadata(annotation):
+ """Yield each metadata expression inside ``Annotated[T, meta, ...]``.
+
+ Handles both the bare-name (``Annotated[...]``) and qualified
+ (``typing.Annotated[...]``) spellings. ``ast.Subscript.slice`` is the
+ expression directly on the Python versions this project targets (3.9+),
+ so a multi-element subscript is an ``ast.Tuple``.
+ """
+ if not isinstance(annotation, ast.Subscript):
+ return
+ head = annotation.value
+ is_annotated = (isinstance(head, ast.Name) and head.id == "Annotated") or (
+ isinstance(head, ast.Attribute) and head.attr == "Annotated"
+ )
+ if not is_annotated:
+ return
+ sl = annotation.slice
+ elts = sl.elts if isinstance(sl, ast.Tuple) else [sl]
+ # elts[0] is the wrapped type; everything after it is metadata.
+ yield from elts[1:]
+
+
def _declared_body_params(node) -> list[tuple[str, str]]:
"""Body-bound parameters: ``Form()`` / ``File()`` / ``Body()`` defaults
and ``UploadFile`` annotations. These are the ones FastAPI resolves
from the request body, i.e. the ones that force a pre-dependency read.
+
+ A parameter may spell its body binding either the legacy way
+ (``x: T = Form()``) or via ``Annotated``
+ (``x: Annotated[T, Form()]``) -- both must be detected or this scan
+ silently blinds itself to every ``Annotated``-spelled route (which is
+ exactly what the FAST002 conversion produced for every ``Form``
+ parameter in this router directory).
"""
found = []
for arg, default in _params_with_defaults(node):
- if (
- isinstance(default, ast.Call)
- and isinstance(default.func, ast.Name)
- and default.func.id in {"Form", "File", "Body"}
- ):
- found.append((arg.arg, default.func.id))
+ candidates = [default] if default is not None else []
+ candidates += list(_annotated_metadata(arg.annotation))
+ for candidate in candidates:
+ if (
+ isinstance(candidate, ast.Call)
+ and isinstance(candidate.func, ast.Name)
+ and candidate.func.id in {"Form", "File", "Body"}
+ ):
+ found.append((arg.arg, candidate.func.id))
if arg.annotation is not None:
rendered = ast.unparse(arg.annotation)
if "UploadFile" in rendered:
@@ -220,21 +252,28 @@ def _declared_body_params(node) -> list[tuple[str, str]]:
return found
+def _depends_target(default):
+ if (
+ isinstance(default, ast.Call)
+ and isinstance(default.func, ast.Name)
+ and default.func.id == "Depends"
+ and default.args
+ ):
+ target = default.args[0]
+ return (
+ target.id
+ if isinstance(target, ast.Name)
+ else getattr(target, "attr", "")
+ )
+ return None
+
+
def _declares_require_auth(node) -> bool:
- for _arg, default in _params_with_defaults(node):
- if (
- isinstance(default, ast.Call)
- and isinstance(default.func, ast.Name)
- and default.func.id == "Depends"
- and default.args
- ):
- target = default.args[0]
- name = (
- target.id
- if isinstance(target, ast.Name)
- else getattr(target, "attr", "")
- )
- if name == "require_auth":
+ for arg, default in _params_with_defaults(node):
+ candidates = [default] if default is not None else []
+ candidates += list(_annotated_metadata(arg.annotation))
+ for candidate in candidates:
+ if _depends_target(candidate) == "require_auth":
return True
return False
diff --git a/tests/web/routers/test_library_delete_branch_outcomes.py b/tests/web/routers/test_library_delete_branch_outcomes.py
index d251e7ce68..dc71efa32f 100644
--- a/tests/web/routers/test_library_delete_branch_outcomes.py
+++ b/tests/web/routers/test_library_delete_branch_outcomes.py
@@ -115,7 +115,18 @@ def _patch_services(document=None, collection=None, bulk=None):
def _call(handler, *args, document=None, collection=None, bulk=None, **kwargs):
- """Run a handler (sync or async) with the deletion services patched."""
+ """Run a handler (sync or async) with the deletion services patched.
+
+ ``username`` is the FAST002 ``Annotated[str, Depends(require_auth)]``
+ parameter on every handler here -- Annotated carries no default (unlike
+ the pre-conversion ``= Depends(require_auth)`` spelling), so a direct
+ call bypassing FastAPI's own dependency resolution must supply it
+ explicitly or every handler call raises ``TypeError: missing 1 required
+ positional argument: 'username'``. None of these tests exercise
+ username-dependent behavior, so a fixed stand-in is injected unless a
+ caller overrides it.
+ """
+ kwargs.setdefault("username", "testuser")
patches = _patch_services(document, collection, bulk)
# The four bulk handlers hand their per-document loop to run_db_sync;
diff --git a/tests/web/routers/test_notes_body_gate_ordering.py b/tests/web/routers/test_notes_body_gate_ordering.py
index 0740efd38a..6c44f6ae40 100644
--- a/tests/web/routers/test_notes_body_gate_ordering.py
+++ b/tests/web/routers/test_notes_body_gate_ordering.py
@@ -45,9 +45,36 @@ from local_deep_research.web.routers import notes as notes_module
NOTES_PATH = Path(notes_module.__file__).resolve()
+def _annotated_aliases(tree):
+ """Map ``NAME -> Annotated[...]`` for module-level ``NAME = Annotated[...]``
+ assignments, e.g. ``_NotesBody = Annotated[..., Depends(_notes_json_body)]``.
+
+ Routes reference the dependency through this alias
+ (``body: _NotesBody``) rather than spelling ``Annotated[...]`` inline, so
+ the scan below has to resolve it to see the wrapped ``Depends(...)``.
+ """
+ aliases = {}
+ for node in tree.body:
+ if not (
+ isinstance(node, ast.Assign)
+ and len(node.targets) == 1
+ and isinstance(node.targets[0], ast.Name)
+ ):
+ continue
+ value = node.value
+ head = value.value if isinstance(value, ast.Subscript) else None
+ is_annotated = (
+ isinstance(head, ast.Name) and head.id == "Annotated"
+ ) or (isinstance(head, ast.Attribute) and head.attr == "Annotated")
+ if is_annotated:
+ aliases[node.targets[0].id] = value
+ return aliases
+
+
def _routes_with_both_deps():
"""Yield (func_name, body_index, auth_index) per decorated notes route."""
tree = ast.parse(NOTES_PATH.read_text(encoding="utf-8"))
+ aliases = _annotated_aliases(tree)
for node in tree.body:
if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
continue
@@ -61,7 +88,18 @@ def _routes_with_both_deps():
)
body_i = auth_i = None
for i, (arg, default) in enumerate(zip(args, defaults)):
- rendered = ast.unparse(default) if default is not None else ""
+ # A dependency may be spelled as a default (``x = Depends(f)``),
+ # inline ``Annotated`` (``x: Annotated[T, Depends(f)]``), or a
+ # module-level ``Annotated`` alias used as the annotation
+ # (``x: _NotesBody``) -- resolve the alias, then render both the
+ # (possibly-resolved) annotation and the default, so no spelling
+ # makes this scan blind.
+ annotation = arg.annotation
+ if isinstance(annotation, ast.Name) and annotation.id in aliases:
+ annotation = aliases[annotation.id]
+ rendered = " ".join(
+ ast.unparse(n) for n in (annotation, default) if n is not None
+ )
if "_notes_json_body" in rendered:
body_i = i
if "require_auth" in rendered:
diff --git a/tests/web/test_route_table_parity.py b/tests/web/test_route_table_parity.py
index 6b4e8b7d9c..7df407b7cd 100644
--- a/tests/web/test_route_table_parity.py
+++ b/tests/web/test_route_table_parity.py
@@ -70,6 +70,7 @@ happened before trusting the new file.
# same reason.
import ast
+import itertools
import json
import os
import re
@@ -307,6 +308,36 @@ _FLASK_CONVERTER_TO_ANNOTATION = {
_BODY_KEYS_OF_INTEREST = ("error", "detail", "message")
+def _annotated_aliases(tree: ast.Module) -> dict:
+ """Map ``NAME -> Annotated[...]`` for module-level
+ ``NAME = Annotated[...]`` assignments, e.g. notes.py's
+ ``_NotesBody = Annotated[..., Depends(_notes_json_body)]``.
+
+ A route parameter can reference a dependency through such an alias
+ (``body: _NotesBody``) instead of spelling ``Annotated[...]`` inline.
+ The alias's own AST node never appears inside the route function's
+ subtree, so a plain `ast.walk(fn)` cannot see the wrapped
+ ``Depends(...)`` (or the status codes it raises) — this lets callers
+ substitute the alias's node in before walking.
+ """
+ aliases = {}
+ for node in tree.body:
+ if not (
+ isinstance(node, ast.Assign)
+ and len(node.targets) == 1
+ and isinstance(node.targets[0], ast.Name)
+ ):
+ continue
+ value = node.value
+ head = value.value if isinstance(value, ast.Subscript) else None
+ is_annotated = (
+ isinstance(head, ast.Name) and head.id == "Annotated"
+ ) or (isinstance(head, ast.Attribute) and head.attr == "Annotated")
+ if is_annotated:
+ aliases[node.targets[0].id] = value
+ return aliases
+
+
def _module_functions(tree: ast.Module) -> dict:
"""Module-LEVEL functions only, deliberately not `ast.walk`.
@@ -336,13 +367,34 @@ def _decorator_names(fn) -> set[str]:
return names
-def _scan_one_function(fn, *, flask_side: bool):
- """-> (literal status codes, body keys of interest, bare names called)."""
+def _scan_one_function(fn, *, flask_side: bool, aliases: dict | None = None):
+ """-> (literal status codes, body keys of interest, bare names called).
+
+ ``aliases`` (FastAPI side only) maps a module-level ``Annotated[...]``
+ alias name to its AST node — e.g. notes.py's ``_NotesBody`` used as
+ ``body: _NotesBody``. A parameter annotated with such a bare-name alias
+ hides its ``Depends(...)`` behind the alias, outside `fn`'s own
+ subtree, so those params get the alias's node walked in alongside `fn`.
+ """
codes: set[int] = set()
keys: set[str] = set()
calls: set[str] = set()
- for node in ast.walk(fn):
+ extra_nodes = []
+ if aliases:
+ params = (
+ list(fn.args.posonlyargs)
+ + list(fn.args.args)
+ + list(fn.args.kwonlyargs)
+ )
+ for arg in params:
+ ann = arg.annotation
+ if isinstance(ann, ast.Name) and ann.id in aliases:
+ extra_nodes.append(aliases[ann.id])
+
+ for node in itertools.chain(
+ ast.walk(fn), *(ast.walk(n) for n in extra_nodes)
+ ):
if isinstance(node, ast.Name):
# Every bare name, not just called ones: both stacks hand
# helpers to a runner (`await run_db_sync(_start_sync)`,
@@ -406,9 +458,13 @@ def _scan_one_function(fn, *, flask_side: bool):
_SCAN_DEPTH = 2
-def _scan_view(fn, module_fns, *, flask_side: bool):
+def _scan_view(
+ fn, module_fns, *, flask_side: bool, aliases: dict | None = None
+):
"""Status codes + body keys of a view plus the helpers it reaches."""
- codes, keys, refs = _scan_one_function(fn, flask_side=flask_side)
+ codes, keys, refs = _scan_one_function(
+ fn, flask_side=flask_side, aliases=aliases
+ )
seen = {fn.name}
frontier = refs
for _ in range(_SCAN_DEPTH):
@@ -570,6 +626,7 @@ def derive_fastapi_view_table() -> list[dict]:
src = path.read_text(encoding="utf-8")
tree = ast.parse(src, filename=str(path))
module_fns = _module_functions(tree)
+ aliases = _annotated_aliases(tree)
prefix = _fastapi_router_prefix(tree) if holder == "router" else None
router_deps = _fastapi_router_dependencies(tree)
rel = path.relative_to(REPO_ROOT).as_posix()
@@ -590,7 +647,9 @@ def derive_fastapi_view_table() -> list[dict]:
if route_path is None:
continue
- codes, keys = _scan_view(node, module_fns, flask_side=False)
+ codes, keys = _scan_view(
+ node, module_fns, flask_side=False, aliases=aliases
+ )
for kw in dec.keywords:
if kw.arg == "status_code" and isinstance(
kw.value, ast.Constant