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.

11.4 KB
Raw Blame
"""
Shared Jinja2 templates instance.

This module exists to break the circular import between fastapi_app.py
and router modules. Routers import templates from here instead of
from fastapi_app.py.
"""

from importlib import resources as importlib_resources
from pathlib import Path
from typing import Any

from fastapi.templating import Jinja2Templates
from starlette.requests import Request
from starlette.responses import Response


# Starlette's TemplateResponse(request, name, context, status_code, headers,
# media_type, background) parameters, in order.
_TEMPLATE_RESPONSE_ARGS = (
    "request",
    "name",
    "context",
    "status_code",
    "headers",
    "media_type",
    "background",
)


class _LDRTemplates(Jinja2Templates):
    """Custom Jinja2Templates that injects CSRF token + flash messages
    into every TemplateResponse, so routes can use templates.TemplateResponse
    directly without losing CSRF/flash support.
    """

    def TemplateResponse(  # noqa: N802 — match parent API
        self,
        *args: Any,
        **kwargs: Any,
    ) -> Response:
        # Normalise: support both positional and keyword forms.
        # Jinja2Templates.TemplateResponse(request, name, context, ...) OR
        # Jinja2Templates.TemplateResponse(name, context, request=, ...) (legacy) OR
        # Jinja2Templates.TemplateResponse(request=, name=, context=, ...)
        # Starlette's own form is folded into keywords first, so the context
        # the defaults go into is the one rendered: read from kwargs only, a
        # positional context was replaced by a fresh {} and then passed a
        # second time as context=, a TypeError.
        if args and isinstance(args[0], Request):
            for key, value in zip(_TEMPLATE_RESPONSE_ARGS, args):
                if key in kwargs:
                    raise TypeError(
                        f"TemplateResponse() got multiple values for argument {key!r}"
                    )
                kwargs[key] = value
            args = args[len(_TEMPLATE_RESPONSE_ARGS) :]
        elif args and isinstance(args[0], str):
            legacy_keys = _TEMPLATE_RESPONSE_ARGS[1:]
            for key, value in zip(legacy_keys, args):
                if key in kwargs:
                    raise TypeError(
                        f"TemplateResponse() got multiple values for argument {key!r}"
                    )
                kwargs[key] = value
            args = args[len(legacy_keys) :]
        context = dict(kwargs.get("context") or {})
        request = kwargs.get("request") or context.get("request")

        if request is None and args:
            # First positional could be Request
            if isinstance(args[0], Request):
                request = args[0]

        if request is not None:
            from .utils.csp import template_security_context

            security = template_security_context(request.scope)
            context["csp_nonce"] = security.nonce
            context["template_event_token"] = security.event_token
            kwargs["request"] = request
        kwargs["context"] = context

        session = getattr(request, "session", None) if request else None
        # Session is a Starlette mapping (dict-like); guard conservatively
        # — the old check `session.__class__.get` crashed when session was
        # None (NoneType has no `.get`) and was vacuously true otherwise.
        if request is not None and hasattr(session, "get"):
            # Inject session so templates can do {{ session.username }}.
            # Every base template reads session.username for the top bar.
            context.setdefault("session", session)
            from .dependencies.csrf import get_auth_context

            context["auth_context"] = get_auth_context(session)

            # Inject CSRF token if not already present
            if "csrf_token" not in context:
                from .dependencies.csrf import generate_csrf_token

                token = generate_csrf_token(request)  # gitleaks:allow
                context["csrf_token"] = lambda: token

            # Inject flash messages if not already present
            if "get_flashed_messages" not in context:
                from .dependencies.flash import get_flashed_messages

                flashes = get_flashed_messages(request, with_categories=True)
                context["get_flashed_messages"] = lambda with_categories=False: (
                    flashes if with_categories else [msg for _, msg in flashes]
                )

            kwargs["context"] = context

        # Inject frontend constants used by base.html (ports Flask's
        # inject_frontend_constants context processor from app_factory.py).
        if "research_status_enum" not in context:
            from ..constants import ResearchStatus

            terminal = [
                ResearchStatus.COMPLETED,
                ResearchStatus.SUSPENDED,
                ResearchStatus.FAILED,
                ResearchStatus.ERROR,
                ResearchStatus.CANCELLED,
            ]
            context["research_status_enum"] = {
                m.name: m.value for m in ResearchStatus
            }
            context["research_terminal_states"] = [str(s) for s in terminal]
            from ..constants import (
                DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,
                DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,
                DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC,
                DEFAULT_LOCAL_SEARCH_INDEX_TYPE,
                DEFAULT_LOCAL_SEARCH_MODEL,
                DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS,
                DEFAULT_LOCAL_SEARCH_PROVIDER,
                DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE,
                DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS,
                HISTORY_LOGS_DEFAULT_LIMIT,
                HISTORY_LOGS_HARD_CAP,
            )

            context["log_limits"] = {
                "default": HISTORY_LOGS_DEFAULT_LIMIT,
                "hard_cap": HISTORY_LOGS_HARD_CAP,
            }
            context["local_search_defaults"] = {
                "provider": DEFAULT_LOCAL_SEARCH_PROVIDER,
                "model": DEFAULT_LOCAL_SEARCH_MODEL,
                "chunk_size": DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,
                "chunk_overlap": DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,
                "splitter_type": DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE,
                "text_separators": list(DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS),
                "distance_metric": DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC,
                "normalize_vectors": DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS,
                "index_type": DEFAULT_LOCAL_SEARCH_INDEX_TYPE,
            }
            kwargs["context"] = context

        # Inject the app version for every render (main did this via
        # render_template_with_defaults' `version=__version__`). The sidebar
        # renders a version badge linking to the matching release tag; without
        # injection `version` is Undefined and every page shows an empty badge
        # pointing at .../releases/tag/v.
        if "version" not in context:
            from ..__version__ import __version__

            context["version"] = __version__
            kwargs["context"] = context

        # Inject has_encryption for every render (main did this via
        # render_template_with_defaults). settings_dashboard.html gates its
        # "Database encryption is not available" security warning on
        # `{% if not has_encryption %}`; without injection the variable is
        # Undefined → the warning renders on every page load including
        # fully encrypted installs, training users to ignore it.
        if "has_encryption" not in context:
            from ..database.encrypted_db import db_manager

            context["has_encryption"] = db_manager.has_encryption
            kwargs["context"] = context

        # Inject filesystem_pdf_storage_allowed for every render so that
        # templates (such as storage_mode_modal.html) can gate the unencrypted
        # filesystem storage option without requiring each route to remember
        # passing it.
        if "filesystem_pdf_storage_allowed" not in context:
            from ..research_library.services.pdf_storage_manager import (
                filesystem_pdf_storage_allowed,
            )

            context["filesystem_pdf_storage_allowed"] = (
                filesystem_pdf_storage_allowed()
            )
            kwargs["context"] = context

        # Inject the user's saved egress scope so base.html renders it onto
        # <body data-scope=…> on EVERY page. Previously only routes going
        # through dependencies/template_helpers.render_template got this;
        # pages using templates.TemplateResponse directly (history, metrics,
        # …) silently fell back to the module-level Jinja default, so the
        # scope-aware CSS cues vanished on those pages. Fail open to the
        # default — never crash a page render over a styling cue.
        if "egress_scope" not in context:
            from ..security.egress.policy import DEFAULT_EGRESS_SCOPE

            scope = DEFAULT_EGRESS_SCOPE
            try:
                username = (
                    session.get("username") if hasattr(session, "get") else None
                )
                if username:
                    from ..database.session_context import (
                        get_user_db_session,
                    )
                    from ..utilities.db_utils import get_settings_manager

                    with get_user_db_session(username) as db_session:
                        if db_session:
                            sm = get_settings_manager(db_session, username)
                            scope = (
                                sm.get_setting(
                                    "policy.egress_scope",
                                    DEFAULT_EGRESS_SCOPE,
                                )
                                or DEFAULT_EGRESS_SCOPE
                            )
                            # Canonicalise before it reaches the template: this collapses case
                            # and whitespace and maps invalid / retired values to the
                            # protective default. Without it a stored "STRICT" renders
                            # data-scope="STRICT", and base.html's body[data-scope="strict"]
                            # selector -- attribute values are case-sensitive -- silently stops
                            # matching, so the strict-scope visual cue disappears. Lost in the
                            # port; main applied it at app_factory.py:585.
                            from ..security.egress.policy import (
                                effective_scope_for_display,
                            )

                            scope = effective_scope_for_display(scope)
            except Exception:
                from loguru import logger

                logger.debug(
                    "Failed to read egress scope for template context",
                    exc_info=True,
                )
            context["egress_scope"] = scope
            kwargs["context"] = context

        return super().TemplateResponse(*args, **kwargs)


try:
    _PACKAGE_DIR = importlib_resources.files("local_deep_research") / "web"
    with importlib_resources.as_file(_PACKAGE_DIR) as _pkg:
        TEMPLATE_DIR = (_pkg / "templates").as_posix()
        STATIC_DIR = (_pkg / "static").as_posix()
except Exception:
    TEMPLATE_DIR = str(Path("templates").resolve())
    STATIC_DIR = str(Path("static").resolve())

templates = _LDRTemplates(directory=TEMPLATE_DIR)