Skip to content

The agent that grows with you

fix(webapp): report the Webapp unavailable when hermes update could not rebuild it

emozilla04318229b26b
diff --git a/gateway/webapp_listener.py b/gateway/webapp_listener.py
index 780e1d88f31..f9c288c54ea 100644
--- a/gateway/webapp_listener.py
+++ b/gateway/webapp_listener.py
@@ -252,13 +252,23 @@ def _one_use_links_work() -> bool:
#: How every missing-bundle reason starts; ``hermes webapp --status`` asks for no restart after it.
NOT_BUILT = "The Webapp is not built"
+#: Why a bundle ``hermes update`` could not rebuild is not served (``hermes_cli.webapp.mark_webapp_stale``).
+NOT_REBUILT = (f"{NOT_BUILT} for this version of Hermes: hermes update could not rebuild it. "
+ "Run hermes webapp to rebuild it.")
+
+
+def bundle_stale_reason(dist) -> str | None:
+ """:data:`NOT_REBUILT` while the bundle in *dist* is marked out of date, else None."""
+ from hermes_cli.webapp import webapp_bundle_stale
+ return NOT_REBUILT if webapp_bundle_stale(dist) else None
def bundle_missing_reason(dist) -> str | None:
- """Why the Webapp cannot be served from *dist*, or None once its bundle is built. The listener
- serves a bundle the moment it appears, so building it needs no gateway restart."""
+ """Why the Webapp cannot be served from *dist* (no bundle, or one ``hermes update`` could not
+ rebuild), or None once it is built. The listener serves a bundle the moment it appears or is
+ rebuilt, so building it needs no gateway restart."""
if (Path(dist) / "index.html").is_file():
- return None
+ return bundle_stale_reason(dist)
return f"{NOT_BUILT} ({Path(dist) / 'index.html'} is missing). Run hermes webapp to build it."
diff --git a/hermes_cli/source_build.py b/hermes_cli/source_build.py
index a884aadc518..68fc5fd9182 100644
--- a/hermes_cli/source_build.py
+++ b/hermes_cli/source_build.py
@@ -252,15 +252,24 @@ def _rebuild_served_webapp(project_root: Path, publish_stage) -> None:
"""The Webapp bundle (``apps/desktop/dist-webapp``), when a home sharing this install serves it
(``webapp.enabled``): its gateway serves the bundle as built, so one older than the updated
backend would talk to it with an outdated contract. Built with the function ``hermes webapp``
- uses, which reuses a current bundle."""
+ uses, which reuses a current bundle. A failed build leaves the previous bundle on disk, marked
+ out of date: its gateways report the Webapp unavailable until ``hermes webapp`` rebuilds it."""
from gateway.webapp_listener import webapp_settings
- from hermes_cli.webapp import prepare_webapp_renderer
+ from hermes_cli.webapp import mark_webapp_stale, prepare_webapp_renderer
from pm.plugins_state import dependency_homes
if not any(webapp_settings(home).enabled for home in dependency_homes()):
return
publish_stage("Building the Webapp")
- prepare_webapp_renderer(project_root, explicit=True)
+ try:
+ prepare_webapp_renderer(project_root, explicit=True)
+ except BaseException:
+ try:
+ if mark_webapp_stale(project_root):
+ print(" ⓘ The Webapp stays unavailable until `hermes webapp` rebuilds it.")
+ except OSError as exc:
+ print(f" ⚠ Could not mark the Webapp out of date: {exc}")
+ raise
def _build_desktop_product(project_root: Path, env: dict, publish_stage) -> None:
diff --git a/hermes_cli/web_server_dashboard.py b/hermes_cli/web_server_dashboard.py
index 0d35c6b20ed..eaec75be31f 100644
--- a/hermes_cli/web_server_dashboard.py
+++ b/hermes_cli/web_server_dashboard.py
@@ -176,6 +176,13 @@ def mount_spa(application: FastAPI):
missing = ("The Webapp is not built. Run: hermes webapp" if webapp
else "Frontend not built. Run: cd web && npm run build")
return JSONResponse({"error": missing}, status_code=404)
+ if getattr(application.state, "ui_surface", "dashboard") == "webapp":
+ # A bundle `hermes update` could not rebuild was built for the code before the update:
+ # refuse it until `hermes webapp` rebuilds it.
+ from gateway.webapp_listener import bundle_stale_reason
+ stale = bundle_stale_reason(web_dist())
+ if stale:
+ return JSONResponse({"error": stale}, status_code=503, headers=_NO_STORE)
chat_js = "true" if _DASHBOARD_EMBEDDED_CHAT_ENABLED else "false"
gated = bool(getattr(application.state, "auth_required", False))
surface = getattr(application.state, "ui_surface", "dashboard")
diff --git a/hermes_cli/webapp.py b/hermes_cli/webapp.py
index 9166c07c665..9318b701714 100644
--- a/hermes_cli/webapp.py
+++ b/hermes_cli/webapp.py
@@ -16,6 +16,11 @@ import subprocess
# Serialize renderer publication with Dashboard builds in this checkout.
_LOCK_NAME = ".web_ui_build.lock"
_LOCK_WAIT_SECONDS = 30 * 60
+# Written into the bundle when `hermes update` could not rebuild it, so the gateways serving it report
+# the Webapp unavailable instead of serving it against the updated backend. Publishing a build
+# replaces the whole folder, and the receipt's output hash covers this file, so a marked bundle is
+# never reused as current.
+STALE_MARKER = ".hermes-stale"
class WebappBuildError(RuntimeError):
@@ -26,6 +31,28 @@ def webapp_dist_dir(project_root: Path) -> Path:
return project_root / "apps" / "desktop" / "dist-webapp"
+def mark_webapp_stale(project_root: Path) -> bool:
+ """Mark the built bundle in *project_root* out of date, after a rebuild that failed. False when
+ no bundle is built: nothing serves one, and the build output folder stays the builder's."""
+ dist = webapp_dist_dir(project_root)
+ if not (dist / "index.html").is_file():
+ return False
+ (dist / STALE_MARKER).write_text("hermes update could not rebuild this bundle\n", encoding="utf-8")
+ return True
+
+
+def webapp_bundle_stale(dist: Path) -> bool:
+ """Whether the bundle in *dist* is marked out of date (:func:`mark_webapp_stale`)."""
+ return (Path(dist) / STALE_MARKER).is_file()
+
+
+def _clear_stale_mark(dist: Path) -> None:
+ try:
+ (dist / STALE_MARKER).unlink(missing_ok=True)
+ except OSError as exc:
+ raise WebappBuildError(f"Could not mark the Webapp renderer at {dist} current: {exc}") from exc
+
+
@contextmanager
def _exclusive_build_lock(path: Path):
"""Cross-platform exclusive lock for one renderer generation."""
@@ -78,11 +105,13 @@ def prepare_webapp_renderer(
return dist
with _exclusive_build_lock(project_root / _LOCK_NAME):
if not force and source_product_current(project_root, "webapp", dist):
+ _clear_stale_mark(dist)
print(f"✓ Hermes Webapp renderer is up to date: {dist}")
return dist
try:
build_source_webapp(project_root, env=source_build_env(explicit=explicit), explicit=explicit)
except (OSError, subprocess.SubprocessError, RuntimeError) as exc:
raise WebappBuildError(f"Browser-hosted Desktop build failed: {exc}") from exc
+ _clear_stale_mark(dist)
print(f"✓ Hermes Webapp renderer built: {dist}")
return dist
diff --git a/tests/gateway/fixtures/webapp_fallback_peer.py b/tests/gateway/fixtures/webapp_fallback_peer.py
index 451e8b49a0d..aeb9db09782 100644
--- a/tests/gateway/fixtures/webapp_fallback_peer.py
+++ b/tests/gateway/fixtures/webapp_fallback_peer.py
@@ -12,6 +12,8 @@ Run as ``python webapp_fallback_peer.py '<spec json>'`` with an isolated ``HERME
and starts listening while the gateway mounts the dashboard (Linux only);
- ``connect_during_mount``: a client connects to the Webapp's port while the dashboard mounts;
- ``built``: whether the Webapp bundle has its ``index.html``;
+- ``update_fails``: before the gateway starts, ``hermes update``'s Webapp step runs for this home and its
+ build fails; once the gateway serves, ``hermes webapp``'s build succeeds;
- ``probe_host``: a Host header to send (a public hostname), or null.
Writes ``receipt.json`` into ``HERMES_HOME`` (the gateway redirects stdout). No inference: the model points
@@ -87,6 +89,42 @@ def _fail_startup_once():
uvicorn.Server.startup = startup
+def _fail_webapp_update(home, checkout):
+ """``hermes update``'s Webapp step for an install whose only home is *home*, with a build that
+ fails as a broken npm install would."""
+ import hermes_cli.webapp
+ from hermes_cli import source_build
+ from pm import plugins_state
+
+ def fail(_project_root, **_options):
+ raise hermes_cli.webapp.WebappBuildError("Browser-hosted Desktop build failed: npm ci exited 1")
+
+ plugins_state.dependency_homes = lambda: [home]
+ real, hermes_cli.webapp.prepare_webapp_renderer = hermes_cli.webapp.prepare_webapp_renderer, fail
+ try:
+ source_build._rebuild_served_webapp(checkout, lambda _stage: None)
+ except hermes_cli.webapp.WebappBuildError:
+ pass
+ else:
+ raise AssertionError("the update's failing Webapp build did not fail")
+ finally:
+ hermes_cli.webapp.prepare_webapp_renderer = real
+
+
+def _rebuild_webapp(checkout, dist):
+ """``hermes webapp``'s build, with the compiler stood in by one that writes a new bundle."""
+ import hermes_cli.webapp
+ from hermes_cli import source_build
+
+ def compile_bundle(_root, *, env, explicit):
+ (dist / "index.html").write_text(INDEX.replace("WEBAPP_BUNDLE", "WEBAPP_BUNDLE rebuilt"), encoding="utf-8")
+
+ source_build.source_product_current = lambda *_args: False
+ source_build.source_build_env = lambda *, explicit=False: {}
+ source_build.build_source_webapp = compile_bundle
+ hermes_cli.webapp.prepare_webapp_renderer(checkout, explicit=True)
+
+
async def _native_session_list(runner, origin) -> bool:
from websockets.asyncio.client import connect
@@ -156,6 +194,9 @@ async def probe(spec):
if spec.get("built", True):
(dist / "index.html").write_text(INDEX, encoding="utf-8")
hermes_cli.webapp.webapp_dist_dir = lambda _root: dist # the bundle, without a build
+ checkout = home.parent / "checkout"
+ if spec.get("update_fails"):
+ _fail_webapp_update(home, checkout)
if spec.get("fail_after_mount"):
_fail_startup_once()
rival = None
@@ -232,6 +273,12 @@ async def probe(spec):
built = await client.get("/")
report["index_once_built"] = {"status": built.status_code,
"is_webapp": "WEBAPP_BUNDLE" in built.text}
+ elif spec.get("update_fails"):
+ _rebuild_webapp(checkout, dist)
+ report["status_once_built"] = ask("webapp-status")
+ built = await client.get("/")
+ report["index_once_built"] = {"status": built.status_code,
+ "is_webapp": "WEBAPP_BUNDLE rebuilt" in built.text}
report["token_rotated"] = (home / "webapp" / "session-token").read_text().strip() != SEEDED_TOKEN
finally:
await stop_gateway_api(api)
diff --git a/tests/gateway/test_webapp_bundle.py b/tests/gateway/test_webapp_bundle.py
index 46f35434124..02f974fa868 100644
--- a/tests/gateway/test_webapp_bundle.py
+++ b/tests/gateway/test_webapp_bundle.py
@@ -3,8 +3,9 @@
The gateway serves the Webapp from its built bundle (``apps/desktop/dist-webapp``). Until that bundle
has its ``index.html`` the gateway reports the Webapp unavailable, says to run ``hermes webapp`` (which
builds it), mints no launch link and answers ``/`` with that instruction rather than the dashboard's
-build command. The listener picks the bundle up as soon as it is built, without a restart. The live
-case runs a real gateway listener in a child process (``fixtures/webapp_fallback_peer.py``).
+build command. The listener picks the bundle up as soon as it is built, without a restart. A bundle
+``hermes update`` could not rebuild is reported the same way until ``hermes webapp`` rebuilds it. The
+live cases run a real gateway listener in a child process (``fixtures/webapp_fallback_peer.py``).
"""
import pytest
@@ -41,6 +42,32 @@ def test_the_webapp_is_served_once_built_without_a_restart(unbuilt):
assert unbuilt["index_once_built"] == {"status": 200, "is_webapp": True}
[email protected](scope="module")
+def update_failed(tmp_path_factory):
+ return run(tmp_path_factory.mktemp("update-failed"), {"webapp": {"enabled": True, "port": free_port()},
+ "update_fails": True})
+
+
+def test_a_bundle_hermes_update_could_not_rebuild_is_unavailable_and_says_how_to_rebuild_it(update_failed):
+ """``hermes update`` keeps the previous bundle when it cannot rebuild it, built for the code
+ before the update. The gateway then reports the Webapp unavailable with what to run (``hermes
+ webapp``, which rebuilds it) rather than serving that bundle as current: no launch link, and
+ ``/`` answers with the same instruction instead of the old page."""
+ assert update_failed["start_error"] is None, update_failed.get("start_traceback")
+ status = update_failed["status"]
+ assert (status["state"], status["url"]) == ("unavailable", None)
+ assert status["reason"].startswith(webapp_listener.NOT_BUILT) and "hermes webapp" in status["reason"]
+ assert "hermes webapp" in update_failed["launch"]["refused"]
+ assert update_failed["index"]["status"] == 503
+ assert "hermes webapp" in update_failed["index"]["body"]
+ assert "WEBAPP_BUNDLE" not in update_failed["index"]["body"]
+
+
+def test_hermes_webapp_rebuilds_a_bundle_the_update_left_and_it_is_served_without_a_restart(update_failed):
+ assert update_failed["status_once_built"]["state"] == "serving"
+ assert update_failed["index_once_built"] == {"status": 200, "is_webapp": True}
+
+
def test_the_launcher_reports_an_unbuilt_webapp_without_asking_for_a_restart(monkeypatch, tmp_path, capsys):
# Building it is enough: the running gateway serves the bundle once it exists.
reason = webapp_listener.bundle_missing_reason(tmp_path / "dist-webapp")
diff --git a/tests/hermes_cli/test_source_build.py b/tests/hermes_cli/test_source_build.py
index 191c893d3f9..9b395a3d888 100644
--- a/tests/hermes_cli/test_source_build.py
+++ b/tests/hermes_cli/test_source_build.py
@@ -451,3 +451,51 @@ def test_update_rebuilds_the_webapp_bundle_a_home_serves(tmp_path, monkeypatch,
build_update_products(root, desktop=False)
assert builds == ([(root, {"explicit": True})] if enabled else [])
+
+
[email protected]("built", [True, False])
+def test_a_failed_webapp_rebuild_in_update_marks_the_served_bundle_out_of_date(tmp_path, monkeypatch, capsys, built):
+ """When ``hermes update`` cannot rebuild the Webapp bundle a home serves, the previous bundle
+ stays on disk but is marked out of date: its gateway reports the Webapp unavailable and says to
+ run ``hermes webapp`` (which rebuilds it) instead of serving it against the updated backend. The
+ update still reports the failure. With no bundle built there is nothing to mark."""
+ import hermes_cli.left_core_migration as left_core
+ import hermes_cli.main_install_repair as install_repair
+ import hermes_cli.memory_provider_migration as memory_migration
+ from gateway.webapp_listener import NOT_BUILT, bundle_missing_reason
+ from hermes_cli import update_stage, webapp
+ from hermes_cli.source_build import ProductBuildError, build_update_products
+ from pm import plugins_state
+
+ root = tmp_path / "checkout"
+ (root / "apps/desktop/scripts").mkdir(parents=True)
+ (root / "apps/desktop/scripts/build-webapp.mjs").write_text("", encoding="utf-8")
+ dist = webapp.webapp_dist_dir(root)
+ dist.mkdir()
+ if built:
+ (dist / "index.html").write_text("<!doctype html>", encoding="utf-8")
+ home = tmp_path / "default"
+ home.mkdir()
+ (home / "config.yaml").write_text("webapp:\n enabled: true\n", encoding="utf-8")
+ monkeypatch.setattr(install_repair, "_install_configured_features_missing_deps", lambda _root: None)
+ monkeypatch.setattr(memory_migration, "migrate_all_homes", list)
+ monkeypatch.setattr(left_core, "migrate_all_homes", list)
+ monkeypatch.setattr(update_stage, "publish_stage", lambda _stage: None)
+ monkeypatch.setattr(plugins_state, "dependency_homes", lambda: [home])
+
+ def fail(_project_root, **_options):
+ raise webapp.WebappBuildError("Browser-hosted Desktop build failed: npm ci exited 1")
+
+ monkeypatch.setattr(webapp, "prepare_webapp_renderer", fail)
+ before = sorted(root.rglob("*"))
+
+ with pytest.raises(ProductBuildError, match="Webapp build"):
+ build_update_products(root, desktop=False)
+
+ reason = bundle_missing_reason(dist)
+ assert reason is not None and reason.startswith(NOT_BUILT) and "hermes webapp" in reason
+ if built:
+ assert (dist / "index.html").read_text(encoding="utf-8") == "<!doctype html>"
+ assert "hermes webapp" in capsys.readouterr().out
+ else:
+ assert sorted(root.rglob("*")) == before
diff --git a/tests/hermes_cli/test_webapp_renderer_build.py b/tests/hermes_cli/test_webapp_renderer_build.py
index 677efa00752..cf2f6e08246 100644
--- a/tests/hermes_cli/test_webapp_renderer_build.py
+++ b/tests/hermes_cli/test_webapp_renderer_build.py
@@ -127,6 +127,47 @@ def test_renderer_build_failures_are_reported_not_raised_raw(tmp_path: Path, mon
webapp.prepare_webapp_renderer(tmp_path)
+def test_a_build_or_a_current_bundle_clears_the_out_of_date_mark(tmp_path: Path, monkeypatch):
+ """``hermes update`` marks the bundle out of date when it cannot rebuild it, and the gateway
+ reports the Webapp unavailable while the mark is there. The next build that succeeds (``hermes
+ webapp``, Web Access Start or the next update), or that finds the bundle current, clears it.
+ Reusing the bundle with ``--skip-build`` writes nothing and leaves it marked."""
+ from gateway.webapp_listener import bundle_missing_reason
+ from hermes_cli import source_build
+
+ _workspace_tree(tmp_path)
+ dist = webapp.webapp_dist_dir(tmp_path)
+ dist.mkdir()
+ (dist / "index.html").write_text("<!doctype html>", encoding="utf-8")
+ receipt_current = False
+ monkeypatch.setattr(source_build, "source_product_current", lambda *_a: receipt_current)
+ monkeypatch.setattr(source_build, "source_build_env", lambda *, explicit=False: {})
+ monkeypatch.setattr(source_build, "build_source_webapp", lambda _root, *, env, explicit: None)
+
+ assert webapp.mark_webapp_stale(tmp_path) is True
+ assert bundle_missing_reason(dist) is not None
+ webapp.prepare_webapp_renderer(tmp_path, skip_build=True)
+ assert bundle_missing_reason(dist) is not None
+
+ webapp.prepare_webapp_renderer(tmp_path)
+ assert bundle_missing_reason(dist) is None
+
+ assert webapp.mark_webapp_stale(tmp_path) is True
+ receipt_current = True
+ webapp.prepare_webapp_renderer(tmp_path)
+ assert bundle_missing_reason(dist) is None
+
+
+def test_no_bundle_is_marked_out_of_date_before_one_is_built(tmp_path: Path):
+ """A failed rebuild with no bundle built leaves nothing to mark: the gateway already reports the
+ Webapp as not built, and the build output folder is left for the builder to create."""
+ _workspace_tree(tmp_path)
+ install_tree = sorted(tmp_path.rglob("*"))
+
+ assert webapp.mark_webapp_stale(tmp_path) is False
+ assert sorted(tmp_path.rglob("*")) == install_tree
+
+
def test_dashboard_and_webapp_builds_share_the_workspace_lock(tmp_path: Path, monkeypatch):
"""While the Dashboard builder holds its lock, the Webapp build lock on the same checkout is taken."""
from pm.filesystem import lock_fd
diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.md
index 7645903c81f..1370b7acc72 100644
--- a/website/docs/user-guide/desktop.md
+++ b/website/docs/user-guide/desktop.md
@@ -128,6 +128,8 @@ Web Access changes only the `webapp:` settings and keeps your `webapp.port`. It
`dashboard.public_url` and `.env` alone, so a standalone dashboard you publish separately keeps its
own address. A standalone profile with its own gateway needs its own `webapp.port` to serve a Webapp
beside the default gateway's. `hermes update` rebuilds the Webapp whenever a profile has it turned on.
+If that build fails, the gateway reports the Webapp unavailable, and the page says so, until
+`hermes webapp` rebuilds it.
### Terminal in the Webapp