Skip to content

The agent that grows with you

fix(webapp-access): Web Access Start builds the Webapp before turning it on

emozillaeb3d916b5ae6
diff --git a/apps/desktop/src/api/webapp-access.test.ts b/apps/desktop/src/api/webapp-access.test.ts
new file mode 100644
index 00000000000..397d1dc0c39
--- /dev/null
+++ b/apps/desktop/src/api/webapp-access.test.ts
@@ -0,0 +1,21 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { startWebAccess } from './webapp-access'
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+})
+
+describe('startWebAccess', () => {
+ it('waits as long as a Webapp build can take', async () => {
+ // Start builds the bundle first, as `hermes webapp` does; that build can wait up to 30 minutes
+ // for another one, far past the default request timeout.
+ const api = vi.fn(async () => ({}))
+ vi.stubGlobal('hermesDesktop', { api })
+
+ await startWebAccess('lan')
+
+ expect(api).toHaveBeenCalledWith(expect.objectContaining({ method: 'POST', path: '/api/webapp-access/start' }))
+ expect((api.mock.calls[0] as unknown as [{ timeoutMs?: number }])[0].timeoutMs).toBeGreaterThan(30 * 60_000)
+ })
+})
diff --git a/apps/desktop/src/api/webapp-access.ts b/apps/desktop/src/api/webapp-access.ts
index 39270f76cba..b8571d9fe8e 100644
--- a/apps/desktop/src/api/webapp-access.ts
+++ b/apps/desktop/src/api/webapp-access.ts
@@ -24,6 +24,10 @@ export interface WebAccessChange extends WebAccessStatus {
restart_started: boolean
}
+/** Start builds the Webapp bundle first, as `hermes webapp` does; that build waits up to 30 minutes
+ * for another build of it. */
+const START_REQUEST_TIMEOUT_MS = 35 * 60_000
+
export function getWebAccessStatus(): Promise<WebAccessStatus> {
return hermesApi<WebAccessStatus>({ ...profileScoped(), path: '/api/webapp-access/status' })
}
@@ -33,7 +37,8 @@ export function startWebAccess(mode: WebAccessMode, publicUrl?: string): Promise
...profileScoped(),
body: { mode, public_url: publicUrl },
method: 'POST',
- path: '/api/webapp-access/start'
+ path: '/api/webapp-access/start',
+ timeoutMs: START_REQUEST_TIMEOUT_MS
})
}
diff --git a/hermes_cli/web_routers/webapp_access.py b/hermes_cli/web_routers/webapp_access.py
index b6c008b095f..c541227c1c4 100644
--- a/hermes_cli/web_routers/webapp_access.py
+++ b/hermes_cli/web_routers/webapp_access.py
@@ -81,7 +81,11 @@ 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")
- host, public_url = await _scoped(profile, lambda _gateway: webapp_access.register(body.mode, body.public_url))
+ host, public_url, callback = await _scoped(
+ profile, lambda _gateway: webapp_access.plan(body.mode, body.public_url))
+ # The bundle before anything lasting: a failed build registers, writes and restarts nothing.
+ await _scoped(profile, lambda _gateway: webapp_access.build_bundle())
+ await _scoped(profile, lambda _gateway: webapp_access.register(callback))
def _start(gateway):
webapp_access.serve(host, public_url)
diff --git a/hermes_cli/webapp_access.py b/hermes_cli/webapp_access.py
index ff1ae5765ec..0bfcf36df3a 100644
--- a/hermes_cli/webapp_access.py
+++ b/hermes_cli/webapp_access.py
@@ -96,11 +96,10 @@ def _register_nous_sign_in(callback_url: str) -> None:
save_env_value(_CLIENT_ID_ENV, str(result["client_id"]))
-def register(mode: str, public_url: Optional[str] = None) -> tuple[str, str]:
- """Register Nous sign-in for *mode*; returns the ``(host, public_url)`` for :func:`serve`.
-
- Re-registered on every start, so the callback follows a changed LAN address or URL. Writes no
- config: it waits on the portal, so callers do it before taking the config lock."""
+def plan(mode: str, public_url: Optional[str] = None) -> tuple[str, str, str]:
+ """Check that *mode* can be served and signed in to; returns ``(host, public_url, callback)``:
+ the bind host and the URL to pin for :func:`serve`, and the sign-in callback for
+ :func:`register`. Changes nothing, so Start runs it before any slow or lasting step."""
if mode == "lan":
address = lan_address()
if address is None:
@@ -113,8 +112,28 @@ def register(mode: str, public_url: Optional[str] = None) -> tuple[str, str]:
raise WebappAccessError(f"Unknown access mode {mode!r}.")
if not nous_signed_in():
raise WebappAccessError("Sign in to your Nous account under Providers first.")
- _register_nous_sign_in(f"{url}/auth/callback")
- return host, pinned
+ return host, pinned, f"{url}/auth/callback"
+
+
+def build_bundle() -> None:
+ """Build the Webapp bundle the gateway serves, with the function ``hermes webapp`` uses (it
+ reuses a current bundle), so Start never turns on a Webapp with nothing to serve."""
+ from hermes_cli.config import get_project_root
+ from hermes_cli.webapp import WebappBuildError, prepare_webapp_renderer
+
+ try:
+ prepare_webapp_renderer(get_project_root())
+ except WebappBuildError as exc:
+ raise WebappAccessError(
+ f"{str(exc).rstrip('.')}. Run hermes webapp --build-only to see the full output, then start again.") from exc
+
+
+def register(callback_url: str) -> None:
+ """Register Nous sign-in for *callback_url*.
+
+ Re-registered on every start, so the callback follows a changed LAN address or URL. Writes no
+ config: it waits on the portal, so callers do it before taking the config lock."""
+ _register_nous_sign_in(callback_url)
def serve(host: str, public_url: str) -> None:
diff --git a/tests/hermes_cli/test_webapp_access.py b/tests/hermes_cli/test_webapp_access.py
index fed9db76b3a..9face66118a 100644
--- a/tests/hermes_cli/test_webapp_access.py
+++ b/tests/hermes_cli/test_webapp_access.py
@@ -49,6 +49,22 @@ def nous(monkeypatch):
return callbacks
[email protected](autouse=True)
+def builds(monkeypatch):
+ """Capture the Webapp bundle builds (``hermes_cli.webapp.prepare_webapp_renderer``) instead of
+ compiling the renderer."""
+ from hermes_cli import webapp
+
+ roots: list = []
+
+ def prepare(project_root, **_options):
+ roots.append(project_root)
+ return webapp.webapp_dist_dir(project_root)
+
+ monkeypatch.setattr(webapp, "prepare_webapp_renderer", prepare)
+ return roots
+
+
def _config() -> dict:
from hermes_cli.config import load_config
@@ -201,3 +217,33 @@ def test_web_access_answers_the_native_app_and_the_loopback_token_only():
with pytest.raises(HTTPException) as refused:
owner_on_this_machine(request(gated=True, native=False))
assert refused.value.status_code == 403
+
+
+def test_start_builds_the_webapp_bundle_before_turning_it_on(client, restarts, nous, builds):
+ """Start builds the bundle the gateway serves (``apps/desktop/dist-webapp``) with the function
+ ``hermes webapp`` uses, reusing it when current, so it never reports a Webapp with nothing to
+ serve as running."""
+ from hermes_cli.config import get_project_root
+
+ assert client.post("/api/webapp-access/start", json={"mode": "lan"}).status_code == 200
+ assert builds == [get_project_root()]
+ assert restarts == ["turning on Web Access"]
+
+
+def test_a_failed_build_turns_nothing_on_and_says_how_to_build(client, restarts, nous, monkeypatch):
+ """When the bundle cannot be built, Start registers nothing with the Portal, writes nothing and
+ restarts nothing, and its error names the command that builds the bundle."""
+ from hermes_cli import webapp
+
+ def fail(_project_root, **_options):
+ raise webapp.WebappBuildError("Browser-hosted Desktop build failed: npm exited 1")
+
+ monkeypatch.setattr(webapp, "prepare_webapp_renderer", fail)
+
+ response = client.post("/api/webapp-access/start", json={"mode": "lan"})
+ assert response.status_code == 400
+ assert "npm exited 1" in response.json()["detail"]
+ assert "hermes webapp --build-only" in response.json()["detail"]
+ assert nous == []
+ assert restarts == []
+ assert not _config()["webapp"]["enabled"]