The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp-access): Web Access Start, Stop and Restart run one at a time
emozillacad03b90f669
diff --git a/hermes_cli/web_routers/webapp_access.py b/hermes_cli/web_routers/webapp_access.pyindex 91df88571bb..c2c24bfb0c6 100644--- a/hermes_cli/web_routers/webapp_access.py+++ b/hermes_cli/web_routers/webapp_access.py@@ -2,14 +2,16 @@Thin HTTP over :mod:`hermes_cli.webapp_access`. Every handler acts on the home of the gateway thatserves the requested profile; start and stop write its ``webapp:`` config and restart that gateway,-which reads the config only when it starts. Only the machine's owner reaches them-(:func:`owner_on_this_machine`), never a browser signed in over the network.+which reads the config only when it starts. Start, Stop and Restart run one at a time. Only the+machine's owner reaches them (:func:`owner_on_this_machine`), never a browser signed in over the+network."""from __future__ import annotationsimport asyncio-from contextlib import contextmanager+import threading+from contextlib import asynccontextmanager, contextmanagerfrom typing import Any, Callable, Optionalfrom fastapi import APIRouter, Depends, HTTPException, Request@@ -25,6 +27,11 @@ from hermes_cli.web_routers._common import ()_restart_gateway_after = late("_restart_gateway_after", "hermes_cli.web_server_gateway")+# One Web Access change at a time in this backend (every Desktop window's pane talks to it): a+# Start, Stop or Restart waits for the one in flight, from its build through the restart request,+# so the Portal's callback, the config and the gateway all end on the last change asked for.+_CHANGE_LOCK = threading.Lock()+_CHANGE_POLL_SECONDS = 0.05def owner_on_this_machine(request: Request) -> None:@@ -82,6 +89,18 @@ async def _in_gateway_home(gateway: Optional[str], fn: Callable[[], Any]) -> Anyraise HTTPException(status_code=400, detail=str(exc)) from exc+@asynccontextmanager+async def _one_change_at_a_time():+ """Hold :data:`_CHANGE_LOCK` for one change. Polled rather than awaited on a worker thread, so a+ request cancelled while it waits never takes the lock, and the steps run on any event loop."""+ while not _CHANGE_LOCK.acquire(blocking=False):+ await asyncio.sleep(_CHANGE_POLL_SECONDS)+ try:+ yield+ finally:+ _CHANGE_LOCK.release()++async def _restart(gateway: Optional[str], what: str) -> dict:"""The status after asking the *gateway* profile's gateway to restart onto the saved config. Runsafter the config write released the config lock, as main's config routes do: the restart spawn@@ -99,13 +118,14 @@ async def webapp_access_status(profile: Optional[str] = None):@router.post("/api/webapp-access/start")async def start_webapp_access(body: StartBody, profile: Optional[str] = None):profile = destructive_profile(profile, "POST /api/webapp-access/start")- gateway, (host, public_url, callback) = await _scoped(- profile, lambda gateway: (gateway, webapp_access.plan(body.mode, body.public_url)))- # The bundle before anything lasting: a failed build registers, writes and restarts nothing.- await _in_gateway_home(gateway, webapp_access.build_bundle)- await _in_gateway_home(gateway, lambda: webapp_access.register(callback))- await _scoped(profile, lambda _gateway: webapp_access.serve(host, public_url), config_write=True)- return await _restart(gateway, "turning on Web Access")+ async with _one_change_at_a_time():+ gateway, (host, public_url, callback) = await _scoped(+ profile, lambda gateway: (gateway, webapp_access.plan(body.mode, body.public_url)))+ # The bundle before anything lasting: a failed build registers, writes and restarts nothing.+ await _in_gateway_home(gateway, webapp_access.build_bundle)+ await _in_gateway_home(gateway, lambda: webapp_access.register(callback))+ await _scoped(profile, lambda _gateway: webapp_access.serve(host, public_url), config_write=True)+ return await _restart(gateway, "turning on Web Access")@router.post("/api/webapp-access/stop")@@ -116,7 +136,8 @@ async def stop_webapp_access(profile: Optional[str] = None):webapp_access.turn_off()return gateway- return await _restart(await _scoped(profile, _stop, config_write=True), "turning off Web Access")+ async with _one_change_at_a_time():+ return await _restart(await _scoped(profile, _stop, config_write=True), "turning off Web Access")@router.post("/api/webapp-access/restart")@@ -124,4 +145,5 @@ async def restart_webapp_access(profile: Optional[str] = None):"""Apply the saved config to a gateway that has not restarted onto it yet: restart that gatewayand nothing else (no Portal registration, no build, no config write)."""profile = destructive_profile(profile, "POST /api/webapp-access/restart")- return await _restart(await _scoped(profile, lambda gateway: gateway), "applying Web Access")+ async with _one_change_at_a_time():+ return await _restart(await _scoped(profile, lambda gateway: gateway), "applying Web Access")diff --git a/tests/hermes_cli/test_webapp_access.py b/tests/hermes_cli/test_webapp_access.pyindex 1fa511c33ee..e422d1016ce 100644--- a/tests/hermes_cli/test_webapp_access.py+++ b/tests/hermes_cli/test_webapp_access.py@@ -730,3 +730,74 @@ def test_the_gateway_restart_and_status_run_outside_the_config_lock(client, nousassert free_during == {"restart": True, "status": True}[email protected](("held", "second"), [("build", "stop"), ("registration", "public")])+def test_web_access_changes_run_one_at_a_time(client, restarts, nous, monkeypatch, held, second):+ """Start, Stop and Restart each build, register, write and restart as one change, and a second+ change waits for the one in flight. A Stop sent while a Start builds therefore ends with the+ Webapp off, and two windows starting different modes end with the Portal's callback and the+ served mode both the last one's: never Nous sign-in returning to an address the Webapp does not+ serve, nor the Webapp on the network after the user stopped it."""+ import threading++ from hermes_cli import webapp, webapp_access+ from hermes_cli.web_routers import webapp_access as routes++ class WatchedLock:+ """The routes' change lock, noting when a change found it held."""++ def __init__(self):+ self.lock, self.found_held = threading.Lock(), threading.Event()++ def acquire(self, blocking=True, timeout=-1):+ taken = self.lock.acquire(blocking, timeout)+ if not taken:+ self.found_held.set()+ return taken++ def release(self):+ self.lock.release()++ watched = WatchedLock()+ monkeypatch.setattr(routes, "_CHANGE_LOCK", watched)+ entered, release = threading.Event(), threading.Event()++ def hold(*_args, **_options):+ if not entered.is_set():+ entered.set()+ release.wait(20)++ if held == "build":+ monkeypatch.setattr(webapp, "prepare_webapp_renderer", lambda root, **options: hold())+ else:+ monkeypatch.setattr(webapp_access, "_register_nous_sign_in",+ lambda callback: (hold(), nous.append(callback)))+ public_url = "https://hermes.example.test"+ requests = {"lan": ("/api/webapp-access/start", {"mode": "lan"}),+ "stop": ("/api/webapp-access/stop", None),+ "public": ("/api/webapp-access/start", {"mode": "public", "public_url": public_url})}+ answers: dict[str, int] = {}++ def send(name: str) -> None:+ # Each thread needs its own client on the same native-Desktop app, which mints a grant per request.+ other = TestClient(client.app, raise_server_exceptions=False)+ path, body = requests[name]+ answers[name] = other.post(path, json=body).status_code++ first = threading.Thread(target=send, args=("lan",), daemon=True)+ first.start()+ assert entered.wait(20)+ later = threading.Thread(target=send, args=(second,), daemon=True)+ later.start()+ assert watched.found_held.wait(20)+ assert restarts == [] and answers == {} # the second change waits for the first+ release.set()+ first.join(30)+ later.join(30)+ assert answers == {"lan": 200, second: 200}+ block = _config()["webapp"]+ if second == "stop":+ assert restarts == ["turning on Web Access", "turning off Web Access"]+ assert block["enabled"] is False+ else:+ assert nous == ["http://192.168.1.50:9120/auth/callback", f"{public_url}/auth/callback"]+ assert (block["enabled"], block.get("public_url")) == (True, public_url)