~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): detect a stale Vite manifest, not just a missing one (#6193)
LearningCircuita27d3be66ad4
diff --git a/changelog.d/6193.bugfix.md b/changelog.d/6193.bugfix.mdnew file mode 100644index 0000000000..1d758d321a--- /dev/null+++ b/changelog.d/6193.bugfix.md@@ -0,0 +1,3 @@+The web server now notices a Vite frontend rebuild without being restarted, and says so out loud when it cannot serve one. `manifest.json` is re-read on every production render (bounded read plus a hash; the JSON is re-parsed only when the bytes actually change), so a `npm run build` that lands under a running server is picked up on the next page load instead of serving the previous build's hashed URLs until someone restarts. A manifest that is absent, oversized, malformed, or valid-but-pointing-at-files that are not on disk no longer degrades silently: the page carries a red "Frontend assets have not been built" banner, and the server log records the problem once per distinct cause — naming the manifest file and why it was refused when the manifest itself is unusable, and naming the entry and what is wrong with it when the manifest is fine but the entry cannot be served. A file deleted from `dist/` after its entry was already verified is picked up within a few seconds, when that verification is re-checked. A chunk the entry loads on demand (`dynamicImports`) is validated but only warns, so a missing lazily-loaded chunk degrades that one feature rather than blanking every page including login.++Asset filenames are percent-encoded in generated script and stylesheet URLs, so literal query, fragment and percent characters continue to address the verified file and cannot alter tag attributes.diff --git a/docs/FRONTEND_BUILD_SYSTEM.md b/docs/FRONTEND_BUILD_SYSTEM.mdindex 9264d09eff..349873c193 100644--- a/docs/FRONTEND_BUILD_SYSTEM.md+++ b/docs/FRONTEND_BUILD_SYSTEM.md@@ -196,7 +196,11 @@ npm outdated1. Check browser console for errors2. Verify npm packages installed: `npm install`3. Rebuild assets: `npm run build`-4. Check the server is serving from dist: look for `src/local_deep_research/web/static/dist/.vite/manifest.json`. If it is missing, the server logs a `Vite manifest not found` warning at startup.+4. Check the server is serving from dist: look for `src/local_deep_research/web/static/dist/.vite/manifest.json`. If it is missing — or present but unusable (malformed, empty, truncated) — the server logs a `No usable Vite manifest at <path>` warning at startup, plus a line naming the specific cause, and every page carries a red "Frontend assets have not been built" banner.+ A manifest that *parses* while a chunk it references is missing from `dist/` is a different, quieter case: adoption succeeds, so **nothing is logged at startup at all**. The first log line arrives at the first render that asks for the affected entry, because that is when the entry's files are checked. Watch for `Vite manifest entry '<name>' cannot be served: ...` rather than the startup warning.+ Per-entry results are asymmetric: a *positive* check (the file was found) is remembered for `_VERIFICATION_TTL_SECONDS` (5 seconds) and then re-walked, but a *negative* check (the file was missing) is never memoised and is re-walked on every render — so the manifest-parses-but-chunk-missing case above recovers on the very first render after the chunk is flushed to `dist/`; there is no window to wait out. The window matters only for the opposite change: a chunk that *was* verified present and is then deleted from `dist/` under a running server (without `manifest.json` itself changing) is not caught by a background timer between renders — nothing runs on its own — it is noticed within that window of the next render, once a render after the memo has expired asks for the entry again, rather than only at the next rebuild or restart.+ A chunk that the entry loads *on demand* (`dynamicImports` — in this build, the canvg chunk behind diagram export) is validated too, but only warns: `Vite entry '<name>' is servable, but a chunk it loads on demand is not: ...`. The page still renders, and the feature that pulls that chunk in is what fails.+ A rebuild is picked up on the next request and no restart is needed; the banner names restarting the server only as the last resort for when it survives a successful rebuild and reload.### Vite Dev Server Issues@@ -244,8 +248,14 @@ Vite automatically:The `ViteHelper` class (`src/local_deep_research/web/utils/vite_helper.py`) iswired up by `_setup_template_globals()` in `web/fastapi_app.py`, which calls-`vite.init_for_fastapi(STATIC_DIR, templates)`. That registers the `vite_asset`-and `vite_hmr` Jinja2 globals used by `templates/base.html`, and handles:+`vite.init_for_fastapi(STATIC_DIR, templates)`. That registers exactly three+Jinja2 globals — `vite_asset`, `vite_hmr` and `vite_missing_assets_banner`+(the banner is rendered at the top of `<body>`, not from the `<head>` asset+call). `templates/base.html` uses all three, and so does every template that+does not extend it: `templates/auth/login.html`,+`templates/auth/register.html` and `templates/auth/change_password.html` are+each a standalone page that calls all three globals directly. `assets_are_missing()`+is *not* a global; it is the internal predicate the banner helper calls. The helper handles:- Loading from the Vite dev server when `LDR_VITE_DEV_MODE=true`- Loading built assets from the manifest in production- Fallback if the build hasn't run yetdiff --git a/src/local_deep_research/web/utils/vite_helper.py b/src/local_deep_research/web/utils/vite_helper.pyindex 5bf26f7020..54237918c7 100644--- a/src/local_deep_research/web/utils/vite_helper.py+++ b/src/local_deep_research/web/utils/vite_helper.py@@ -1,19 +1,98 @@"""-Vite integration helper for Flask+Vite integration helper for FastAPIHandles development and production asset loading"""+import hashlibimport jsonimport threading-from pathlib import Path+import time+from dataclasses import dataclass, field+from pathlib import Path, PureWindowsPath+from typing import Any, Optional+from urllib.parse import quotefrom markupsafe import Markupfrom 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()+# Upper bound on the manifest.json bytes we are willing to read. The real+# manifest for this project is a few tens of KiB; anything vastly bigger is a+# corrupted or substituted file, and reading it whole would hand an unbounded+# allocation (and an unbounded `json.loads`) to whatever wrote it. We read one+# byte past the cap so "too large" is detected without materialising the file.+_MAX_MANIFEST_BYTES = 4 * 1024 * 1024++# Causes we have already reported, so a persistent failure logs once instead+# of once per request. Keyed by cause rather than by a single boolean: a+# second, *different* failure still gets reported instead of being swallowed+# because some earlier transient already burned the only warning. The key is+# deliberately free of the manifest fingerprint: a manifest rewritten with+# fresh garbage on every request produces new bytes but the *same* operator+# problem, and keying on the bytes would re-warn once per render. The+# fingerprint goes in the message body instead, so the one line that is+# emitted still identifies the snapshot it describes. Module-level so the+# de-duplication is process-wide, matching the "warn once per process" intent+# of the original flag.+_warned_causes = set()+_warned_causes_lock = threading.Lock()+_WARNED_CAUSES_LIMIT = 64++# Bound on remembered per-entry validation results (see `_entry_problem`).+# Concurrent renders each test this bound and then insert, so the memo can+# overshoot it by up to one entry per racing thread; it is a sanity cap on an+# otherwise unbounded key space, not an exact quota.+_VERIFIED_ENTRIES_LIMIT = 64++# How long a positive per-entry verification stays good before that entry's+# reference closure is walked again. The memo exists so the healthy path costs+# one dict lookup instead of a `resolve()` plus an `is_file()` per referenced+# path; but a memo is only *discarded* when the manifest bytes change, so+# without an expiry a verification outlives the files it verified: deleting a+# chunk from `dist/` while leaving manifest.json alone left the entry serving+# a URL for a file that is no longer there, with no banner and no log line,+# until the next rebuild or a restart. Re-walking at most once per entry per+# window bounds how long that can last; a few seconds is far below the time+# any operator needs to notice, and it keeps the steady-state cost at+# essentially the memo's.+_VERIFICATION_TTL_SECONDS = 5.0++# Bound to a module-level name so a test can drive the window with a fake+# clock instead of sleeping. Monotonic, so a wall-clock adjustment cannot make+# a memo look arbitrarily fresh (or expire it early).+_monotonic = time.monotonic+++def _warn_once(cause_key, message):+ """Log ``message`` the first time this ``cause_key`` is seen."""+ with _warned_causes_lock:+ if cause_key in _warned_causes:+ return+ if len(_warned_causes) >= _WARNED_CAUSES_LIMIT:+ # Pathological churn (e.g. a manifest whose *causes* keep+ # changing) must not grow this set without bound; dropping the+ # history costs at most a repeated warning.+ _warned_causes.clear()+ _warned_causes.add(cause_key)+ logger.warning(message)+++def _for_log(value):+ """Render a manifest-supplied string safely for a single log line.++ Manifest keys and file paths come from a JSON file on disk that this+ process does not write. A key containing a newline (or a CR, or an ANSI+ escape) would otherwise forge additional log lines - a fabricated+ "ERROR ..." record indistinguishable from a real one in any log+ aggregator. Non-printable characters are escaped and the result is+ truncated, so one bad manifest key cannot rewrite the log.+ """+ text = value if isinstance(value, str) else str(value)+ if len(text) > 200:+ text = text[:200] + "..."+ return "".join(+ character if character.isprintable() else f"\\u{ord(character):04x}"+ for character in text+ )+# Visible, self-contained warning banner rendered when the Vite build output# is missing. Inline styles are intentional: the real stylesheet is exactly@@ -29,28 +108,119 @@ _FALLBACK_BANNER = """<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.+ from the project root, then reload this page — the rebuild is picked up+ automatically, without a restart. If the banner is still here after a+ successful build and reload, the server log names the cause; restarting+ the server is the last resort.</div>"""+@dataclass(frozen=True, eq=False)+class _ManifestState:+ """Everything derived from one read of manifest.json, as one value.++ The point of grouping these is that they must be read together or not at+ all. `vite_asset()` renders from a manifest, decides whether that+ manifest's entry is servable, and reports why it isn't - three questions+ that must all be answered about the *same* snapshot. Holding them in+ separate attributes let a positive verification of manifest A be stored+ under manifest B's fingerprint (a rebuild landing between the two reads),+ after which B was served with validation skipped, durably, until its+ bytes changed again.++ So readers take `self._state` once and use only that object, and writers+ publish a whole new state in a single attribute store. The dataclass is+ frozen to make "mutate one field" impossible to write by accident.+ `verified_entries` is a mutable dict owned by *this* state: it memoises+ results for these bytes only, and a new state starts with a fresh one, so+ a memo can never outlive the manifest it describes. It cannot outlive the+ *files* it describes either by more than `_VERIFICATION_TTL_SECONDS`,+ because each result is stamped with the time it was taken and expires+ after that window.+ """++ manifest: Optional[dict] = None+ # SHA-256 of the exact manifest.json bytes that produced `manifest`, or+ # None when `manifest` did not come from a disk read (a direct+ # assignment, or a failure). Deriving it from the parsed bytes keeps the+ # pair coherent even if a rebuild replaces the file during startup, and+ # also detects a same-size rewrite whose mtime is restored or coarse.+ fingerprint: Optional[str] = None+ # SHA-256 of the last manifest.json bytes that were read and refused.+ # Acceptance is a pure function of those bytes (no filesystem lookups+ # happen during adoption), so identical bytes always get the identical+ # verdict: remembering the fingerprint lets the degraded path skip the+ # JSON parse until the file actually changes.+ rejected_fingerprint: Optional[str] = None+ # (cause, location) describing why this state has no usable manifest, or+ # None when no read has failed. Lets the fallback markup and its log+ # distinguish "no manifest file at all" from "manifest present but+ # refused", which call for different operator actions.+ failure: Optional[tuple] = None+ # Entry point -> monotonic timestamp of the check that found its whole+ # blocking reference closure on disk, for *this* manifest. Positive+ # results only: a rejected entry is re-checked on the next call so a+ # chunk that lands late is picked up without waiting for the manifest+ # bytes to change. A positive result is re-checked too, once its+ # timestamp is older than `_VERIFICATION_TTL_SECONDS`, so a file deleted+ # after the check is noticed within that window of the next render+ # rather than never - expiry is only evaluated when the entry is next+ # requested, not on a timer, so an idle server never notices on its own.+ verified_entries: dict = field(default_factory=dict)++class ViteHelper:- """Helper class for Vite integration with Flask"""+ """Helper class for Vite integration with FastAPI.++ The `init_app()` / `_load_manifest()` pair is the legacy Flask entry+ point; the shipped application reaches this class through+ `init_for_fastapi()`.+ """def __init__(self, app=None):self.app = app- self.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.+ # Set by `_load_manifest()` / `init_for_fastapi()` so+ # `_refresh_manifest_if_stale()` knows where to re-check for a+ # rebuilt/just-appeared manifest. Stays None for helpers built+ # directly in tests, which is the signal to skip any filesystem+ # access.self._manifest_path = None+ # The single coherent snapshot every reader takes a reference to.+ self._state = _ManifestState()if app:self.init_app(app)+ @property+ def manifest(self):+ """The manifest dict of the current snapshot (None before any load)."""+ return self._state.manifest++ @manifest.setter+ def manifest(self, value):+ # Assigning a manifest directly starts a brand-new snapshot: no+ # fingerprint describes these bytes (they never came from a read),+ # and no earlier verification result may carry over to them.+ self._state = _ManifestState(manifest=value)++ @property+ def _manifest_fingerprint(self):+ return self._state.fingerprint++ @property+ def _rejected_fingerprint(self):+ return self._state.rejected_fingerprint++ @property+ def _manifest_failure(self):+ return self._state.failure++ @property+ def _verified_entries(self):+ return self._state.verified_entries+def init_app(self, app):"""Initialize the helper with Flask app"""self.app = app@@ -72,13 +242,8 @@ class ViteHelper:static_dir = self.app.config.get("STATIC_DIR", "static")manifest_path = Path(static_dir) / "dist" / ".vite" / "manifest.json"self._manifest_path = manifest_path-- if manifest_path.exists():- with open(manifest_path, "r", encoding="utf-8-sig") as f:- self.manifest = json.load(f)- else:- # Fallback if manifest doesn't exist yet- self.manifest = {}+ self._state = _ManifestState(manifest={})+ self._adopt_manifest_from_disk()def vite_hmr(self):"""Return HMR client script for development"""@@ -101,119 +266,579 @@ class ViteHelper:f'<script type="module" src="http://localhost:5173/{entry_point}"></script>')- # 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:- # Manifest file itself is missing - the entry name is irrelevant- # because nothing resolves against an absent manifest.- return self._fallback_assets()+ self._refresh_manifest_if_stale()+ # Read the snapshot once into a local: a concurrent refresh (which is+ # not serialised, and really is concurrent on a free-threaded build)+ # can publish a new state at any point, and the manifest, the+ # verification verdict and the failure reason below must all describe+ # the one snapshot this call renders from.+ state = self._state+ manifest = state.manifest+ if not manifest:+ # No usable manifest at all - either the file is absent or it was+ # read and refused. The entry name is irrelevant because nothing+ # resolves against an unusable manifest; `_fallback_assets`+ # distinguishes the two causes from `state.failure`.+ return self._fallback_assets(state)++ problem = self._entry_problem(state, entry_point)+ if problem is not None:+ return self._fallback_assets(state, entry_point, problem)# Get the built file from manifest- if entry_point in self.manifest:- file_info = self.manifest[entry_point]- file_path = f"/static/dist/{file_info['file']}"+ file_info = manifest.get(entry_point)+ if not isinstance(file_info, dict):+ # Defence in depth. `_entry_problem` already established that this+ # key holds an object with a string 'file' *in this snapshot*, and+ # the snapshot cannot be swapped underneath us, but the dict it+ # points at is still shared mutable state (tests assign+ # `helper.manifest` directly, and nothing stops a future caller+ # editing it in place). Fail closed to the banner rather than+ # raise out of template rendering and 500 the page. The cause is+ # passed explicitly: the entry is present, so the default+ # "absent from the manifest" would send an operator looking for+ # a key that is sitting right there.+ return self._fallback_assets(+ state,+ entry_point,+ "its manifest entry stopped being an object after it was "+ "verified",+ )++ file_name = file_info.get("file")+ if not isinstance(file_name, str):+ # Same reasoning: a bare `file_info['file']` here turns a manifest+ # whose entry lost its 'file' key into a KeyError escaping into+ # Jinja, i.e. a 500 on every page instead of a degraded one. The+ # entry itself is present, so the cause is named rather than+ # left to the "absent from the manifest" default.+ return self._fallback_assets(+ state,+ entry_point,+ "its manifest entry has no 'file' string",+ )- # Include CSS if present- css_tags = ""- if "css" in file_info:- for css_file in file_info["css"]:- css_tags += f'<link rel="stylesheet" href="/static/dist/{css_file}">\n'+ # Encode filename characters before putting them into trusted markup.+ # A literal ?, # or % must still address the file we verified, and+ # quotes must remain URL data rather than HTML attribute delimiters.+ file_path = f"/static/dist/{quote(file_name, safe='/')}"- # Include the main JS file- js_tag = f'<script type="module" src="{file_path}"></script>'+ # Include CSS if present+ css_tags = ""+ for css_file in file_info.get("css") or ():+ css_tags += f'<link rel="stylesheet" href="/static/dist/{quote(css_file, safe="/")}">\n'- return Markup(css_tags + js_tag)+ # Include the main JS file+ js_tag = f'<script type="module" src="{file_path}"></script>'- return self._fallback_assets(entry_point)+ return Markup(css_tags + js_tag)- def _fallback_assets(self, entry_point=None):+ def _fallback_assets(self, state=None, entry_point=None, problem=None):"""Fallback markup used when the Vite manifest or a requested entry- isn't available.+ isn't usable.This only fires in production mode (`is_dev` is False) - dev-servermode returns from `vite_asset()` before ever reaching here, so it isnever 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).+ missing/stale), so we log it once per distinct cause and return HTML+ comments in place of the script and stylesheet tags. The comments+ are for whoever views source; the operator-visible signal is the+ red banner from `missing_assets_banner()`, which templates render at+ the top of `<body>`, and the log line emitted here.++ ``state`` is the snapshot the caller rendered from, so the reason+ reported here describes the same bytes the caller refused to serve+ rather than whatever the current attribute happens to hold; it+ defaults to the live snapshot for callers with nothing to render.++ ``entry_point`` is None when no manifest is in memory at all, which+ covers both "the file is absent" and "the file was read and refused";+ the snapshot's ``failure`` tells those apart, and a refusal was+ already reported by `_fail_closed()` naming the file and the cause, so+ it is not re-reported here under a misleading "manifest not found"+ headline. ``entry_point`` is the requested entry name (e.g.+ ``"js/app.js"``) when a manifest is loaded but that entry cannot be+ served, with ``problem`` naming the offending manifest key or file.+ Every caller that has an entry name also knows why that entry was+ refused and says so; the default below is only a last resort for a+ future caller that does not, so it is deliberately non-committal+ rather than asserting a specific cause it cannot know. Guessing+ "absent from the manifest" here sent operators looking for a key+ that was sitting in the file.+ The cases are logged differently because they call for different+ operator actions (rebuild everything vs. investigate one entry)."""- 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+ if state is None:+ state = self._state+ if entry_point is not None:+ problem = problem or "it is not servable from the current build"+ safe_entry = _for_log(entry_point)+ _warn_once(+ f"entry:{safe_entry}:{problem}",+ f"Vite manifest entry '{safe_entry}' cannot be served: "+ f"{problem}. This asset came from a stale or incomplete "+ "build (unstyled page or missing JavaScript). Run "+ "'npm run build' from the project root to regenerate "+ "static/dist, then reload.",+ )+ # Deliberately free of the entry name, the manifest path and the+ # hashed filename: those go to the log, which is not served to+ # every visitor, and nothing interpolated into this markup is+ # then attacker- or manifest-controlled.+ detail = (+ "the requested entry is not servable from the current "+ "build - see the server log"+ )+ elif state.failure is not None:+ cause, _location = state.failure+ # `_fail_closed()` already logged this, naming the file. `cause`+ # is one of this module's own literals.+ detail = (+ f"the manifest was read and refused ({cause}) - see the "+ "server log"+ )+ else:+ _warn_once(+ f"manifest-absent:{self._manifest_path}",+ "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 reload.",+ )+ detail = "using existing static files as fallback"return Markup("\n<!-- Vite build not found - run 'npm run build' to generate production assets -->\n"- "<!-- Using existing static files as fallback -->\n"+ f"<!-- {detail} -->\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.+ def _refresh_manifest_if_stale(self):+ """Refresh production state from a coherent manifest snapshot.++ Detecting a same-size rewrite whose mtime is restored or coarse+ requires looking at content, not metadata, so every production call+ reads and hashes the (size-capped) manifest.json. `main` did no+ filesystem work at all on the healthy path - an accurate claim there,+ and exactly why `main` can never notice a rebuild without a restart.+ This trades that for staleness detection. JSON parsing happens only+ when the bytes differ from the one fingerprint the current state+ carries - a state records either the manifest it adopted or the+ bytes it refused, never both - so a steady state, healthy or+ degraded, costs a bounded read plus a hash and no parse.++ Templates currently invoke both the asset and the banner helper, so+ each helper invocation performs this check independently, and the+ two can legitimately disagree: `vite_asset()` in `<head>` and+ `missing_assets_banner()`/`assets_are_missing()` at the top of+ `<body>` each take their own snapshot. Each is internally coherent,+ but a rebuild landing between them can put valid script tags and the+ red banner on the same page. That is a cosmetic one-render artefact,+ not a stale-URL bug, and the next render agrees with itself again.+ The corollary is the steady-state cost: a page that calls both+ helpers pays this read-plus-hash twice, once per helper, not once.++ One steady state costs more than that, and deliberately so: a+ manifest that parses fine while a file it references is missing from+ `dist/`. Adoption succeeds, so the read and hash are the small ones,+ but the *entry* is unservable and negative verification results are+ not memoised (that is what lets a chunk landing a second later be+ picked up on the very next render). Every render therefore re-walks+ that entry's blocking closure and performs a `resolve()` plus an+ `is_file()` for each path in it - so the cost of that state is+ linear in the size of the closure, not of the manifest. On the real+ 67-entry manifest, `js/app.js`'s own blocking closure is just two+ files - itself and its one stylesheet (65 of the 67 entries are+ fonts nothing asks for, and the on-demand diagram-export chunk is+ excluded from this closure by design, see `_entry_problem`) - but+ `resolve()` re-derives the real path from scratch for every+ referenced file rather than reusing the already-resolved `dist/`+ prefix, so most of the cost is stat-ing each directory component+ down to `dist/`, not the handful of files themselves. Measured+ against this repository's own checkout depth, a single degraded+ closure walk costs on the order of thirty `stat`/`lstat` syscalls,+ and a page renders both helpers (see above), so on the order of+ fifty of those syscalls are paid per page for as long as the build+ stays broken - a state an operator is expected to fix rather than+ run in. The healthy state pays the same walk once per entry per+ `_VERIFICATION_TTL_SECONDS`, which is what bounds how long a file+ deleted from `dist/` after verification can go unnoticed.++ The content hash comes from the exact bytes being parsed. A+ replacement between a read and a separate stat cannot pair manifest A+ in memory with manifest B's fingerprint: the next call hashes B and+ adopts it. Missing, oversized, malformed, or non-object manifests fail+ closed by clearing cached URLs, which activates fallback markup and+ the visible banner while a later valid build can still be adopted+ automatically."""if self.is_dev or not self._manifest_path:return- if self.manifest and "js/app.js" in self.manifest:+ self._adopt_manifest_from_disk()++ def _adopt_manifest_from_disk(self):+ """Read, parse, and adopt a coherent disk snapshot.++ The fingerprint is calculated from the exact bytes parsed below. This+ avoids a read-then-stat race at startup and ensures a same-size,+ same-mtime content rewrite is observed. It is taken before the size+ check so that an oversized manifest is remembered by the bytes that+ were actually read, exactly like every other refusal - an oversize+ refusal that stored no fingerprint left the state permanently+ "unknown", so nothing downstream could tell a repeat of the same bad+ file from a fresh one.++ Adoption itself touches only the bytes: unreadable, oversized,+ unparseable, and non-object manifests are refused, everything else is+ adopted. Whether the files a *requested* entry points at are actually+ on disk is checked per entry in `_entry_problem()`, so one dangling+ reference in an entry nothing asks for cannot blank the whole UI.+ Because adoption is a pure function of the bytes, identical bytes get+ an identical verdict - which is what makes the `rejected_fingerprint`+ fast path below safe: re-parsing refused bytes could not change the+ outcome, so the degraded path parses once, not once per request.++ A failure deliberately drops any old cached manifest rather than+ preserving URLs that a rebuild may have deleted. Adoption and refusal+ both publish one whole new `_ManifestState` in a single attribute+ store, so a concurrent reader sees either the old snapshot or the new+ one and never a mixture of the two.++ Two concurrent refreshes are not serialised, so the state that ends+ up published may be the one built from the *older* bytes. That is+ still a coherent snapshot rather than a mixture, and it self-heals:+ the next call hashes what is on disk, finds it differs from the+ fingerprint the published state carries, and adopts it.+ """+ try:+ with self._manifest_path.open("rb") as handle:+ raw_manifest = handle.read(_MAX_MANIFEST_BYTES + 1)+ except OSError:+ # Absent, unreadable (EACCES), or a directory. There is nothing to+ # fingerprint, so this is re-checked on every call: that is what+ # lets a manifest that appears later be picked up.+ self._fail_closed("no readable manifest file")+ return++ fingerprint = hashlib.sha256(raw_manifest).hexdigest()+ state = self._state+ if state.manifest and fingerprint == state.fingerprint:+ return+ if not state.manifest and fingerprint == state.rejected_fingerprint:+ return++ if len(raw_manifest) > _MAX_MANIFEST_BYTES:+ self._fail_closed(+ f"larger than the {_MAX_MANIFEST_BYTES}-byte read cap",+ fingerprint,+ )+ return++ try:+ manifest = json.loads(raw_manifest.decode("utf-8-sig"))+ except ValueError:+ self._fail_closed("not valid JSON", fingerprint)+ return+ except RecursionError:+ # Deeply nested JSON exhausts the interpreter's stack rather than+ # raising ValueError; without this the exception would escape into+ # template rendering and 500 every page instead of degrading.+ self._fail_closed("nested too deeply to parse", fingerprint)+ return++ if not isinstance(manifest, dict) or not manifest:+ self._fail_closed("not a non-empty JSON object", fingerprint)+ return++ self._state = _ManifestState(manifest=manifest, fingerprint=fingerprint)++ def _fail_closed(self, cause, fingerprint=None):+ """Drop the cached manifest and report why, once per distinct cause.++ "Distinct cause" means the (location, cause) pair, not the bytes: a+ manifest being rewritten with fresh garbage produces a new+ fingerprint on every render while remaining the *same* problem for+ the operator, and keying the de-duplication on the bytes turned "warn+ once" into one warning per render. The fingerprint is named in the+ message instead, so the single line that is emitted still identifies+ which bytes it looked at.+ """+ location = self._manifest_path+ self._state = _ManifestState(+ manifest={},+ rejected_fingerprint=fingerprint,+ failure=(+ cause,+ str(location) if location is not None else "<unknown path>",+ ),+ )+ if location is None or self.is_dev:+ # Nothing to name, or dev mode - where the manifest is expected to+ # be absent because Vite serves from memory.return+ seen = (+ f" (sha256 {fingerprint[:12]})" if fingerprint is not None else ""+ )+ _warn_once(+ f"manifest:{location}:{cause}",+ f"Vite manifest at {location} is unusable ({cause}){seen}; the "+ "frontend is being served without built assets (unstyled page, "+ "no JavaScript). Run 'npm run build' from the project root, "+ "then reload.",+ )++ @staticmethod+ def _is_contained_file(dist_root, relative_path):+ """True when ``relative_path`` names a real file inside ``dist_root``.++ The path has to be *relative*, has to name a file, and has to be+ written in already-normalised form, because the very same string is+ percent-encoded into a URL as `/static/dist/<path>`. Anything pathlib folds+ away silently is therefore a trap: this function verifies one path+ and the browser then requests another.++ `dist_root / relative_path` lets an absolute operand win, so an+ absolute path pointing at a file *inside* dist/ passed containment+ and `is_file()`, and then rendered a `src` that concatenated the+ static prefix with the server's own directory layout - a 404 that+ publishes that layout to every visitor. A trailing slash, a doubled+ separator, a `.` segment and a `..` segment are the same shape of+ bug: `js/app.js/`, `js//app.js` and `js/app.js/.` all resolve to the+ same file here and all render URLs that no static handler maps back+ to the file that was checked. Reject the lot rather than serve a URL+ that only looks verified.+ """+ if not isinstance(relative_path, str) or not relative_path:+ return False+ # Segment-level check on the raw string, before pathlib sees it. An+ # empty segment covers a leading separator, a trailing separator and+ # `a//b`; `.` and `..` cover the segments pathlib would fold away.+ # Both separators are inspected because nothing guarantees the+ # manifest was written on this platform.+ for separator in ("/", "\\"):+ if any(+ segment in ("", ".", "..")+ for segment in relative_path.split(separator)+ ):+ return False+ if PureWindowsPath(relative_path).drive:+ return Falsetry:- 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+ # URL paths use UTF-8; a filesystem surrogate cannot be served+ # through that encoding even if this host can store its bytes.+ relative_path.encode("utf-8")+ target = (dist_root / relative_path).resolve()+ return target.is_relative_to(dist_root) and target.is_file()except (OSError, ValueError):- # ValueError covers json.JSONDecodeError (a manifest caught- # mid-write). Keep serving the existing fallback state.- pass+ return False++ def _entry_problem(self, state, entry_point):+ """Return None if ``entry_point`` is servable, else why it isn't.++ ``state`` is the snapshot to answer the question about, passed in+ rather than re-read from `self`: the verdict, the manifest it+ describes and the memo it is recorded in have to be the same+ snapshot, or a verification of manifest A gets stored against+ manifest B and B is then served with validation skipped.++ Validation is scoped to what serving this entry actually needs: the+ entry itself, its `css`, and the transitive closure of its `imports`.+ Entries outside that closure are irrelevant - the manifest's 60-odd+ font entries are never `vite_asset()` targets (every template asks for+ `js/app.js`), and one font missing from `dist/` must not take the+ whole UI down when on `main` it cost a single 404.++ `dynamicImports` are deliberately *outside* the blocking closure.+ They are the chunks the browser fetches later, on demand: the real+ `js/app.js` entry lazily imports a canvg chunk that only the diagram+ export path ever needs, and letting it gate the closure means one+ unflushed lazy chunk blanks every page including the login form. They+ are still walked, and a problem in them is warned about once, because+ an operator does want to know that a feature will fail when it is+ reached - but it degrades one feature rather than the whole app.++ Every path that *is* reached must resolve to a real file inside+ `dist/`, so a symlink pointing out of the tree, or a chunk that has+ not been flushed yet, is refused. Cycles terminate; dangling manifest+ references are refused. Positive results are remembered in this+ state's own memo, so the healthy path costs one dict lookup for+ `_VERIFICATION_TTL_SECONDS` and then one closure walk; negative ones+ are not remembered at all, so a late-arriving chunk recovers on the+ very next call. The expiry is what keeps the memo from outliving the+ files it describes: manifest.json is not rewritten when a chunk is+ deleted from `dist/`, so nothing else would ever invalidate it.+ """+ verified = state.verified_entries+ verified_at = verified.get(entry_point)+ if verified_at is not None:+ # Clamped so a clock that runs backwards (a fake clock in a test,+ # or a real one stepped back by NTP) cannot produce a negative+ # delta and make this memo look permanently fresh.+ age = max(0.0, _monotonic() - verified_at)+ if age < _VERIFICATION_TTL_SECONDS:+ return None++ manifest = state.manifest+ dist_root = None+ if self._manifest_path is not None:+ try:+ dist_root = self._manifest_path.parent.parent.resolve()+ except OSError:+ return "the dist/ directory could not be resolved"++ deferred: list[tuple[str, Any]] = []+ problem = self._closure_problem(+ manifest, dist_root, [entry_point], deferred+ )+ if problem is not None:+ return problem++ if deferred:+ lazy_problem = self._lazy_closure_problem(+ manifest, dist_root, deferred+ )+ if lazy_problem is not None:+ safe_entry = _for_log(entry_point)+ _warn_once(+ f"lazy:{safe_entry}:{lazy_problem}",+ f"Vite entry '{safe_entry}' is servable, but a chunk it "+ f"loads on demand is not: {lazy_problem}. The page will "+ "render; the feature that pulls that chunk in will fail "+ "at runtime. Run 'npm run build' from the project root "+ "to regenerate static/dist, then reload.",+ )++ # Remembering more than the bound is refused rather than handled by+ # clearing: entry points come from templates, so a real deployment+ # has one or two, and this dict is discarded wholesale the moment the+ # manifest bytes change. Never clearing it also means a concurrent+ # reader's lookup cannot race a wipe. Re-stamping an entry that is+ # already remembered is always allowed, so a full memo cannot pin an+ # entry to a timestamp that never advances.+ if entry_point in verified or len(verified) < _VERIFIED_ENTRIES_LIMIT:+ verified[entry_point] = _monotonic()+ return None++ @classmethod+ def _closure_problem(cls, manifest, dist_root, roots, deferred):+ """Walk the reference closure from ``roots``; return the first problem.++ ``deferred`` is a list that collects ``(key, dynamicImports value)``+ pairs instead of following them - the blocking pass, which must not+ let a lazily-loaded chunk decide whether the page renders at all.+ Pass None to follow `dynamicImports` inline, which is what the+ advisory pass does.+ """+ pending = list(roots)+ visited = set()+ while pending:+ key = pending.pop()+ if key in visited:+ continue+ visited.add(key)++ entry = manifest.get(key)+ if not isinstance(entry, dict):+ return (+ f"manifest key '{_for_log(key)}' is absent or not an object"+ )++ file_path = entry.get("file")+ if not isinstance(file_path, str):+ return f"manifest key '{_for_log(key)}' has no 'file' string"+ if dist_root is not None and not cls._is_contained_file(+ dist_root, file_path+ ):+ return (+ f"'{_for_log(file_path)}' (manifest key "+ f"'{_for_log(key)}') is not a file inside dist/"+ )++ css_paths = entry.get("css")+ if css_paths is not None:+ if not isinstance(css_paths, list):+ return (+ f"manifest key '{_for_log(key)}' has a non-list 'css'"+ )+ for css_path in css_paths:+ if not isinstance(css_path, str):+ return (+ f"manifest key '{_for_log(key)}' has a "+ "non-string CSS entry"+ )+ if dist_root is not None and not cls._is_contained_file(+ dist_root, css_path+ ):+ return (+ f"'{_for_log(css_path)}' (manifest key "+ f"'{_for_log(key)}') is not a file inside dist/"+ )++ fields = ["imports"]+ if deferred is None:+ fields.append("dynamicImports")+ elif entry.get("dynamicImports") is not None:+ deferred.append((key, entry.get("dynamicImports")))++ for field_name in fields:+ references = entry.get(field_name)+ if references is None:+ continue+ if not isinstance(references, list):+ return (+ f"manifest key '{_for_log(key)}' has a non-list "+ f"'{field_name}'"+ )+ for reference in references:+ if not isinstance(reference, str):+ return (+ f"manifest key '{_for_log(key)}' has a "+ f"non-string '{field_name}' reference"+ )+ if reference not in manifest:+ return (+ f"manifest key '{_for_log(key)}' imports "+ f"'{_for_log(reference)}', which the manifest "+ "does not define"+ )+ pending.append(reference)++ return None++ @classmethod+ def _lazy_closure_problem(cls, manifest, dist_root, deferred):+ """Validate the on-demand closure; a problem here is advisory only."""+ roots = []+ for key, references in deferred:+ if not isinstance(references, list):+ return (+ f"manifest key '{_for_log(key)}' has a non-list "+ "'dynamicImports'"+ )+ for reference in references:+ if not isinstance(reference, str):+ return (+ f"manifest key '{_for_log(key)}' has a non-string "+ "'dynamicImports' reference"+ )+ if reference not in manifest:+ return (+ f"manifest key '{_for_log(key)}' lazily imports "+ f"'{_for_log(reference)}', which the manifest does "+ "not define"+ )+ roots.append(reference)+ return cls._closure_problem(manifest, dist_root, roots, None)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+ self._refresh_manifest_if_stale()+ state = self._state+ if not state.manifest:+ return True+ return self._entry_problem(state, "js/app.js") is not Nonedef missing_assets_banner(self):"""Body-level banner shown when the frontend was never built."""@@ -235,27 +860,29 @@ class ViteHelper:self.is_dev = bool(get_env_setting("vite.dev_mode", False))- # Load manifest using static_dir directlymanifest_path = Path(static_dir) / "dist" / ".vite" / "manifest.json"self._manifest_path = manifest_path- if manifest_path.exists():- with open(manifest_path, "r", encoding="utf-8") as f:- self.manifest = json.load(f)- elif self.is_dev:- # Dev mode: manifest absent is expected (Vite serves from memory).- self.manifest = {}- else:- # Prod mode: manifest missing is a real problem — warn loudly- # instead of silently serving a blank page.- from loguru import logger-+ self._state = _ManifestState(manifest={})+ self._adopt_manifest_from_disk()++ if not self.manifest and not self.is_dev:+ # Prod mode: no usable manifest is a real problem — warn loudly+ # instead of silently serving a blank page. This covers a+ # manifest that is present but was refused, not only an absent+ # one: both render the same assetless page, and gating on+ # `manifest_path.exists()` would stay silent for the former.+ #+ # A manifest that *parses* while a chunk it references is missing+ # is not covered here and cannot be: adoption succeeds, so this+ # branch is not taken, and the problem only surfaces when an+ # entry is actually requested. Its first log line therefore+ # arrives at the first render, not at startup.logger.warning(- f"Vite manifest not found at {manifest_path}. "+ f"No usable Vite manifest at {manifest_path}. ""Run `npm run build` to generate production assets, or ""set LDR_VITE_DEV_MODE=true and run `npm run dev`. ""The app will render without JS/CSS until this is fixed.")- self.manifest = {}# Register template functions on the Jinja2 environmentjinja2_templates.env.globals["vite_asset"] = self.vite_assetdiff --git a/tests/web/test_vite_asset_pipeline.py b/tests/web/test_vite_asset_pipeline.pyindex ef003f9d58..79971e08b8 100644--- a/tests/web/test_vite_asset_pipeline.py+++ b/tests/web/test_vite_asset_pipeline.py@@ -20,11 +20,15 @@ have a manifest?) comes first, then what the app does when it does not."""import ast+import hashlib+import ioimport jsonimport reimport subprocessimport typesfrom contextlib import contextmanager+from html.parser import HTMLParser+from urllib.parse import unquote, urlsplitfrom pathlib import Pathimport jinja2@@ -444,6 +448,56 @@ class TestManifestPathContract:class TestMissingOrBrokenManifest:"""Missing / empty / malformed manifest: loud or silently broken?"""+ def test_a_rebuild_landing_during_startup_reaches_the_first_render(+ self, tmp_path, monkeypatch+ ):+ """Catches fingerprinting the file instead of the bytes that were read.++ The startup read returns the old manifest and the rebuild lands+ immediately afterwards. The fingerprint stored at startup must be+ sha256 of the bytes now in ``helper.manifest`` (the old ones), not of+ whatever the file holds by the time it is taken: pair the old data+ with the new file's key and the next request sees "unchanged" and+ serves OLDHASH URLs at files ``emptyOutDir`` has already deleted.+ """+ monkeypatch.delenv(DEV_MODE_ENV_VAR, raising=False)+ old_manifest = {"js/app.js": {"file": "js/app.OLDHASH.js"}}+ new_manifest = {"js/app.js": {"file": "js/app.NEWHASH.js"}}+ manifest_path = _write_manifest(tmp_path, old_manifest)+ for relative_path in ("js/app.OLDHASH.js", "js/app.NEWHASH.js"):+ output = tmp_path / "dist" / relative_path+ output.parent.mkdir(parents=True, exist_ok=True)+ output.write_text("// built", encoding="utf-8")++ original = manifest_path.read_bytes()+ replacement = json.dumps(new_manifest).encode("utf-8")+ real_open = Path.open+ swapped = False++ def open_then_swap(path, *args, **kwargs):+ """Serve the pre-rebuild bytes, then let the rebuild land."""+ nonlocal swapped+ if path != manifest_path or swapped:+ return real_open(path, *args, **kwargs)+ swapped = True+ manifest_path.write_bytes(replacement)+ return io.BytesIO(original)++ monkeypatch.setattr(Path, "open", open_then_swap)+ helper = _fresh_helper()+ stub, env = _templates_stub()+ helper.init_for_fastapi(str(tmp_path), stub)++ assert manifest_path.read_bytes() == replacement+ assert helper.manifest == old_manifest+ assert (+ helper._manifest_fingerprint == hashlib.sha256(original).hexdigest()+ )++ html = env.from_string("{{ vite_asset('js/app.js') }}").render()+ assert helper.manifest == new_manifest+ assert "js/app.NEWHASH.js" in html+def test_missing_manifest_warns_then_serves_a_page_with_no_assets(self, tmp_path, monkeypatch):@@ -491,18 +545,20 @@ class TestMissingOrBrokenManifest:assert helper.is_dev is Trueassert not [m for m in warnings if "Vite manifest not found" in str(m)]- def test_an_empty_json_object_manifest_is_broken_with_no_warning(+ def test_an_empty_json_object_manifest_is_refused_and_warns(self, tmp_path, monkeypatch):- """DEFECT: a ``{}`` manifest is indistinguishable from a good one.-- The existence check passes, so the loud warning never fires, yet- ``vite_asset`` falls through to the same empty comment. A- truncated or partially-written build therefore produces a- completely silent, completely JS-less deployment.+ """Catches gating the startup warning on ``manifest_path.exists()``.++ A ``{}`` manifest passes an existence check, so a presence-gated+ warning stays silent while ``vite_asset`` falls through to the empty+ comment: a truncated or partially-written build ships a completely+ silent, completely JS-less deployment. The warning has to key off+ "is there a usable manifest in memory", and it has to name the file+ so the operator is not sent looking for a missing one."""monkeypatch.delenv(DEV_MODE_ENV_VAR, raising=False)- _write_manifest(tmp_path, {})+ manifest_path = _write_manifest(tmp_path, {})helper = _fresh_helper()stub, env = _templates_stub()@@ -510,9 +566,9 @@ class TestMissingOrBrokenManifest:helper.init_for_fastapi(str(tmp_path), stub)assert helper.manifest == {}- assert not [m for m in warnings if "manifest" in str(m).lower()], (- "an empty manifest now warns -- good; tighten this test"- )+ joined = "\n".join(str(m) for m in warnings)+ assert str(manifest_path) in joined+ assert "not a non-empty JSON object" in joinedhtml = env.from_string("{{ vite_asset('js/app.js') }}").render()assert "Vite build not found" in html@@ -526,6 +582,9 @@ class TestMissingOrBrokenManifest:_write_manifest(tmp_path, {"js/main.js": {"file": "js/main.abc12345.js"}})+ output = tmp_path / "dist" / "js" / "main.abc12345.js"+ output.parent.mkdir(parents=True, exist_ok=True)+ output.write_text("// built", encoding="utf-8")helper = _fresh_helper()stub, env = _templates_stub()helper.init_for_fastapi(str(tmp_path), stub)@@ -542,85 +601,122 @@ class TestMissingOrBrokenManifest:("html-error-page", "<!doctype html><h1>502</h1>"),],)- def test_a_malformed_manifest_kills_startup_not_the_request(+ def test_a_malformed_manifest_fails_closed_at_startup(self, tmp_path, monkeypatch, label, raw):- """Malformed JSON raises out of ``init_for_fastapi`` uncaught.+ """Malformed bytes must degrade at startup and allow later recovery.- Loud rather than silent -- but it surfaces as a bare- ``JSONDecodeError`` during module import (see- ``test_manifest_load_runs_at_import_with_no_error_handling``),- with none of the remediation text the missing-manifest path took- the trouble to write.+ Truncated JSON, an empty file and an HTML error page all fail JSON+ decoding. Without the ValueError guard, each aborts initialization.+ The separate empty-object case covers the manifest-shape check.+ A later valid build must be adopted without restarting the helper."""monkeypatch.delenv(DEV_MODE_ENV_VAR, raising=False)_write_manifest(tmp_path, None, raw=raw)helper = _fresh_helper()- stub, _env = _templates_stub()+ stub, env = _templates_stub()+ helper.init_for_fastapi(str(tmp_path), stub)- with pytest.raises(json.JSONDecodeError):- helper.init_for_fastapi(str(tmp_path), stub)+ assert helper.manifest == {}+ html = env.from_string("{{ vite_asset('js/app.js') }}").render()+ assert "Vite build not found" in html+ assert "ldr-vite-missing-assets-banner" in str(+ helper.missing_assets_banner()+ )- def test_a_bom_prefixed_manifest_regressed_against_the_flask_reader(+ payload = {"js/app.js": {"file": "js/app.abc12345.js"}}+ _write_manifest(tmp_path, payload)+ output = tmp_path / "dist" / "js" / "app.abc12345.js"+ output.parent.mkdir(parents=True, exist_ok=True)+ output.write_text("// built", encoding="utf-8")++ assert (+ "js/app.abc12345.js"+ in env.from_string("{{ vite_asset('js/app.js') }}").render()+ )++ def test_a_bom_prefixed_manifest_is_tolerated_by_the_one_reader(self, tmp_path, monkeypatch):- """DEFECT: the port narrowed ``utf-8-sig`` to ``utf-8``.-- The Flask ``_load_manifest`` opened the manifest with- ``encoding="utf-8-sig"`` and so tolerated a BOM (what a- Windows/PowerShell-mediated build or an editor round-trip can- leave behind). ``init_for_fastapi`` opens it as plain ``utf-8``,- where the BOM becomes a leading U+FEFF and the app cannot even- import. Both halves are executed here.+ """Catches a revert to ``decode("utf-8")`` in the single reader.++ The Flask and FastAPI entry points both delegate to+ ``_adopt_manifest_from_disk``, so BOM tolerance lives in exactly one+ place -- asserting it twice would only exercise the same branch+ twice. What is worth pinning is that the two entry points really do+ converge: they must end up with the same parsed manifest *and* the+ same fingerprint for identical bytes, because a second reader with+ its own decoding rules is how the two paths would drift apart."""monkeypatch.delenv(DEV_MODE_ENV_VAR, raising=False)payload = {"js/app.js": {"file": "js/app.abc12345.js"}}_write_manifest(tmp_path, None, raw="\ufeff" + json.dumps(payload))+ output = tmp_path / "dist" / "js" / "app.abc12345.js"+ output.parent.mkdir(parents=True, exist_ok=True)+ output.write_text("// built", encoding="utf-8")helper = _fresh_helper()stub, _env = _templates_stub()- with pytest.raises(json.JSONDecodeError):- helper.init_for_fastapi(str(tmp_path), stub)+ helper.init_for_fastapi(str(tmp_path), stub)+ assert helper.manifest == payload, (+ "the BOM a Windows editor leaves on manifest.json is no longer "+ "stripped; a valid build now reads as malformed"+ )- # The dead Flask path, called explicitly, still reads it fine.flask_helper = _fresh_helper()flask_helper.app = types.SimpleNamespace(config={"STATIC_DIR": str(tmp_path)})flask_helper._load_manifest()- assert flask_helper.manifest == payload, (- "utf-8-sig tolerance is gone from the Flask reader too; the "- "regression framing of this test needs revisiting"+ assert (+ flask_helper.manifest,+ flask_helper._manifest_fingerprint,+ ) == (helper.manifest, helper._manifest_fingerprint), (+ "the Flask and FastAPI entry points no longer share one reader")- def test_a_manifest_entry_without_a_file_key_raises_at_render_time(+ def test_a_manifest_entry_without_a_file_key_fails_closed_at_render_time(self, tmp_path, monkeypatch):- """Structurally wrong manifests escape startup and 500 per request.-- Only ``json.load`` guards the manifest -- its *shape* is never- checked -- so an entry carrying CSS but no ``file`` (or any- third-party/handwritten manifest) blows up inside template- rendering, i.e. on every page view rather than once at boot.+ """Catches dropping the per-entry `'file'` string check.++ This manifest is perfectly good JSON and its stylesheet really is on+ disk, so adoption succeeds and startup says nothing - the entry is+ only unservable at render time, which is exactly the case+ `_entry_problem()` exists for. Remove that check and the render path+ emits the <link> tags and then subscripts a key that isn't there,+ turning a degraded page into a KeyError out of Jinja on every+ request."""monkeypatch.delenv(DEV_MODE_ENV_VAR, raising=False)_write_manifest(tmp_path, {"js/app.js": {"css": ["css/styles.abc12345.css"]}})+ stylesheet = tmp_path / "dist" / "css" / "styles.abc12345.css"+ stylesheet.parent.mkdir(parents=True, exist_ok=True)+ stylesheet.write_text("/* built */", encoding="utf-8")helper = _fresh_helper()stub, env = _templates_stub()helper.init_for_fastapi(str(tmp_path), stub)- with pytest.raises(KeyError, match="file"):- env.from_string("{{ vite_asset('js/app.js') }}").render()-- def test_manifest_load_runs_at_import_with_no_error_handling(self):- """Locates the blast radius of the JSONDecodeError above.+ html = env.from_string("{{ vite_asset('js/app.js') }}").render()+ assert "Vite build not found" in html+ assert "ldr-vite-missing-assets-banner" in str(+ helper.missing_assets_banner()+ )- ``_setup_template_globals()`` is invoked at ``fastapi_app`` module- scope and calls ``vite.init_for_fastapi`` with no ``try``- around it, so a malformed manifest is an import-time crash of the- web app, not a degraded page.+ def test_manifest_setup_runs_at_import_and_its_caller_does_not_catch(+ self,+ ):+ """The manifest read happens at import, unguarded *by its caller*.++ ``init_for_fastapi`` has plenty of error handling of its own -- it+ fails closed on every unusable manifest -- so the property here is+ narrower than "no error handling": ``_setup_template_globals`` runs+ at module scope and does not wrap the call in ``try``, which is what+ makes an unexpected failure abort the import rather than degrade+ invisibly. Both halves are asserted below; the name used to promise+ the broader, false claim."""tree = _module_ast(FASTAPI_APP_PY)@@ -713,6 +809,13 @@ class TestDevProdSwitch:}}_write_manifest(tmp_path, payload)+ for relative_path in (+ "js/app.abc12345.js",+ "css/styles.def67890.css",+ ):+ output = tmp_path / "dist" / relative_path+ output.parent.mkdir(parents=True, exist_ok=True)+ output.write_text("// built", encoding="utf-8")helper = _fresh_helper()stub, env = _templates_stub()helper.init_for_fastapi(str(tmp_path), stub)@@ -820,8 +923,21 @@ class TestDevProdSwitch:# ----------------------------------------------------------------------------class TestManifestValuesReachHtmlUnescaped:- """Manifest strings are interpolated into markup with no escaping."""+class TestManifestAssetUrls:+ """Manifest filenames stay URL data inside generated script/link tags.++ The helper now percent-encodes asset paths before marking the tags safe.+ These regressions require exactly the intended attributes and elements,+ while retaining the original filename after URL decoding.+ """++ class Tags(HTMLParser):+ def __init__(self):+ super().__init__()+ self.tags = []++ def handle_starttag(self, tag, attrs):+ self.tags.append((tag, dict(attrs)))PAYLOAD_FILE = 'js/app.abc12345.js" onload="alert(1)'PAYLOAD_CSS = 'css/x.css"><script>alert(1)</script><link href="'@@ -829,6 +945,10 @@ class TestManifestValuesReachHtmlUnescaped:def _render_with(self, tmp_path, entry, monkeypatch):monkeypatch.delenv(DEV_MODE_ENV_VAR, raising=False)_write_manifest(tmp_path, {"js/app.js": entry})+ for relative_path in [entry["file"], *entry.get("css", [])]:+ output = tmp_path / "dist" / relative_path+ output.parent.mkdir(parents=True, exist_ok=True)+ output.write_text("// built", encoding="utf-8")helper = _fresh_helper()stub, env = _templates_stub()helper.init_for_fastapi(str(tmp_path), stub)@@ -854,47 +974,54 @@ class TestManifestValuesReachHtmlUnescaped:)assert "<script>alert(1)</script>" not in escaped- def test_the_file_value_lands_in_the_src_attribute_unescaped(+ def test_file_value_stays_inside_the_encoded_src_attribute(self, tmp_path, monkeypatch):- """``file`` is f-string-interpolated then wrapped in ``Markup``.-- Severity is bounded -- the manifest is a build artefact, not user- input -- but there is no defence in depth: anything that can- influence the built manifest (a compromised or misconfigured- frontend dependency emitting a crafted asset name) writes raw- markup into every page. ``markupsafe.escape`` on the two- interpolated values would cost nothing.+ """Encoding replaces the previous raw filename interpolation.++ A quote in a valid local filename must not introduce an event+ attribute, and the emitted URL must still address that filename."""_env, html = self._render_with(tmp_path, {"file": self.PAYLOAD_FILE}, monkeypatch)- assert f'src="/static/dist/{self.PAYLOAD_FILE}"' in html, (- f"expected the payload verbatim inside src=; got {html!r}"- )- assert """ not in html and """ not in html, (- "the file value is now escaped -- good; invert this test"- )- assert 'onload="alert(1)"' in html, (- "the injected attribute did not break out of src=; re-derive "- "the payload before weakening this assertion"- )-- def test_css_entries_can_close_the_link_tag_and_open_a_script(+ parser = self.Tags()+ parser.feed(html)+ assert len(parser.tags) == 1+ tag, attrs = parser.tags[0]+ assert tag == "script"+ assert set(attrs) == {"type", "src"}+ assert attrs["type"] == "module"+ url = urlsplit(attrs["src"])+ assert not url.query and not url.fragment+ assert unquote(url.path) == f"/static/dist/{self.PAYLOAD_FILE}"++ def test_css_filename_cannot_create_additional_elements(self, tmp_path, monkeypatch):- """Same hole on the stylesheet branch of ``vite_asset``."""+ """CSS filenames are encoded by the same production URL contract.++ The previous raw interpolation could terminate a link tag. The+ filename now stays in href while the ordinary app script survives.+ """_env, html = self._render_with(tmp_path,{"file": "js/app.abc12345.js", "css": [self.PAYLOAD_CSS]},monkeypatch,)- assert "<script>alert(1)</script>" in html, (- f"expected a raw injected script element; got {html!r}"- )- assert "<script>" not in html, (- "css entries are now escaped -- good; invert this test"- )+ parser = self.Tags()+ parser.feed(html)+ assert [tag for tag, _ in parser.tags] == ["link", "script"]+ attrs = parser.tags[0][1]+ assert set(attrs) == {"rel", "href"}+ assert attrs["rel"] == "stylesheet"+ url = urlsplit(attrs["href"])+ assert not url.query and not url.fragment+ assert unquote(url.path) == f"/static/dist/{self.PAYLOAD_CSS}"+ assert parser.tags[1][1] == {+ "type": "module",+ "src": "/static/dist/js/app.abc12345.js",+ }# ---------------------------------------------------------------------------diff --git a/tests/web/utils/test_vite_helper.py b/tests/web/utils/test_vite_helper.pyindex b4017d2d72..b1fa824207 100644--- a/tests/web/utils/test_vite_helper.py+++ b/tests/web/utils/test_vite_helper.py@@ -1,7 +1,12 @@"""Tests for web/utils/vite_helper.py."""+import hashlib+import ioimport json-from unittest.mock import Mock, patch, mock_open+import os+import threading+from pathlib import Path+from unittest.mock import Mock, patchimport pytest@@ -143,24 +148,27 @@ class TestViteHelperInitApp:class TestViteHelperLoadManifest:"""Tests for ViteHelper._load_manifest method."""- def test_load_manifest_reads_json_file(self):+ def test_load_manifest_reads_json_file(self, tmp_path):"""Test that manifest JSON is loaded from file."""from local_deep_research.web.utils.vite_helper import ViteHelperhelper = ViteHelper()helper.app = Mock()- helper.app.config = {"STATIC_DIR": "/app/static"}+ helper.app.config = {"STATIC_DIR": str(tmp_path)}manifest_data = {"js/app.js": {"file": "assets/app-abc123.js"}}- with patch("pathlib.Path.exists", return_value=True):- with patch(- "builtins.open", mock_open(read_data=json.dumps(manifest_data))- ):- helper._load_manifest()- assert helper.manifest == manifest_data+ manifest_path = tmp_path / "dist" / ".vite" / "manifest.json"+ manifest_path.parent.mkdir(parents=True)+ manifest_path.write_text(json.dumps(manifest_data), encoding="utf-8")+ asset_path = tmp_path / "dist" / "assets" / "app-abc123.js"+ asset_path.parent.mkdir()+ asset_path.write_text("// built", encoding="utf-8")- def test_load_manifest_uses_default_static_dir(self):+ helper._load_manifest()+ assert helper.manifest == manifest_data++ def test_load_manifest_uses_default_static_dir(self, monkeypatch, tmp_path):"""Test that default static directory is used when not configured."""from local_deep_research.web.utils.vite_helper import ViteHelper@@ -168,21 +176,20 @@ class TestViteHelperLoadManifest:helper.app = Mock()helper.app.config = {}- with patch("pathlib.Path.exists", return_value=False):- helper._load_manifest()- assert helper.manifest == {}+ monkeypatch.chdir(tmp_path)+ helper._load_manifest()+ assert helper.manifest == {}- def test_load_manifest_handles_missing_file(self):+ def test_load_manifest_handles_missing_file(self, tmp_path):"""Test that missing manifest file results in empty dict."""from local_deep_research.web.utils.vite_helper import ViteHelperhelper = ViteHelper()helper.app = Mock()- helper.app.config = {"STATIC_DIR": "/app/static"}+ helper.app.config = {"STATIC_DIR": str(tmp_path)}- with patch("pathlib.Path.exists", return_value=False):- helper._load_manifest()- assert helper.manifest == {}+ helper._load_manifest()+ assert helper.manifest == {}class TestViteHelperViteHmr:@@ -212,7 +219,16 @@ class TestViteHelperViteHmr:class TestViteHelperViteAsset:- """Tests for ViteHelper.vite_asset method."""+ """Tests for ViteHelper.vite_asset method.++ Every helper here is a bare ``ViteHelper()`` with ``_manifest_path``+ left at None and ``manifest`` assigned in memory, which is the+ *no-`dist_root`* path: `_refresh_manifest_if_stale()` returns without+ touching the filesystem and `_entry_problem()` checks the manifest's+ shape only. These are markup/branching tests; they are not coverage of+ the on-disk validation, which needs a real `dist/` tree and lives in+ `TestRequestedEntryConsistency`.+ """def test_vite_asset_returns_dev_server_url_in_dev_mode(self):"""Test that dev server URL is returned in development mode."""@@ -294,20 +310,20 @@ class TestViteHelperViteAsset:@pytest.fixture(autouse=True)-def _reset_missing_manifest_warned():+def _reset_warned_causes():"""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+ `_warned_causes` is intentionally module-level state (so each distinct+ cause is reported once per process, not once per request). That means itleaks across tests unless we reset it, both before and after, so teststhat check "warns" and tests that check "doesn't warn" don't depend onexecution order."""import local_deep_research.web.utils.vite_helper as vite_helper_module- vite_helper_module._missing_manifest_warned = False+ vite_helper_module._warned_causes.clear()yield- vite_helper_module._missing_manifest_warned = False+ vite_helper_module._warned_causes.clear()class TestViteHelperFallbackAssets:@@ -339,19 +355,31 @@ class TestViteHelperFallbackAssets:assert "style=" in result_strdef 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."""+ """A restart is the last resort, not the instruction.++ The helper re-reads the manifest on every production render, so a+ rebuild is picked up without restarting anything - and the banner+ must say so, because telling operators to bounce the server for a+ problem a reload already fixes is how a 30-second fix becomes an+ outage. It still names a restart, as the fallback for the case where+ the banner survives a successful build and reload, which is the same+ thing `docs/FRONTEND_BUILD_SYSTEM.md` says.++ Merely asserting that the word "restart" appears is satisfied by the+ wording this replaced ("run `npm run build`, then restart the+ server"), which said the opposite. The sentences that carry the+ meaning are pinned instead.+ """from local_deep_research.web.utils.vite_helper import ViteHelperhelper = ViteHelper()helper.is_dev = Falsehelper.manifest = {}- result_str = str(helper.missing_assets_banner())+ result_str = " ".join(str(helper.missing_assets_banner()).split())- assert "restart" in result_str.lower()+ assert "picked up" in result_str+ assert "without a restart" in result_str+ assert "restarting the server is the last resort" in result_strdef test_missing_assets_banner_empty_when_assets_built(self):"""A healthy production build renders no banner at all."""@@ -441,146 +469,1117 @@ class TestViteHelperFallbackAssets: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 _write_manifest(static_dir, manifest):+ manifest_path = static_dir / "dist" / ".vite" / "manifest.json"+ manifest_path.parent.mkdir(parents=True, exist_ok=True)+ manifest_path.write_text(json.dumps(manifest), encoding="utf-8")+ return manifest_path- 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")+def _write_asset(static_dir, relative_path):+ asset_path = static_dir / "dist" / relative_path+ asset_path.parent.mkdir(parents=True, exist_ok=True)+ asset_path.write_text("// built", encoding="utf-8")+ return asset_path- with patch.object(Path, "exists") as mock_exists:- helper._refresh_manifest_if_missing()- mock_exists.assert_not_called()+def _production_helper(static_dir):+ from local_deep_research.web.utils.vite_helper import ViteHelper- 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+ helper = ViteHelper()+ helper.is_dev = False+ helper.manifest = {}+ helper._manifest_path = static_dir / "dist" / ".vite" / "manifest.json"+ return helper+++def _count_reads_and_parses(monkeypatch):+ """Record every manifest `Path.open` and every `json.loads`."""+ import local_deep_research.web.utils.vite_helper as vite_helper_module++ real_open = Path.open+ real_loads = vite_helper_module.json.loads+ opens = []+ parses = []++ def counting_open(path, *args, **kwargs):+ opens.append(path)+ return real_open(path, *args, **kwargs)++ def counting_loads(*args, **kwargs):+ parses.append(args)+ return real_loads(*args, **kwargs)++ monkeypatch.setattr(Path, "open", counting_open)+ monkeypatch.setattr(vite_helper_module.json, "loads", counting_loads)+ return opens, parses+++def _swap_manifest_after_the_first_read(+ monkeypatch, manifest_path, replacement+):+ """Replace the manifest on disk the moment its first read returns.++ The reader gets the original bytes (served from memory, so the swap+ cannot retroactively change what it saw), and every later read sees the+ replacement - exactly the ordering a rebuild lands in during startup.+ """+ real_open = Path.open+ original = manifest_path.read_bytes()+ swapped = False++ def open_then_swap(path, *args, **kwargs):+ nonlocal swapped+ if path != manifest_path or swapped:+ return real_open(path, *args, **kwargs)+ swapped = True+ manifest_path.write_bytes(replacement)+ return io.BytesIO(original)++ monkeypatch.setattr(Path, "open", open_then_swap)+++def _assert_fallback_and_banner(helper, stale_url):+ assert helper.assets_are_missing() is True+ assert stale_url not in str(helper.vite_asset())+ assert "Vite build not found" in str(helper.vite_asset())+ assert "ldr-vite-missing-assets-banner" in str(+ helper.missing_assets_banner()+ )+++class TestViteHelperRefreshManifestIfStale:+ def test_unchanged_bytes_are_reread_but_not_reparsed(+ self, tmp_path, monkeypatch+ ):+ """Catches a revert that re-parses JSON on every healthy request.++ The steady-state cost is one bounded read plus a hash. Deleting the+ `fingerprint == self._manifest_fingerprint` short-circuit in+ `_adopt_manifest_from_disk` makes `json.loads` run per request and+ fails the `parses == []` assertion.+ """+ manifest = {"js/app.js": {"file": "js/app.OLDHASH.js"}}+ _write_manifest(tmp_path, manifest)+ _write_asset(tmp_path, "js/app.OLDHASH.js")+ helper = _production_helper(tmp_path)+ helper._refresh_manifest_if_stale()++ opens, parses = _count_reads_and_parses(monkeypatch)+ helper._refresh_manifest_if_stale()++ assert opens == [helper._manifest_path]+ assert parses == []++ def test_a_refused_manifest_is_parsed_once_not_once_per_request(+ self, tmp_path, monkeypatch+ ):+ """Catches removal of the rejected-fingerprint backoff.++ Adoption is a pure function of the manifest bytes, so re-parsing+ bytes already refused cannot change the verdict. Without the+ `fingerprint == self._rejected_fingerprint` short-circuit, a broken+ build re-parses on every `vite_asset()` *and* every banner call;+ with it, 50 renders cost one parse.+ """+ manifest_path = _write_manifest(+ tmp_path, {"js/app.js": {"file": "js/app.OLDHASH.js"}}+ )+ manifest_path.write_text("{broken", encoding="utf-8")+ helper = _production_helper(tmp_path)+ helper._refresh_manifest_if_stale()++ _opens, parses = _count_reads_and_parses(monkeypatch)+ for _ in range(50):+ helper.vite_asset()+ helper.missing_assets_banner()++ assert parses == []++ def test_the_backoff_still_adopts_a_later_valid_rebuild(self, tmp_path):+ """The backoff must not latch: new bytes are always parsed."""+ manifest_path = _write_manifest(+ tmp_path, {"js/app.js": {"file": "js/app.OLDHASH.js"}}+ )+ manifest_path.write_text("{broken", encoding="utf-8")+ helper = _production_helper(tmp_path)+ for _ in range(20):+ helper.vite_asset()++ _write_manifest(tmp_path, {"js/app.js": {"file": "js/app.NEW.js"}})+ _write_asset(tmp_path, "js/app.NEW.js")++ assert "js/app.NEW.js" in str(helper.vite_asset())++ def test_a_manifest_larger_than_the_read_cap_is_refused(self, tmp_path):+ """Catches a revert to an unbounded `read_bytes()`.++ A capped read means an oversized manifest is refused instead of+ materialised; the helper degrades rather than allocating whatever+ the file happens to contain.+ """+ from local_deep_research.web.utils.vite_helper import (+ _MAX_MANIFEST_BYTES,+ )++ manifest_path = _write_manifest(+ tmp_path, {"js/app.js": {"file": "js/app.OK.js"}}+ )+ _write_asset(tmp_path, "js/app.OK.js")+ padding = "A" * (_MAX_MANIFEST_BYTES + 1)+ manifest_path.write_text(+ json.dumps({"js/app.js": {"file": "js/app.OK.js", "pad": padding}}),+ encoding="utf-8",+ )+ helper = _production_helper(tmp_path)++ _assert_fallback_and_banner(helper, "js/app.OK.js")+ # The refusal has to remember *which* bytes it refused, like every+ # other refusal: without it the state is permanently "unknown", so+ # nothing downstream can tell a repeat of the same bad file from a+ # fresh one, and the backoff that the other refusal paths rely on+ # never engages.+ assert (+ helper._rejected_fingerprint+ == hashlib.sha256(+ manifest_path.read_bytes()[: _MAX_MANIFEST_BYTES + 1]+ ).hexdigest()+ )+ # Deleting the size check does not make this file *servable*: the+ # capped read hands `json.loads` a truncated document, which is+ # refused as malformed with the identical fingerprint. So the+ # markup, the banner and the fingerprint above are all satisfied by+ # a helper that has no size check at all. The recorded cause is the+ # only thing that distinguishes them.+ cause, _location = helper._manifest_failure+ assert "read cap" in cause, cause+ assert "not valid JSON" not in cause, cause++ def test_a_deeply_nested_manifest_degrades_instead_of_raising(+ self, tmp_path+ ):+ """Catches narrowing the parse guard back to `except ValueError`.++ `json.loads` raises RecursionError - not a ValueError - on deeply+ nested input, so an unguarded parse escapes into template rendering+ and turns every page into a 500 instead of a banner.+ """+ manifest_path = _write_manifest(+ tmp_path, {"js/app.js": {"file": "js/app.OK.js"}}+ )+ _write_asset(tmp_path, "js/app.OK.js")+ manifest_path.write_text(+ "[" * 200_000 + "]" * 200_000, encoding="utf-8"+ )+ helper = _production_helper(tmp_path)++ _assert_fallback_and_banner(helper, "js/app.OK.js")++ def test_no_filesystem_access_without_a_manifest_path(self):from local_deep_research.web.utils.vite_helper import ViteHelperhelper = ViteHelper()helper.is_dev = Falsehelper.manifest = {}- with patch.object(Path, "exists") as mock_exists:- helper._refresh_manifest_if_missing()+ with patch.object(Path, "open") as mock_open_path:+ helper._refresh_manifest_if_stale()- mock_exists.assert_not_called()+ mock_open_path.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+ def test_no_filesystem_access_in_dev_mode(self):from local_deep_research.web.utils.vite_helper import ViteHelperhelper = ViteHelper()helper.is_dev = True- helper.manifest = Nonehelper._manifest_path = Path("/fake/static/dist/.vite/manifest.json")- with patch.object(Path, "exists") as mock_exists:- helper._refresh_manifest_if_missing()+ with patch.object(Path, "open") as mock_open_path:+ helper._refresh_manifest_if_stale()- mock_exists.assert_not_called()+ mock_open_path.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+ def test_initial_missing_manifest_recovers_after_a_valid_rebuild(+ self, tmp_path+ ):+ helper = _production_helper(tmp_path)+ helper._refresh_manifest_if_stale()+ _assert_fallback_and_banner(helper, "OLDHASH")- helper = ViteHelper()- helper.is_dev = False- helper.manifest = {}- helper._manifest_path = Path("/fake/static/dist/.vite/manifest.json")+ manifest = {"js/app.js": {"file": "js/app.NEWHASH.js"}}+ _write_manifest(tmp_path, manifest)+ _write_asset(tmp_path, "js/app.NEWHASH.js")- 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 "js/app.NEWHASH.js" in str(helper.vite_asset())+ assert str(helper.missing_assets_banner()) == ""+ def test_vite_asset_reflects_a_valid_rebuild_on_the_next_request(+ self, tmp_path+ ):+ old_manifest = {"js/app.js": {"file": "js/app.OLDHASH.js"}}+ new_manifest = {"js/app.js": {"file": "js/app.NEWHASH.js"}}+ _write_manifest(tmp_path, old_manifest)+ _write_asset(tmp_path, "js/app.OLDHASH.js")+ helper = _production_helper(tmp_path)+ helper._refresh_manifest_if_stale()++ _write_manifest(tmp_path, new_manifest)+ _write_asset(tmp_path, "js/app.NEWHASH.js")++ assert helper.manifest == old_manifest+ assert "js/app.NEWHASH.js" in str(helper.vite_asset())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+ def test_consistent_manifest_without_app_entry_is_refreshed(self, tmp_path):+ old_manifest = {"js/other.js": {"file": "js/other.OLDHASH.js"}}+ new_manifest = {"js/app.js": {"file": "js/app.NEWHASH.js"}}+ _write_manifest(tmp_path, old_manifest)+ _write_asset(tmp_path, "js/other.OLDHASH.js")+ helper = _production_helper(tmp_path)+ helper._refresh_manifest_if_stale()+ assert helper.assets_are_missing() is True++ _write_manifest(tmp_path, new_manifest)+ _write_asset(tmp_path, "js/app.NEWHASH.js")++ assert "js/app.NEWHASH.js" in str(helper.vite_asset())+++class TestManifestAssetUrlEncoding:+ @pytest.mark.parametrize("field", ["file", "css"])+ @pytest.mark.parametrize(+ "filename",+ ["chunk?x.js", "chunk#x.js", "chunk%41.js", "chunk name.js", "文.js"],+ )+ def test_rendered_url_addresses_the_literal_filename(self, field, filename):+ """URL syntax must not change the filename validated on disk.++ This checks tag generation with an in-memory manifest: percent+ decoding the emitted path once must recover the exact filename,+ with no query or fragment and no duplicated encoding.+ """+ import re+ from urllib.parse import unquote, urlsplit+from local_deep_research.web.utils.vite_helper import ViteHelperhelper = ViteHelper()- helper.is_dev = False- helper.manifest = {}- helper._manifest_path = Path("/fake/static/dist/.vite/manifest.json")+ entry = (+ {"file": filename}+ if field == "file"+ else {"file": "app.js", "css": [filename]}+ )+ helper.manifest = {"js/app.js": entry}+ html = str(helper.vite_asset())+ attribute = "src" if field == "file" else "href"+ match = re.search(rf'{attribute}="([^"]+)"', html)+ assert match is not None, html+ url = urlsplit(match.group(1))+ assert url.query == ""+ assert url.fragment == ""+ assert unquote(url.path) == f"/static/dist/{filename}"+++class TestManifestSnapshotCoherence:+ def test_the_stored_fingerprint_describes_the_bytes_held_in_memory(+ self, tmp_path, monkeypatch+ ):+ """Catches any revert that fingerprints the file, not the bytes read.++ The startup read returns manifest A and the file becomes B before the+ fingerprint is taken. The invariant asserted here is the one that+ makes staleness detection work at all: `_manifest_fingerprint` is+ sha256(A) - the bytes actually in `self.manifest` - *not* sha256(B),+ the file's current content. Re-deriving the fingerprint from a second+ read or a stat (the shape this helper had before) stores B's key+ alongside A's data, and the next refresh sees "unchanged" and latches+ OLDHASH forever, which the follow-up assertions then catch.+ """+ from local_deep_research.web.utils.vite_helper import ViteHelper- 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")+ old_manifest = {"js/app.js": {"file": "js/app.OLDHASH.js"}}+ new_manifest = {"js/app.js": {"file": "js/app.NEWHASH.js"}}+ manifest_path = _write_manifest(tmp_path, old_manifest)+ _write_asset(tmp_path, "js/app.OLDHASH.js")+ _write_asset(tmp_path, "js/app.NEWHASH.js")+ original = json.dumps(old_manifest).encode("utf-8")+ replacement = json.dumps(new_manifest).encode("utf-8")+ assert manifest_path.read_bytes() == original+ _swap_manifest_after_the_first_read(+ monkeypatch, manifest_path, replacement+ )- assert "assets/app-def456.js" in str(result)+ helper = ViteHelper()+ helper.app = Mock(config={"STATIC_DIR": str(tmp_path)})+ helper._load_manifest()- 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+ # The replacement has already landed on disk, but startup adopted A.+ assert manifest_path.read_bytes() == replacement+ assert helper.manifest == old_manifest+ assert (+ helper._manifest_fingerprint == hashlib.sha256(original).hexdigest()+ )++ helper._refresh_manifest_if_stale()++ assert helper.manifest == new_manifest+ assert (+ helper._manifest_fingerprint+ == hashlib.sha256(replacement).hexdigest()+ )+ assert "js/app.NEWHASH.js" in str(helper.vite_asset())+++class TestConcurrentManifestReplacement:+ """A rebuild landing mid-render must not poison the next render."""++ def test_a_manifest_swapped_mid_validation_cannot_poison_the_memo(+ self, tmp_path, monkeypatch+ ):+ """Catches splitting the snapshot back into separate attributes.++ `vite_asset()` renders from a manifest, asks whether that manifest's+ entry is servable, and records the answer. While those three lived+ in separate attributes, a refresh landing between the render's+ snapshot and the verdict's memo key stored a *positive* verification+ of manifest A under manifest B's fingerprint - after which B was+ served with validation skipped, durably, until its bytes changed+ again. The interleaving is forced through a monkeypatched hook, not+ timing, so this is deterministic rather than a stress test.++ B is deliberately a manifest that *renders*: its entry is an object+ with a perfectly good `file` string, pointing at a chunk that is not+ on disk. A B whose entry merely lacked `file` would be caught by the+ render path's own `.get("file")` guard even with the memo poisoned,+ so it could not tell a coherent snapshot apart from a bad one. With+ this B, the only thing standing between the poisoned memo and a+ `<script>` tag naming a file that does not exist is verifying B for+ itself.+ """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")+ manifest_a = {"js/app.js": {"file": "js/app.AAA.js"}}+ manifest_b = {"js/app.js": {"file": "js/app.MISSING.js"}}+ _write_manifest(tmp_path, manifest_a)+ _write_asset(tmp_path, "js/app.AAA.js")+ # js/app.MISSING.js is deliberately never written.+ helper = _production_helper(tmp_path)++ real_entry_problem = ViteHelper._entry_problem+ swapped = threading.Event()++ def swap_then_validate(self, *args, **kwargs):+ # Runs in the render thread once `vite_asset()` has taken the+ # snapshot it will render from (A) and before that snapshot is+ # verified. A second thread publishes B here, and this returns+ # only once it has.+ if not swapped.is_set():+ swapped.set()++ def rewriter():+ _write_manifest(tmp_path, manifest_b)+ helper._refresh_manifest_if_stale()++ rewriter_thread = threading.Thread(+ target=rewriter, name="manifest-rewriter"+ )+ rewriter_thread.start()+ rewriter_thread.join()+ return real_entry_problem(self, *args, **kwargs)++ monkeypatch.setattr(ViteHelper, "_entry_problem", swap_then_validate)++ rendered = []+ render_thread = threading.Thread(+ target=lambda: rendered.append(str(helper.vite_asset("js/app.js"))),+ name="render",+ )+ render_thread.start()+ render_thread.join()++ # The render that verified A serves A: its tag names a file that the+ # manifest it rendered from actually defines.+ assert rendered, "the render thread raised before producing markup"+ assert "js/app.AAA.js" in rendered[0]+ assert helper.manifest == manifest_b++ # The next render sees B, and must verify B for itself. A memo+ # attributed to the wrong manifest serves B's dangling URL here,+ # with no banner and no warning.+ html = str(helper.vite_asset("js/app.js"))+ assert "Vite build not found" in html+ assert "js/app.MISSING.js" not in html+ assert "js/app.AAA.js" not in html+ assert "<script" not in html+ assert helper.assets_are_missing() is True++ def test_a_rewritten_manifest_is_reverified_not_served_from_the_old_memo(+ self, tmp_path+ ):+ """Catches hoisting `verified_entries` off the state onto `self`.++ The sequential half of the pair above: no threads, no forced+ interleaving, just a manifest rewritten between two renders. The+ memo lives on the state, so the new state starts with an empty one+ and the new manifest is walked for itself. Hoisted onto the helper+ it survives the state swap, `js/app.js` is still "verified", and the+ second render serves a chunk that was never flushed - the exact+ stale URL this PR exists to stop.+ """+ _write_manifest(tmp_path, {"js/app.js": {"file": "js/app.AAA.js"}})+ _write_asset(tmp_path, "js/app.AAA.js")+ helper = _production_helper(tmp_path)++ assert "js/app.AAA.js" in str(helper.vite_asset("js/app.js"))+ assert helper.assets_are_missing() is False++ # New bytes; js/app.BBB.js is deliberately never written.+ _write_manifest(tmp_path, {"js/app.js": {"file": "js/app.BBB.js"}})++ html = str(helper.vite_asset("js/app.js"))+ assert "Vite build not found" in html+ assert "js/app.BBB.js" not in html+ assert "<script" not in html+ assert helper.assets_are_missing() is True++ def test_an_asset_deleted_after_verification_is_noticed_in_the_window(+ self, tmp_path, monkeypatch+ ):+ """Catches a memo that outlives the files it verified.++ Nothing rewrites `manifest.json` when a chunk is deleted from+ `dist/`, so the bytes-changed invalidation never fires and a+ verification recorded once would otherwise stand for the life of the+ process: `assets_are_missing()` keeps saying False and the page+ keeps carrying a `<script>` tag for a file that is gone. Each+ positive result is therefore stamped and re-checked once it is older+ than `_VERIFICATION_TTL_SECONDS`.++ The clock is faked rather than slept on, and the window is pinned at+ both ends: a midpoint, a point just under the TTL, and the TTL+ boundary itself. The comparison in `_entry_problem()` is a strict+ `<` (delta against `_VERIFICATION_TTL_SECONDS`), so a memo taken at+ t=0 must still answer at a delta just under the TTL and must be+ re-checked at a delta exactly equal to it; a `<` -> `<=` regression+ would keep answering from the memo at the exact boundary too, and+ only the boundary step below would catch that.+ """+ import local_deep_research.web.utils.vite_helper as vite_helper_module- 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+ clock = {"now": 1000.0}+ monkeypatch.setattr(+ vite_helper_module, "_monotonic", lambda: clock["now"]+ )- assert helper.manifest == {}+ _write_manifest(tmp_path, {"js/app.js": {"file": "js/app.OK.js"}})+ asset = _write_asset(tmp_path, "js/app.OK.js")+ helper = _production_helper(tmp_path)++ verified_at = clock["now"]+ assert "js/app.OK.js" in str(helper.vite_asset("js/app.js"))+ assert helper.assets_are_missing() is False++ # manifest.json is untouched: same bytes, same hash, same state.+ asset.unlink()++ ttl = vite_helper_module._VERIFICATION_TTL_SECONDS++ clock["now"] = verified_at + ttl / 2+ assert helper.assets_are_missing() is False++ # Just under the TTL: still memoised, deletion not yet surfaced.+ clock["now"] = verified_at + ttl - 0.001+ assert helper.assets_are_missing() is False++ # Exactly at the TTL: the strict `<` must treat the memo as expired.+ clock["now"] = verified_at + ttl+ _assert_fallback_and_banner(helper, "js/app.OK.js")- 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+ def test_a_verified_entry_without_a_file_string_still_falls_back(+ self, monkeypatch+ ):+ """Catches reverting `file_info.get("file")` to `file_info["file"]`.++ Validation and rendering are two separate reads of the same dict, so+ the render path may not treat the verdict as a guarantee about what+ it is about to subscript. With a bare subscript an entry that has no+ 'file' key raises KeyError out of Jinja - a 500 on every page,+ instead of the degraded page the banner exists for.+ """from local_deep_research.web.utils.vite_helper import ViteHelperhelper = 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()+ helper.manifest = {"js/app.js": {"css": ["css/app.css"]}}+ monkeypatch.setattr(+ ViteHelper, "_entry_problem", lambda *args, **kwargs: None+ )++ html = str(helper.vite_asset("js/app.js"))++ assert "Vite build not found" in html+ assert "<script" not in html+ assert "<link" not in html+++class TestContentChangeDetection:+ def test_equal_size_same_mtime_rewrite_is_adopted(self, tmp_path):+ old_manifest = {"js/app.js": {"file": "js/app.OLDHASH.js"}}+ new_manifest = {"js/app.js": {"file": "js/app.NEWHASH.js"}}+ old_bytes = json.dumps(old_manifest).encode("utf-8")+ new_bytes = json.dumps(new_manifest).encode("utf-8")+ assert len(old_bytes) == len(new_bytes)++ manifest_path = _write_manifest(tmp_path, old_manifest)+ _write_asset(tmp_path, "js/app.OLDHASH.js")+ helper = _production_helper(tmp_path)+ helper._refresh_manifest_if_stale()+ original_stat = manifest_path.stat()++ _write_asset(tmp_path, "js/app.NEWHASH.js")+ manifest_path.write_bytes(new_bytes)+ os.utime(+ manifest_path,+ ns=(original_stat.st_atime_ns, original_stat.st_mtime_ns),+ )+ rewritten_stat = manifest_path.stat()+ assert (+ rewritten_stat.st_mtime_ns,+ rewritten_stat.st_size,+ ) == (original_stat.st_mtime_ns, original_stat.st_size)++ helper._refresh_manifest_if_stale()assert helper.manifest == new_manifest+ assert "js/app.NEWHASH.js" in str(helper.vite_asset())+++class TestFailClosedOnUnusableManifest:+ def test_deleted_manifest_drops_old_urls_and_recovers(self, tmp_path):+ old_manifest = {"js/app.js": {"file": "js/app.OLDHASH.js"}}+ new_manifest = {"js/app.js": {"file": "js/app.NEWHASH.js"}}+ manifest_path = _write_manifest(tmp_path, old_manifest)+ old_asset = _write_asset(tmp_path, "js/app.OLDHASH.js")+ helper = _production_helper(tmp_path)+ helper._refresh_manifest_if_stale()++ manifest_path.unlink()+ old_asset.unlink()+ _assert_fallback_and_banner(helper, "OLDHASH")++ _write_manifest(tmp_path, new_manifest)+ _write_asset(tmp_path, "js/app.NEWHASH.js")+ assert "js/app.NEWHASH.js" in str(helper.vite_asset())++ def test_malformed_manifest_drops_old_urls_and_recovers(self, tmp_path):+ old_manifest = {"js/app.js": {"file": "js/app.OLDHASH.js"}}+ new_manifest = {"js/app.js": {"file": "js/app.NEWHASH.js"}}+ manifest_path = _write_manifest(tmp_path, old_manifest)+ _write_asset(tmp_path, "js/app.OLDHASH.js")+ helper = _production_helper(tmp_path)+ helper._refresh_manifest_if_stale()+ old_fingerprint = helper._manifest_fingerprint++ manifest_path.write_text("{broken", encoding="utf-8")+ _assert_fallback_and_banner(helper, "OLDHASH")+ # The adopted fingerprint is dropped with the manifest it described;+ # the refused bytes are remembered separately, which is what stops+ # the degraded path re-parsing them on every request.+ assert helper._manifest_fingerprint is None+ assert helper._rejected_fingerprint not in (None, old_fingerprint)++ _write_manifest(tmp_path, new_manifest)+ _write_asset(tmp_path, "js/app.NEWHASH.js")+ assert "js/app.NEWHASH.js" in str(helper.vite_asset())++ def test_incomplete_manifest_drops_old_urls_and_recovers(self, tmp_path):+ old_manifest = {"js/app.js": {"file": "js/app.OLDHASH.js"}}+ incomplete_manifest = {+ "js/app.js": {+ "file": "js/app.NEWHASH.js",+ "css": ["css/app.NEWHASH.css"],+ }+ }+ _write_manifest(tmp_path, old_manifest)+ _write_asset(tmp_path, "js/app.OLDHASH.js")+ helper = _production_helper(tmp_path)+ helper._refresh_manifest_if_stale()++ _write_manifest(tmp_path, incomplete_manifest)+ _write_asset(tmp_path, "js/app.NEWHASH.js")+ _assert_fallback_and_banner(helper, "OLDHASH")++ _write_asset(tmp_path, "css/app.NEWHASH.css")+ assert "js/app.NEWHASH.js" in str(helper.vite_asset())+++class TestRequestedEntryConsistency:+ """Validation is scoped to the closure of the entry actually asked for."""++ def test_an_unrelated_entry_missing_from_disk_still_serves_app_js(+ self, tmp_path+ ):+ """Catches re-widening validation to every manifest entry.++ The real manifest carries 67 top-level entries, 65 of them fonts+ that no template ever passes to `vite_asset()`. Validating all of+ them all-or-nothing turns one missing font - a single 404 on `main`+ - into an empty manifest, a blank page and a red banner. Only the+ requested entry's own closure may gate it.+ """+ manifest = {+ "js/app.js": {+ "file": "js/app.OKHASH.js",+ "css": ["css/app.OKHASH.css"],+ "imports": ["_vendor.js"],+ },+ "_vendor.js": {"file": "js/vendor.OKHASH.js"},+ "fonts/fa-solid-900.ttf": {+ "file": "fonts/fa-solid-900.MISSING.ttf"+ },+ }+ _write_manifest(tmp_path, manifest)+ _write_asset(tmp_path, "js/app.OKHASH.js")+ _write_asset(tmp_path, "css/app.OKHASH.css")+ _write_asset(tmp_path, "js/vendor.OKHASH.js")+ helper = _production_helper(tmp_path)++ html = str(helper.vite_asset("js/app.js"))+ assert "js/app.OKHASH.js" in html+ assert "css/app.OKHASH.css" in html+ assert str(helper.missing_assets_banner()) == ""+ assert helper.assets_are_missing() is False++ def test_the_unrelated_entry_is_still_refused_when_it_is_requested(+ self, tmp_path+ ):+ """Scoping must not become "never check": asking for it still fails."""+ manifest = {+ "js/app.js": {"file": "js/app.OKHASH.js"},+ "fonts/fa-solid-900.ttf": {+ "file": "fonts/fa-solid-900.MISSING.ttf"+ },+ }+ _write_manifest(tmp_path, manifest)+ _write_asset(tmp_path, "js/app.OKHASH.js")+ helper = _production_helper(tmp_path)++ html = str(helper.vite_asset("fonts/fa-solid-900.ttf"))+ assert "Vite build not found" in html+ assert "<script" not in html+ assert "<link" not in html++ def test_primary_file_missing_degrades_until_the_chunk_is_flushed(+ self, tmp_path+ ):+ """Catches removing the existence check on the entry's own `file`.++ Vite writes manifest.json before every hashed chunk is flushed, so an+ entry pointing at a file that is not there yet must degrade - and+ must recover on the very next call once it lands, which only works+ because negative results are not cached.+ """+ manifest = {"js/app.js": {"file": "js/app.NEWHASH.js"}}+ _write_manifest(tmp_path, manifest)+ helper = _production_helper(tmp_path)++ _assert_fallback_and_banner(helper, "NEWHASH")++ _write_asset(tmp_path, "js/app.NEWHASH.js")+ assert "js/app.NEWHASH.js" in str(helper.vite_asset())++ def test_missing_css_makes_the_requested_entry_unservable(self, tmp_path):+ """Catches dropping `css` from the per-entry closure walk.++ Without it the entry is served with a <link> to a stylesheet that+ 404s - a styled-looking tag pointing at nothing.+ """+ manifest = {+ "js/app.js": {+ "file": "js/app.OKHASH.js",+ "css": ["css/app.MISSING.css"],+ }+ }+ _write_manifest(tmp_path, manifest)+ _write_asset(tmp_path, "js/app.OKHASH.js")+ helper = _production_helper(tmp_path)++ _assert_fallback_and_banner(helper, "app.OKHASH.js")++ def test_dangling_import_reference_is_rejected(self, tmp_path):+ manifest = {+ "js/app.js": {+ "file": "js/app.OKHASH.js",+ "imports": ["js/missing.js"],+ }+ }+ _write_manifest(tmp_path, manifest)+ _write_asset(tmp_path, "js/app.OKHASH.js")+ helper = _production_helper(tmp_path)++ _assert_fallback_and_banner(helper, "app.OKHASH.js")++ def test_an_unflushed_static_import_is_rejected(self, tmp_path):+ """A chunk the entry needs up front still gates the whole entry."""+ manifest = {+ "js/app.js": {+ "file": "js/app.OKHASH.js",+ "imports": ["js/vendor.js"],+ },+ "js/vendor.js": {"file": "js/vendor.MISSING.js"},+ }+ _write_manifest(tmp_path, manifest)+ _write_asset(tmp_path, "js/app.OKHASH.js")+ helper = _production_helper(tmp_path)++ _assert_fallback_and_banner(helper, "app.OKHASH.js")++ def test_an_unflushed_lazy_chunk_warns_but_still_serves_the_page(+ self, tmp_path+ ):+ """Catches putting `dynamicImports` back in the blocking closure.++ The shipped `js/app.js` entry lazily imports a canvg chunk that only+ the diagram-export path ever pulls in. Gating the entry on it means+ one unflushed lazy chunk renders the login form as a red banner -+ the app is unreachable over a feature nobody on that page uses. The+ chunk is still validated, and the operator is still told once; the+ blast radius is the one feature, not the whole UI.+ """+ manifest = {+ "js/app.js": {+ "file": "js/app.OKHASH.js",+ "dynamicImports": ["js/lazy.js"],+ },+ "js/lazy.js": {"file": "js/lazy.MISSING.js"},+ }+ _write_manifest(tmp_path, manifest)+ _write_asset(tmp_path, "js/app.OKHASH.js")+ helper = _production_helper(tmp_path)++ with patch(+ "local_deep_research.web.utils.vite_helper.logger"+ ) as mock_logger:+ html = str(helper.vite_asset("js/app.js"))++ assert "js/app.OKHASH.js" in html+ assert "Vite build not found" not in html+ assert str(helper.missing_assets_banner()) == ""+ assert helper.assets_are_missing() is False+ mock_logger.warning.assert_called_once()+ (message,), _ = mock_logger.warning.call_args+ assert "js/lazy.MISSING.js" in message+ assert "on demand" in message++ def test_a_dangling_lazy_reference_warns_but_still_serves_the_page(+ self, tmp_path+ ):+ """A `dynamicImports` name the manifest never defines is advisory too."""+ manifest = {+ "js/app.js": {+ "file": "js/app.OKHASH.js",+ "dynamicImports": ["js/nowhere.js"],+ }+ }+ _write_manifest(tmp_path, manifest)+ _write_asset(tmp_path, "js/app.OKHASH.js")+ helper = _production_helper(tmp_path)++ with patch(+ "local_deep_research.web.utils.vite_helper.logger"+ ) as mock_logger:+ html = str(helper.vite_asset("js/app.js"))++ assert "js/app.OKHASH.js" in html+ mock_logger.warning.assert_called_once()+ (message,), _ = mock_logger.warning.call_args+ assert "js/nowhere.js" in message++ def test_cyclic_imports_are_validated_once_and_served(self, tmp_path):+ """Catches dropping the `visited` set: a cycle would hang forever.++ "Hang forever" is why the walk runs on a worker thread with a+ bounded `join()`: without `visited` this test would not fail, it+ would never return, and a hung worker takes the whole suite with it+ instead of reporting one red test. The thread is a daemon so the+ interpreter can still exit if the assertion below trips.+ """+ manifest = {+ "js/app.js": {+ "file": "js/app.OKHASH.js",+ "imports": ["js/vendor.js"],+ },+ "js/vendor.js": {+ "file": "js/vendor.OKHASH.js",+ "dynamicImports": ["js/app.js"],+ },+ }+ _write_manifest(tmp_path, manifest)+ _write_asset(tmp_path, "js/app.OKHASH.js")+ _write_asset(tmp_path, "js/vendor.OKHASH.js")+ helper = _production_helper(tmp_path)++ helper._refresh_manifest_if_stale()+ assert helper.manifest == manifest++ verdicts = []+ walker = threading.Thread(+ target=lambda: verdicts.append(helper.assets_are_missing()),+ name="closure-walk",+ daemon=True,+ )+ walker.start()+ walker.join(timeout=30)++ assert not walker.is_alive(), (+ "the closure walk did not terminate on a cycle"+ )+ assert verdicts == [False]++ def test_path_outside_dist_is_rejected(self, tmp_path):+ """Catches dropping the `is_relative_to(dist_root)` containment check.++ `..`-escaping and symlinked targets must not become servable URLs+ just because the file happens to exist.+ """+ manifest = {"js/app.js": {"file": "../escaped.js"}}+ _write_manifest(tmp_path, manifest)+ escaped = tmp_path / "escaped.js"+ escaped.write_text("// outside dist", encoding="utf-8")+ helper = _production_helper(tmp_path)++ _assert_fallback_and_banner(helper, "escaped.js")++ def test_an_absolute_path_into_dist_is_rejected(self, tmp_path):+ """Catches accepting an absolute manifest path that lands in dist/.++ `dist_root / "/srv/app/static/dist/js/app.js"` is the absolute path+ itself (pathlib lets the absolute operand win), so containment and+ `is_file()` both pass - and the value is then pasted into+ `src="/static/dist/<path>"`, publishing the server's filesystem+ layout to every visitor on a URL that 404s anyway.+ """+ served = tmp_path / "dist" / "js" / "app.OKHASH.js"+ served.parent.mkdir(parents=True, exist_ok=True)+ served.write_text("// built", encoding="utf-8")+ _write_manifest(tmp_path, {"js/app.js": {"file": str(served)}})+ helper = _production_helper(tmp_path)++ html = str(helper.vite_asset("js/app.js"))+ assert "Vite build not found" in html+ assert str(tmp_path) not in html+ assert "<script" not in html++ @pytest.mark.parametrize(+ "manifest_file_value",+ [+ "js/app.OKHASH.js/", # trailing separator+ "js//app.OKHASH.js", # empty segment+ "js/app.OKHASH.js/.", # '.' segment+ "./js/app.OKHASH.js", # leading '.' segment+ "js/../js/app.OKHASH.js", # '..' segment that stays inside+ ],+ )+ def test_an_unnormalised_path_is_rejected(+ self, tmp_path, manifest_file_value+ ):+ """Catches accepting paths pathlib normalises but a URL does not.++ Every value here resolves to the same real file inside `dist/`, so+ containment and `is_file()` both pass - and then the raw string is+ pasted into `src="/static/dist/<path>"`, where it is not the URL of+ the file that was just verified. `js/app.OKHASH.js/` renders a+ trailing slash, `js//app.OKHASH.js` renders a doubled separator, and+ the dot segments render paths a static handler is under no+ obligation to fold. All 404 while the check says "verified".+ """+ _write_manifest(tmp_path, {"js/app.js": {"file": manifest_file_value}})+ _write_asset(tmp_path, "js/app.OKHASH.js")+ helper = _production_helper(tmp_path)++ _assert_fallback_and_banner(helper, "app.OKHASH.js")++ def test_the_normalised_form_of_that_path_is_still_served(self, tmp_path):+ """The rejection above must be about the shape, not the file.++ Without this row, rejecting every path unconditionally passes the+ parametrised test.+ """+ _write_manifest(tmp_path, {"js/app.js": {"file": "js/app.OKHASH.js"}})+ _write_asset(tmp_path, "js/app.OKHASH.js")+ helper = _production_helper(tmp_path)++ assert "js/app.OKHASH.js" in str(helper.vite_asset("js/app.js"))+ assert helper.assets_are_missing() is False+++class TestRefusedManifestIsReported:+ """A manifest that exists but is refused must not be silent or misdescribed."""++ def test_a_refused_manifest_warns_and_names_the_file(self, tmp_path):+ """Catches a silent `_fail_closed()`.++ Deleting the warning from `_fail_closed` (or gating the startup+ warning on `manifest_path.exists()` again) leaves a present-but-+ unusable manifest logging nothing at all, and the render-time+ fallback then blames a file that is sitting right there.+ """+ manifest_path = _write_manifest(+ tmp_path, {"js/app.js": {"file": "js/app.OK.js"}}+ )+ manifest_path.write_text("{broken", encoding="utf-8")+ helper = _production_helper(tmp_path)++ with patch(+ "local_deep_research.web.utils.vite_helper.logger"+ ) as mock_logger:+ markup = str(helper.vite_asset("js/app.js"))++ mock_logger.warning.assert_called_once()+ (message,), _ = mock_logger.warning.call_args+ assert str(manifest_path) in message+ assert "not valid JSON" in message+ assert "manifest not found" not in message+ # The rendered comment says the manifest was refused rather than+ # blaming a file that is sitting right there - and, unlike the log,+ # it carries neither the server's filesystem layout nor any+ # manifest-controlled text into every visitor's HTML.+ assert "read and refused" in markup+ assert str(manifest_path) not in markup+ assert str(tmp_path) not in markup++ def test_a_repeated_failure_warns_once_per_distinct_cause(self, tmp_path):+ """Catches a revert to the single-boolean "already warned" flag.++ With one process-wide boolean the first transient burns the only+ warning and every later, different failure is silent forever.+ Arrays and empty objects share one rejection cause, so changing+ between them must not warn again; removing the file is a distinct+ cause and must produce another warning.+ """+ manifest_path = _write_manifest(+ tmp_path, {"js/app.js": {"file": "js/app.OK.js"}}+ )+ manifest_path.write_text("{broken", encoding="utf-8")+ helper = _production_helper(tmp_path)++ with patch(+ "local_deep_research.web.utils.vite_helper.logger"+ ) as mock_logger:+ for _ in range(5):+ helper.vite_asset("js/app.js")+ assert mock_logger.warning.call_count == 1++ manifest_path.write_text("[1, 2, 3]", encoding="utf-8")+ helper.vite_asset("js/app.js")+ assert mock_logger.warning.call_count == 2++ manifest_path.write_text("{}", encoding="utf-8")+ helper.vite_asset("js/app.js")+ assert mock_logger.warning.call_count == 2++ manifest_path.unlink()+ helper.vite_asset("js/app.js")++ assert mock_logger.warning.call_count == 3+ messages = [call.args[0] for call in mock_logger.warning.call_args_list]+ assert "not valid JSON" in messages[0]+ assert "not a non-empty JSON object" in messages[1]+ assert "no readable manifest file" in messages[2]++ def test_an_unservable_entry_names_the_file_that_is_missing(self, tmp_path):+ """Catches dropping the reason from the entry-level warning."""+ _write_manifest(tmp_path, {"js/app.js": {"file": "js/app.GONE.js"}})+ helper = _production_helper(tmp_path)++ with patch(+ "local_deep_research.web.utils.vite_helper.logger"+ ) as mock_logger:+ helper.vite_asset("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 "js/app.GONE.js" in message+++class TestManifestDerivedTextInTheLog:+ """What a manifest says must not decide how much of the log it owns."""++ def test_churning_manifest_bytes_warn_once_not_once_per_render(+ self, tmp_path+ ):+ """Catches putting the fingerprint back in the warning's cause key.++ A manifest being rewritten with fresh garbage yields new bytes on+ every render and the *same* operator problem. Keying "warn once" on+ the bytes turns one warning into one per render, which buries every+ other line in the log; the fingerprint belongs in the message, where+ it identifies the snapshot without multiplying the records.+ """+ manifest_path = tmp_path / "dist" / ".vite" / "manifest.json"+ manifest_path.parent.mkdir(parents=True, exist_ok=True)+ helper = _production_helper(tmp_path)++ with patch(+ "local_deep_research.web.utils.vite_helper.logger"+ ) as mock_logger:+ for index in range(300):+ manifest_path.write_text(+ "{broken " + "x" * index, encoding="utf-8"+ )+ helper.vite_asset("js/app.js")++ mock_logger.warning.assert_called_once()+ (message,), _ = mock_logger.warning.call_args+ assert "not valid JSON" in message+ assert "sha256" in message++ def test_a_manifest_key_cannot_forge_a_second_log_line(self, tmp_path):+ """Catches interpolating manifest-supplied text into a log record raw.++ manifest.json is not written by this process. A key containing a+ newline splices a second, fabricated record into the log that no+ aggregator can tell apart from a real one - so the text is escaped,+ not dropped: the operator still sees what the manifest actually+ said.+ """+ forged = "js/app.js\nERROR | totally-real-log-line"+ _write_manifest(+ tmp_path,+ {+ "js/app.js": {+ "file": "js/app.OKHASH.js",+ "imports": [forged],+ },+ forged: {},+ },+ )+ _write_asset(tmp_path, "js/app.OKHASH.js")+ helper = _production_helper(tmp_path)++ with patch(+ "local_deep_research.web.utils.vite_helper.logger"+ ) as mock_logger:+ helper.vite_asset("js/app.js")++ mock_logger.warning.assert_called_once()+ (message,), _ = mock_logger.warning.call_args+ assert "\n" not in message+ assert "\r" not in message+ assert "totally-real-log-line" in messageclass TestViteAssetWarningIntegration:- """End-to-end coverage of vite_asset()'s warning/banner behavior."""+ """End-to-end coverage of vite_asset()'s warning/banner behavior.++ "End-to-end" here means template-global to markup, not manifest file to+ markup: like `TestViteHelperViteAsset` these helpers have no+ ``_manifest_path``, so they exercise only the no-`dist_root` path and no+ file is ever read or checked. The disk-backed equivalents are in+ `TestRefusedManifestIsReported` and `TestRequestedEntryConsistency`.+ """def test_manifest_present_no_banner_no_warning(self):"""Normal production path: no banner, no warning."""