~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(web): surface a missing frontend build instead of failing silently (#5423)
LearningCircuit8ee12e4c51b4
diff --git a/src/local_deep_research/web/templates/auth/change_password.html b/src/local_deep_research/web/templates/auth/change_password.htmlindex c4bc8aa448..b741da0e77 100644--- a/src/local_deep_research/web/templates/auth/change_password.html+++ b/src/local_deep_research/web/templates/auth/change_password.html@@ -97,6 +97,7 @@</style></head><body>+ {{ vite_missing_assets_banner() }}<div class="ldr-change-password-container"><div class="ldr-change-password-header"><h1><i aria-hidden="true" class="fas fa-key"></i> Change Password</h1>diff --git a/src/local_deep_research/web/templates/auth/login.html b/src/local_deep_research/web/templates/auth/login.htmlindex 20b24d94a0..1079d89239 100644--- a/src/local_deep_research/web/templates/auth/login.html+++ b/src/local_deep_research/web/templates/auth/login.html@@ -311,6 +311,7 @@</style></head><body>+ {{ vite_missing_assets_banner() }}<div class="ldr-auth-wrapper"><div class="ldr-auth-container"><div class="ldr-auth-header">diff --git a/src/local_deep_research/web/templates/auth/register.html b/src/local_deep_research/web/templates/auth/register.htmlindex f470126d01..62c7e59476 100644--- a/src/local_deep_research/web/templates/auth/register.html+++ b/src/local_deep_research/web/templates/auth/register.html@@ -381,6 +381,7 @@</style></head><body>+ {{ vite_missing_assets_banner() }}<div class="ldr-auth-container"><div class="ldr-auth-header"><h1><i aria-hidden="true" class="fas fa-user-plus"></i> Create Account</h1>diff --git a/src/local_deep_research/web/templates/base.html b/src/local_deep_research/web/templates/base.htmlindex 9c0b6c7dc2..cc60439f94 100644--- a/src/local_deep_research/web/templates/base.html+++ b/src/local_deep_research/web/templates/base.html@@ -169,6 +169,7 @@{% block extra_head %}{% endblock %}</head><body data-scope="{{ egress_scope or 'adaptive' }}">+ {{ vite_missing_assets_banner() }}<!-- Skip to content link for keyboard/screen reader users --><a href="#main-content" class="ldr-skip-link">Skip to main content</a>diff --git a/src/local_deep_research/web/utils/vite_helper.py b/src/local_deep_research/web/utils/vite_helper.pyindex 06c4a935ce..5bf26f7020 100644--- a/src/local_deep_research/web/utils/vite_helper.py+++ b/src/local_deep_research/web/utils/vite_helper.py@@ -4,8 +4,34 @@ Handles development and production asset loading"""import json+import threadingfrom pathlib import Pathfrom markupsafe import Markup+from loguru import logger++# Emitted to the server log the first time a page is served with no Vite+# manifest (i.e. `npm run build` has never been run / assets are stale).+# Module-level flag so we warn once per process instead of on every request.+_missing_manifest_warned = False+_missing_manifest_warned_lock = threading.Lock()++# Visible, self-contained warning banner rendered when the Vite build output+# is missing. Inline styles are intentional: the real stylesheet is exactly+# what failed to load, so we can't rely on it, and the banner carries no JS+# dependency because the JS bundle is the very thing that's broken.+#+# Templates render this via `vite_missing_assets_banner()` at the top of+# <body> rather than from the `vite_asset()` call in <head> — flow content in+# <head> only renders because the HTML parser's error recovery force-opens+# <body>, which no strict parser or template test would reproduce.+_FALLBACK_BANNER = """+<div id="ldr-vite-missing-assets-banner" style="position:relative;z-index:99999;display:block;width:100%;box-sizing:border-box;background:#b91c1c;color:#ffffff;padding:12px 20px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;font-size:14px;line-height:1.5;text-align:center;border-bottom:2px solid #7f1d1d;">+ <strong>Frontend assets have not been built.</strong>+ The page below is unstyled and has no JavaScript.+ Run <code style="background:rgba(255,255,255,0.25);padding:2px 6px;border-radius:3px;font-family:monospace;">npm run build</code>+ from the project root, then reload this page. If this banner is still here afterward, restart the server too.+</div>+"""class ViteHelper:@@ -15,6 +41,12 @@ class ViteHelper:self.app = appself.manifest = Noneself.is_dev = False+ # Set by `_load_manifest()` / `init_for_fastapi()` so the+ # already-broken path (see `_refresh_manifest_if_missing`) knows+ # where to re-check for a manifest that just appeared. Stays None+ # for helpers built directly in tests, which is the signal to skip+ # any filesystem access.+ self._manifest_path = Noneif app:self.init_app(app)@@ -31,11 +63,15 @@ class ViteHelper:# Register template functionsapp.jinja_env.globals["vite_asset"] = self.vite_assetapp.jinja_env.globals["vite_hmr"] = self.vite_hmr+ app.jinja_env.globals["vite_missing_assets_banner"] = (+ self.missing_assets_banner+ )def _load_manifest(self):"""Load Vite manifest file"""static_dir = self.app.config.get("STATIC_DIR", "static")manifest_path = Path(static_dir) / "dist" / ".vite" / "manifest.json"+ self._manifest_path = manifest_pathif manifest_path.exists():with open(manifest_path, "r", encoding="utf-8-sig") as f:@@ -65,9 +101,14 @@ class ViteHelper:f'<script type="module" src="http://localhost:5173/{entry_point}"></script>')- # Production mode - use manifest+ # Production mode - use manifest. Re-check disk first: this is a+ # no-op whenever assets are already known to be present (see+ # `_refresh_manifest_if_missing`), so the healthy request path+ # still does zero extra I/O.+ self._refresh_manifest_if_missing()if not self.manifest:- # Fallback to CDN references if build hasn't run yet+ # Manifest file itself is missing - the entry name is irrelevant+ # because nothing resolves against an absent manifest.return self._fallback_assets()# Get the built file from manifest@@ -86,15 +127,99 @@ class ViteHelper:return Markup(css_tags + js_tag)- return self._fallback_assets()+ return self._fallback_assets(entry_point)++ def _fallback_assets(self, entry_point=None):+ """Fallback markup used when the Vite manifest or a requested entry+ isn't available.++ This only fires in production mode (`is_dev` is False) - dev-server+ mode returns from `vite_asset()` before ever reaching here, so it is+ never mistaken for a legitimate "no manifest yet" state. It means+ `npm run build` has never been run (or the built entry point is+ missing/stale), so we log it once and render a visible banner+ instead of silently shipping an unstyled, non-interactive page.++ ``entry_point`` is None when the manifest file itself is missing,+ and is the requested entry name (e.g. ``"js/app.js"``) when the+ manifest exists but does not contain that entry. The two cases+ are logged differently because they call for different operator+ actions (rebuild everything vs. investigate why a specific entry+ is absent from an otherwise-present manifest).+ """+ global _missing_manifest_warned+ with _missing_manifest_warned_lock:+ if not _missing_manifest_warned:+ if entry_point is None:+ logger.warning(+ "Vite manifest not found - the frontend was served "+ "without built assets (unstyled page, no JavaScript). "+ "Run 'npm run build' from the project root to generate "+ "static/dist, then restart/reload."+ )+ else:+ logger.warning(+ f"Vite manifest entry '{entry_point}' not found - "+ "this asset was served from a stale/missing build "+ "(unstyled page or missing JavaScript). Run "+ "'npm run build' from the project root to regenerate "+ "static/dist, then restart/reload."+ )+ _missing_manifest_warned = True++ return Markup(+ "\n<!-- Vite build not found - run 'npm run build' to generate production assets -->\n"+ "<!-- Using existing static files as fallback -->\n"+ )++ def _refresh_manifest_if_missing(self):+ """Re-read the manifest from disk if it is currently known to be+ missing (or missing the app entry).++ This is what lets "run `npm run build`, then reload this page"+ actually work for the `pip install -e .` / source audience this+ banner targets: `init_for_fastapi()` loads the manifest exactly+ once at process startup, and `ldr-web` runs uvicorn without+ `--reload`, so without this the in-memory manifest would stay+ stale until the operator restarts the server, no matter how many+ times they rebuild and reload.++ Only called from the already-broken path (guarded below), so a+ healthy production request — the overwhelming common case — never+ pays for a `stat()`/read here.++ A build in progress can leave `manifest.json` truncated or+ mid-write; a decode/read failure is treated the same as "still+ missing" rather than propagated, since crashing the request would+ be worse than leaving the fallback banner up for one more reload.+ """+ if self.is_dev or not self._manifest_path:+ return+ if self.manifest and "js/app.js" in self.manifest:+ return+ try:+ if self._manifest_path.exists():+ with open(self._manifest_path, "r", encoding="utf-8-sig") as f:+ manifest = json.load(f)+ if manifest:+ self.manifest = manifest+ except (OSError, ValueError):+ # ValueError covers json.JSONDecodeError (a manifest caught+ # mid-write). Keep serving the existing fallback state.+ pass++ def assets_are_missing(self) -> bool:+ """True when a production page would render without built assets."""+ if self.is_dev:+ return False+ self._refresh_manifest_if_missing()+ return not self.manifest or "js/app.js" not in self.manifest- def _fallback_assets(self):- """Fallback to existing script tags if build hasn't run"""- # This will be replaced once npm build is run- return Markup("""-<!-- Vite build not found - run 'npm run build' to generate production assets -->-<!-- Using existing static files as fallback -->- """)+ def missing_assets_banner(self):+ """Body-level banner shown when the frontend was never built."""+ if not self.assets_are_missing():+ return Markup("")+ return Markup(_FALLBACK_BANNER)def init_for_fastapi(self, static_dir, jinja2_templates):"""Initialize the helper for FastAPI (no Flask app dependency).@@ -112,6 +237,7 @@ class ViteHelper:# Load manifest using static_dir directlymanifest_path = Path(static_dir) / "dist" / ".vite" / "manifest.json"+ self._manifest_path = manifest_pathif manifest_path.exists():with open(manifest_path, "r", encoding="utf-8") as f:self.manifest = json.load(f)@@ -134,6 +260,9 @@ class ViteHelper:# Register template functions on the Jinja2 environmentjinja2_templates.env.globals["vite_asset"] = self.vite_assetjinja2_templates.env.globals["vite_hmr"] = self.vite_hmr+ jinja2_templates.env.globals["vite_missing_assets_banner"] = (+ self.missing_assets_banner+ )# Create global instancediff --git a/tests/web/utils/test_vite_helper.py b/tests/web/utils/test_vite_helper.pyindex 9258a19d19..b4017d2d72 100644--- a/tests/web/utils/test_vite_helper.py+++ b/tests/web/utils/test_vite_helper.py@@ -3,6 +3,8 @@import jsonfrom unittest.mock import Mock, patch, mock_open+import pytest+class TestViteHelperInit:"""Tests for ViteHelper initialization."""@@ -291,6 +293,23 @@ class TestViteHelperViteAsset:assert "Vite build not found" in str(result)[email protected](autouse=True)+def _reset_missing_manifest_warned():+ """Reset the module-level "already warned" guard around every test.++ `_missing_manifest_warned` is intentionally module-level state (so the+ warning fires once per process, not once per request). That means it+ leaks across tests unless we reset it, both before and after, so tests+ that check "warns" and tests that check "doesn't warn" don't depend on+ execution order.+ """+ import local_deep_research.web.utils.vite_helper as vite_helper_module++ vite_helper_module._missing_manifest_warned = False+ yield+ vite_helper_module._missing_manifest_warned = False++class TestViteHelperFallbackAssets:"""Tests for ViteHelper._fallback_assets method."""@@ -304,6 +323,356 @@ class TestViteHelperFallbackAssets:assert "Vite build not found" in str(result)assert "npm run build" in str(result)+ def test_missing_assets_banner_is_visible_and_self_contained(self):+ """The body-level banner names the problem and the fix."""+ from local_deep_research.web.utils.vite_helper import ViteHelper++ helper = ViteHelper()+ helper.is_dev = False+ helper.manifest = {}+ result_str = str(helper.missing_assets_banner())++ assert 'id="ldr-vite-missing-assets-banner"' in result_str+ assert "not been built" in result_str+ assert "npm run build" in result_str+ # Inline styles are required: the real stylesheet is what's missing.+ assert "style=" in result_str++ def test_missing_assets_banner_mentions_restart_as_a_fallback(self):+ """`npm run build` + reload alone doesn't always resolve this:+ the FastAPI startup hook only reads the manifest once at process+ startup and `ldr-web` runs uvicorn without `--reload`, so the+ banner must tell the user to restart the server too, in case the+ (best-effort) live re-check doesn't catch the rebuild."""+ from local_deep_research.web.utils.vite_helper import ViteHelper++ helper = ViteHelper()+ helper.is_dev = False+ helper.manifest = {}+ result_str = str(helper.missing_assets_banner())++ assert "restart" in result_str.lower()++ def test_missing_assets_banner_empty_when_assets_built(self):+ """A healthy production build renders no banner at all."""+ from local_deep_research.web.utils.vite_helper import ViteHelper++ helper = ViteHelper()+ helper.is_dev = False+ helper.manifest = {"js/app.js": {"file": "assets/app-abc123.js"}}++ assert str(helper.missing_assets_banner()) == ""++ def test_missing_assets_banner_empty_in_dev_mode(self):+ """Dev-server mode has no manifest by design - never banner it."""+ from local_deep_research.web.utils.vite_helper import ViteHelper++ helper = ViteHelper()+ helper.is_dev = True+ helper.manifest = None++ assert str(helper.missing_assets_banner()) == ""++ def test_fallback_assets_logs_warning_once(self):+ """Test that a server-side warning is logged the first time."""+ from local_deep_research.web.utils.vite_helper import ViteHelper++ helper = ViteHelper()++ with patch(+ "local_deep_research.web.utils.vite_helper.logger"+ ) as mock_logger:+ helper._fallback_assets()++ mock_logger.warning.assert_called_once()+ (message,), _ = mock_logger.warning.call_args+ assert "npm run build" in message++ def test_fallback_assets_with_entry_logs_entry_not_found(self):+ """When entry_point is passed, the warning names the missing entry.++ This locks the differentiated log contract: a missing manifest file+ and a missing entry inside an existing manifest are different+ operator-facing problems and must not share one vague message.+ """+ from local_deep_research.web.utils.vite_helper import ViteHelper++ helper = ViteHelper()++ with patch(+ "local_deep_research.web.utils.vite_helper.logger"+ ) as mock_logger:+ helper._fallback_assets(entry_point="js/app.js")++ mock_logger.warning.assert_called_once()+ (message,), _ = mock_logger.warning.call_args+ assert "manifest entry" in message+ assert "js/app.js" in message+ assert "manifest not found" not in message++ def test_fallback_assets_does_not_repeat_warning(self):+ """Test that the warning is only logged once across repeated calls."""+ from local_deep_research.web.utils.vite_helper import ViteHelper++ helper = ViteHelper()++ with patch(+ "local_deep_research.web.utils.vite_helper.logger"+ ) as mock_logger:+ helper._fallback_assets()+ helper._fallback_assets()+ helper._fallback_assets()++ mock_logger.warning.assert_called_once()++ def test_fallback_assets_warning_not_repeated_across_instances(self):+ """Test the guard is process/module-wide, not per-instance."""+ from local_deep_research.web.utils.vite_helper import ViteHelper++ helper_a = ViteHelper()+ helper_b = ViteHelper()++ with patch(+ "local_deep_research.web.utils.vite_helper.logger"+ ) as mock_logger:+ helper_a._fallback_assets()+ helper_b._fallback_assets()++ mock_logger.warning.assert_called_once()+++class TestViteHelperRefreshManifestIfMissing:+ """Tests for `_refresh_manifest_if_missing`, added to fix #5423's banner+ telling users to "run `npm run build`, then reload this page": the+ manifest is otherwise loaded exactly once at process startup (by the+ FastAPI startup hook) and `ldr-web` runs uvicorn without `--reload`,+ so without a re-stat, reloading after a rebuild did nothing and the+ banner's own instructions never worked for the source/`pip install -e+ .` audience it targets.+ """++ def test_no_stat_when_assets_already_present(self):+ """Healthy path: zero filesystem access on every request."""+ from pathlib import Path+ from local_deep_research.web.utils.vite_helper import ViteHelper++ helper = ViteHelper()+ helper.is_dev = False+ helper.manifest = {"js/app.js": {"file": "assets/app-abc123.js"}}+ helper._manifest_path = Path("/fake/static/dist/.vite/manifest.json")++ with patch.object(Path, "exists") as mock_exists:+ helper._refresh_manifest_if_missing()++ mock_exists.assert_not_called()++ def test_no_stat_without_a_manifest_path(self):+ """A bare `ViteHelper()` (never went through init_app or the+ FastAPI startup hook, as in most unit tests) must not touch the+ filesystem even when assets are "missing"."""+ from pathlib import Path+ from local_deep_research.web.utils.vite_helper import ViteHelper++ helper = ViteHelper()+ helper.is_dev = False+ helper.manifest = {}++ with patch.object(Path, "exists") as mock_exists:+ helper._refresh_manifest_if_missing()++ mock_exists.assert_not_called()++ def test_no_stat_in_dev_mode(self):+ """Dev-server mode never consults the manifest - never stat it."""+ from pathlib import Path+ from local_deep_research.web.utils.vite_helper import ViteHelper++ helper = ViteHelper()+ helper.is_dev = True+ helper.manifest = None+ helper._manifest_path = Path("/fake/static/dist/.vite/manifest.json")++ with patch.object(Path, "exists") as mock_exists:+ helper._refresh_manifest_if_missing()++ mock_exists.assert_not_called()++ def test_picks_up_a_manifest_that_appears_after_a_rebuild(self):+ """The scenario the banner promises: build finishes, reload finds+ it - no server restart required."""+ from pathlib import Path+ from local_deep_research.web.utils.vite_helper import ViteHelper++ helper = ViteHelper()+ helper.is_dev = False+ helper.manifest = {}+ helper._manifest_path = Path("/fake/static/dist/.vite/manifest.json")++ new_manifest = {"js/app.js": {"file": "assets/app-def456.js"}}+ with patch.object(Path, "exists", return_value=True):+ with patch(+ "builtins.open", mock_open(read_data=json.dumps(new_manifest))+ ):+ helper._refresh_manifest_if_missing()++ assert helper.manifest == new_manifest++ def test_vite_asset_reflects_a_rebuild_on_the_next_request(self):+ """End-to-end: vite_asset() itself must pick up the rebuilt+ manifest, not just the banner check - otherwise the banner could+ disappear while the page still renders the stale fallback+ comment instead of real script/link tags."""+ from pathlib import Path+ from local_deep_research.web.utils.vite_helper import ViteHelper++ helper = ViteHelper()+ helper.is_dev = False+ helper.manifest = {}+ helper._manifest_path = Path("/fake/static/dist/.vite/manifest.json")++ new_manifest = {"js/app.js": {"file": "assets/app-def456.js"}}+ with patch.object(Path, "exists", return_value=True):+ with patch(+ "builtins.open", mock_open(read_data=json.dumps(new_manifest))+ ):+ result = helper.vite_asset("js/app.js")++ assert "assets/app-def456.js" in str(result)++ def test_survives_a_manifest_caught_mid_write(self):+ """A truncated/invalid manifest.json (build still writing it) must+ not raise - the request should keep serving the fallback state+ instead of a 500."""+ from pathlib import Path+ from local_deep_research.web.utils.vite_helper import ViteHelper++ helper = ViteHelper()+ helper.is_dev = False+ helper.manifest = {}+ helper._manifest_path = Path("/fake/static/dist/.vite/manifest.json")++ with patch.object(Path, "exists", return_value=True):+ with patch("builtins.open", mock_open(read_data="{not valid json")):+ helper._refresh_manifest_if_missing() # must not raise++ assert helper.manifest == {}++ def test_missing_entry_still_triggers_a_refresh_attempt(self):+ """Manifest exists but lacks js/app.js - still worth re-reading,+ since a fresh build rewrites the whole manifest, not just the one+ entry."""+ from pathlib import Path+ from local_deep_research.web.utils.vite_helper import ViteHelper++ helper = ViteHelper()+ helper.is_dev = False+ helper.manifest = {"other/file.js": {"file": "assets/other.js"}}+ helper._manifest_path = Path("/fake/static/dist/.vite/manifest.json")++ new_manifest = {"js/app.js": {"file": "assets/app-ghi789.js"}}+ with patch.object(Path, "exists", return_value=True):+ with patch(+ "builtins.open", mock_open(read_data=json.dumps(new_manifest))+ ):+ helper._refresh_manifest_if_missing()++ assert helper.manifest == new_manifest+++class TestViteAssetWarningIntegration:+ """End-to-end coverage of vite_asset()'s warning/banner behavior."""++ def test_manifest_present_no_banner_no_warning(self):+ """Normal production path: no banner, no warning."""+ from local_deep_research.web.utils.vite_helper import ViteHelper++ helper = ViteHelper()+ helper.is_dev = False+ helper.manifest = {+ "js/app.js": {+ "file": "assets/app-abc123.js",+ "css": ["assets/app-abc123.css"],+ }+ }++ with patch(+ "local_deep_research.web.utils.vite_helper.logger"+ ) as mock_logger:+ result = helper.vite_asset("js/app.js")++ result_str = str(result)+ assert "assets/app-abc123.js" in result_str+ assert "ldr-vite-missing-assets-banner" not in result_str+ mock_logger.warning.assert_not_called()++ def test_manifest_missing_shows_banner_and_warns(self):+ """No manifest at all: fallback markup returned and warning logged."""+ from local_deep_research.web.utils.vite_helper import ViteHelper++ helper = ViteHelper()+ helper.is_dev = False+ helper.manifest = {}++ with patch(+ "local_deep_research.web.utils.vite_helper.logger"+ ) as mock_logger:+ result = helper.vite_asset("js/app.js")++ assert "Vite build not found" in str(result)+ mock_logger.warning.assert_called_once()+ # Manifest file itself is missing - operator must rebuild everything,+ # so the message names the manifest, not a specific entry.+ (message,), _ = mock_logger.warning.call_args+ assert "manifest not found" in message+ assert "manifest entry" not in message++ def test_manifest_missing_entry_shows_banner_and_warns(self):+ """Manifest exists but lacks the requested entry: fallback + warning."""+ from local_deep_research.web.utils.vite_helper import ViteHelper++ helper = ViteHelper()+ helper.is_dev = False+ helper.manifest = {"other/file.js": {"file": "assets/other.js"}}++ with patch(+ "local_deep_research.web.utils.vite_helper.logger"+ ) as mock_logger:+ result = helper.vite_asset("js/app.js")++ assert "Vite build not found" in str(result)+ mock_logger.warning.assert_called_once()+ # Manifest exists but the requested entry is absent - the message+ # must name the specific entry so the operator knows what's missing.+ (message,), _ = mock_logger.warning.call_args+ assert "manifest entry" in message+ assert "js/app.js" in message+ assert "manifest not found" not in message++ def test_dev_server_mode_never_warns_even_without_manifest(self):+ """Dev-server mode is a legitimate no-manifest state - must stay silent.++ In dev mode `vite_asset()` returns the Vite dev-server URL directly+ and never consults the manifest, so the "assets not built" warning+ (which only makes sense for the production/manifest path) must never+ fire here, even though `self.manifest` is None/unset just like the+ "never built" case.+ """+ from local_deep_research.web.utils.vite_helper import ViteHelper++ helper = ViteHelper()+ helper.is_dev = True+ helper.manifest = None++ with patch(+ "local_deep_research.web.utils.vite_helper.logger"+ ) as mock_logger:+ result = helper.vite_asset("js/app.js")++ result_str = str(result)+ assert "localhost:5173" in result_str+ assert "ldr-vite-missing-assets-banner" not in result_str+ mock_logger.warning.assert_not_called()+class TestViteSingleton:"""Tests for the singleton vite instance."""