The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(web-access): a failed restart names its cause, page icons skip sign-in, empty own URL shows no LAN address
Tekniumf5fb4cc28aa3
diff --git a/apps/desktop/src/api/webapp-access.ts b/apps/desktop/src/api/webapp-access.tsindex 50df950f823..8a7670e93b5 100644--- a/apps/desktop/src/api/webapp-access.ts+++ b/apps/desktop/src/api/webapp-access.ts@@ -16,6 +16,9 @@ export interface WebAccessStatus {nous_signed_in: booleanport: numberpublic_url: string+ /** The newest restart of this gateway exited without replacing it; `pid` is the `restart_pid` that+ * restart answered, `reason` the last line it wrote (or its exit code). */+ restart_failure?: null | { exit_code: number; pid: number; reason: string }}/** Start/stop save the config and restart the gateway; a refused restart keeps the config.@@ -23,6 +26,7 @@ export interface WebAccessStatus {export interface WebAccessChange extends WebAccessStatus {restart_busy?: booleanrestart_error?: string+ restart_pid?: numberrestart_started: boolean}diff --git a/apps/desktop/src/app/settings/web-access-settings.test.tsx b/apps/desktop/src/app/settings/web-access-settings.test.tsxindex 21fbb05c76a..4676a0af460 100644--- a/apps/desktop/src/app/settings/web-access-settings.test.tsx+++ b/apps/desktop/src/app/settings/web-access-settings.test.tsx@@ -245,6 +245,39 @@ describe('WebAccessSettings', () => {expect(toast.message).toBe("The gateway didn't stop serving the web app within 90 seconds.")})+ it('names the cause when the restart exits without replacing the gateway', async () => {+ // The restart answered `restart_started` with its pid, then exited at once: the old gateway keeps+ // serving the old config. An older restart's failure (another pid) is not this one's.+ const pending: WebAccessStatus = { ...OFF, enabled: true, mode: 'lan' }+ const failure = (pid: number, reason: string) => ({ exit_code: 1, pid, reason })+ mocked.startWebAccess.mockResolvedValue({ ...pending, restart_pid: 4242, restart_started: true })+ renderPane(OFF)+ const start = await screen.findByRole('button', { name: 'Start' })+ mocked.getWebAccessStatus+ .mockResolvedValueOnce({ ...pending, restart_failure: failure(1111, 'an older restart') })+ .mockResolvedValue({ ...pending, restart_failure: failure(4242, 'run `hermes pm repair`') })++ fireEvent.click(start)++ await waitFor(() => expect($notifications.get()).toHaveLength(1), { timeout: 8000 })+ const [toast] = $notifications.get()+ expect(toast.kind).toBe('error')+ expect(toast.message).toBe("The gateway couldn't restart: run `hermes pm repair`")+ }, 15_000)++ it('shows no LAN address under My own URL while the URL is empty', async () => {+ renderPane(OFF)+ fireEvent.click(await screen.findByRole('button', { name: 'My own URL' }))++ expect(screen.queryByText(/192\.168\.1\.50/)).toBeNull()++ fireEvent.change(screen.getByPlaceholderText('https://hermes.example.com'), {+ target: { value: 'https://hermes.tail.ts.net' }+ })++ expect(screen.getByText('https://hermes.tail.ts.net')).toBeTruthy()+ })+it('says that network access is not encrypted', async () => {// LAN mode is plain HTTP: anyone on the network can read the traffic.renderPane(OFF)diff --git a/apps/desktop/src/app/settings/web-access-settings.tsx b/apps/desktop/src/app/settings/web-access-settings.tsxindex 5afe0bf72bb..113b2f754bb 100644--- a/apps/desktop/src/app/settings/web-access-settings.tsx+++ b/apps/desktop/src/app/settings/web-access-settings.tsx@@ -73,9 +73,17 @@ function appliesConfig(status: WebAccessStatus): boolean {return phase !== 'pendingOn' && phase !== 'pendingOff'}+/** The restart the pane waits on exited without replacing the gateway; `reason` is its last line. */+class RestartFailed extends Error {+ constructor(readonly reason: string) {+ super(reason)+ }+}+/** Poll until the restarted gateway applies the saved config. Start, Stop and Restart all wait here:- * until the old gateway exits it still answers with what it served before. */-async function waitForRestart(): Promise<WebAccessStatus> {+ * until the old gateway exits it still answers with what it served before. A restart (`restartPid`)+ * that exits first leaves the old gateway serving, so the wait ends there with its reason. */+async function waitForRestart(restartPid?: number): Promise<WebAccessStatus> {for (const deadline = Date.now() + RESTART_TIMEOUT_MS; Date.now() < deadline; ) {await new Promise(resolve => setTimeout(resolve, RESTART_POLL_MS))// The backend answering this may be the gateway being restarted.@@ -84,6 +92,10 @@ async function waitForRestart(): Promise<WebAccessStatus> {if (status && appliesConfig(status)) {return status}++ if (restartPid !== undefined && status?.restart_failure?.pid === restartPid) {+ throw new RestartFailed(status.restart_failure.reason)+ }}throw new Error('timeout')@@ -137,6 +149,25 @@ function addressOf(status: WebAccessStatus, lanUrl: null | string): string {return lanUrl ?? ''}+/** Until web access starts, the address is the one being chosen: an own URL not typed yet has none,+ * not the LAN address. A web app on this computer only has no choice to show. */+function chosenAddress(status: WebAccessStatus, lanUrl: null | string, mode: WebAccessMode, publicUrl: string): string {+ if (status.mode === 'local') {+ return addressOf(status, lanUrl)+ }++ return mode === 'public' ? publicUrl.trim() : (lanUrl ?? '')+}++/** A restart that exited says why; otherwise the wait timed out. */+function restartError(err: unknown, change: WebAccessChange, w: WebAccessTranslations): Error {+ if (err instanceof RestartFailed) {+ return new Error(w.restartFailedBecause(err.reason))+ }++ return new Error(change.enabled ? w.startTimedOut : w.stopTimedOut)+}+/** A change saved but not applied yet is not a failure: the pane shows it waiting for the restart,* and the notice says why, without the CLI's refusal text. */function notifyRestartHeld(result: WebAccessChange, w: WebAccessTranslations): void {@@ -150,7 +181,7 @@ function WebAccessForm({ queryKey, status, w }: FormProps): ReactElement {const [publicUrl, setPublicUrl] = useState(status.public_url)const phase = phaseOf(status)const lanUrl = status.lan_address ? `http://${status.lan_address}:${status.port}` : null- const url = addressOf(status, lanUrl)+ const url = phase === 'off' ? chosenAddress(status, lanUrl, mode, publicUrl) : addressOf(status, lanUrl)const ready = status.nous_signed_in && (mode === 'lan' ? Boolean(lanUrl) : publicUrl.trim().startsWith('https://'))const apply = (next: WebAccessStatus): void => {@@ -171,8 +202,7 @@ function WebAccessForm({ queryKey, status, w }: FormProps): ReactElement {return}- const timedOut = result.enabled ? w.startTimedOut : w.stopTimedOut- apply(await waitForRestart().catch(() => Promise.reject(new Error(timedOut))))+ apply(await waitForRestart(result.restart_pid).catch(err => Promise.reject(restartError(err, result, w))))} catch (err) {notifyError(err, w.failed)} finally {diff --git a/apps/desktop/src/i18n/ar_settings.ts b/apps/desktop/src/i18n/ar_settings.tsindex 6dd1ec82d4f..3980af999b6 100644--- a/apps/desktop/src/i18n/ar_settings.ts+++ b/apps/desktop/src/i18n/ar_settings.ts@@ -730,6 +730,7 @@ export const arSettings = {unavailableDetail: reason => `تعذّر على البوابة تقديم تطبيق الويب: ${reason}`,restartBusy: 'تم الحفظ. توجد محادثة قيد التشغيل، لذا لم تُعَد تشغيل البوابة. اختر «إعادة تشغيل البوابة» عند انتهائها.',restartFailed: 'تم الحفظ، لكن تعذّرت إعادة تشغيل البوابة. اختر «إعادة تشغيل البوابة» للمحاولة مجددًا.',+ restartFailedBecause: reason => `تعذّرت إعادة تشغيل البوابة: ${reason}`,startTimedOut: 'لم تقدّم البوابة تطبيق الويب خلال 90 ثانية.',stopTimedOut: 'لم تتوقف البوابة عن تقديم تطبيق الويب خلال 90 ثانية.',start: 'تشغيل',diff --git a/apps/desktop/src/i18n/de_gateway_host.ts b/apps/desktop/src/i18n/de_gateway_host.tsindex 6f4681fac80..2e068fae10e 100644--- a/apps/desktop/src/i18n/de_gateway_host.ts+++ b/apps/desktop/src/i18n/de_gateway_host.ts@@ -27,6 +27,7 @@ export const deGatewayHost: GatewayHostTranslations = {unavailableDetail: reason => `Das Gateway konnte die Web-App nicht bereitstellen: ${reason}`,restartBusy: 'Gespeichert. Ein Chat läuft, deshalb wurde das Gateway nicht neu gestartet. Wähle „Gateway neu starten“, sobald er beendet ist.',restartFailed: 'Gespeichert, aber das Gateway konnte nicht neu starten. Wähle „Gateway neu starten“, um es erneut zu versuchen.',+ restartFailedBecause: reason => `Das Gateway konnte nicht neu starten: ${reason}`,startTimedOut: 'Das Gateway hat die Web-App nicht innerhalb von 90 Sekunden bereitgestellt.',stopTimedOut: 'Das Gateway hat die Bereitstellung der Web-App nicht innerhalb von 90 Sekunden beendet.',start: 'Starten',diff --git a/apps/desktop/src/i18n/en_gateway_host.ts b/apps/desktop/src/i18n/en_gateway_host.tsindex f8d837e47be..28ac0f05ddf 100644--- a/apps/desktop/src/i18n/en_gateway_host.ts+++ b/apps/desktop/src/i18n/en_gateway_host.ts@@ -27,6 +27,7 @@ export const enGatewayHost: GatewayHostTranslations = {unavailableDetail: reason => `The gateway couldn't serve the web app: ${reason}`,restartBusy: "Saved. A chat is running, so the gateway didn't restart. Choose Restart gateway once it ends.",restartFailed: "Saved, but the gateway couldn't restart. Choose Restart gateway to try again.",+ restartFailedBecause: reason => `The gateway couldn't restart: ${reason}`,startTimedOut: "The gateway didn't serve the web app within 90 seconds.",stopTimedOut: "The gateway didn't stop serving the web app within 90 seconds.",start: 'Start',diff --git a/apps/desktop/src/i18n/es_gateway_host.ts b/apps/desktop/src/i18n/es_gateway_host.tsindex 9a1b4e89069..4156b7c5ba2 100644--- a/apps/desktop/src/i18n/es_gateway_host.ts+++ b/apps/desktop/src/i18n/es_gateway_host.ts@@ -28,6 +28,7 @@ export const esGatewayHost: GatewayHostTranslations = {unavailableDetail: reason => `El gateway no pudo servir la aplicación web: ${reason}`,restartBusy: 'Guardado. Hay un chat en curso, así que el gateway no se reinició. Elige «Reiniciar gateway» cuando termine.',restartFailed: 'Guardado, pero el gateway no pudo reiniciarse. Elige «Reiniciar gateway» para volver a intentarlo.',+ restartFailedBecause: reason => `El gateway no pudo reiniciarse: ${reason}`,startTimedOut: 'El gateway no sirvió la aplicación web en 90 segundos.',stopTimedOut: 'El gateway no dejó de servir la aplicación web en 90 segundos.',start: 'Iniciar',diff --git a/apps/desktop/src/i18n/fr_gateway_host.ts b/apps/desktop/src/i18n/fr_gateway_host.tsindex 6754f5e74a9..8c7cb1b0a32 100644--- a/apps/desktop/src/i18n/fr_gateway_host.ts+++ b/apps/desktop/src/i18n/fr_gateway_host.ts@@ -27,6 +27,7 @@ export const frGatewayHost: GatewayHostTranslations = {unavailableDetail: reason => `La passerelle n'a pas pu servir l'application web : ${reason}`,restartBusy: "Enregistré. Une conversation est en cours, la passerelle n'a donc pas redémarré. Choisissez « Redémarrer la passerelle » une fois qu'elle est terminée.",restartFailed: "Enregistré, mais la passerelle n'a pas pu redémarrer. Choisissez « Redémarrer la passerelle » pour réessayer.",+ restartFailedBecause: reason => `La passerelle n'a pas pu redémarrer : ${reason}`,startTimedOut: "La passerelle n'a pas servi l'application web en 90 secondes.",stopTimedOut: "La passerelle n'a pas cessé de servir l'application web en 90 secondes.",start: 'Démarrer',diff --git a/apps/desktop/src/i18n/ja_gateway_host.ts b/apps/desktop/src/i18n/ja_gateway_host.tsindex d89186b9784..b4a0c681a29 100644--- a/apps/desktop/src/i18n/ja_gateway_host.ts+++ b/apps/desktop/src/i18n/ja_gateway_host.ts@@ -27,6 +27,7 @@ export const jaGatewayHost: GatewayHostTranslations = {unavailableDetail: reason => `ゲートウェイが Web アプリを提供できませんでした: ${reason}`,restartBusy: '保存しました。チャットが実行中のため、ゲートウェイは再起動しませんでした。終了したら「ゲートウェイを再起動」を選んでください。',restartFailed: '保存しましたが、ゲートウェイを再起動できませんでした。「ゲートウェイを再起動」を選んで再試行してください。',+ restartFailedBecause: reason => `ゲートウェイを再起動できませんでした: ${reason}`,startTimedOut: 'ゲートウェイが 90 秒以内に Web アプリを提供しませんでした。',stopTimedOut: 'ゲートウェイが 90 秒以内に Web アプリの提供を停止しませんでした。',start: '開始',diff --git a/apps/desktop/src/i18n/ru_gateway_host.ts b/apps/desktop/src/i18n/ru_gateway_host.tsindex efb36b05558..f4d7e53dcab 100644--- a/apps/desktop/src/i18n/ru_gateway_host.ts+++ b/apps/desktop/src/i18n/ru_gateway_host.ts@@ -27,6 +27,7 @@ export const ruGatewayHost: GatewayHostTranslations = {unavailableDetail: reason => `Шлюзу не удалось открыть веб-приложение: ${reason}`,restartBusy: 'Сохранено. Идёт чат, поэтому шлюз не перезапущен. Когда он закончится, нажмите «Перезапустить шлюз».',restartFailed: 'Сохранено, но шлюз не удалось перезапустить. Нажмите «Перезапустить шлюз», чтобы попробовать снова.',+ restartFailedBecause: reason => `Не удалось перезапустить шлюз: ${reason}`,startTimedOut: 'Шлюз не открыл веб-приложение за 90 секунд.',stopTimedOut: 'Шлюз не перестал открывать веб-приложение за 90 секунд.',start: 'Запустить',diff --git a/apps/desktop/src/i18n/types_gateway_host.ts b/apps/desktop/src/i18n/types_gateway_host.tsindex be995939854..421aa6da396 100644--- a/apps/desktop/src/i18n/types_gateway_host.ts+++ b/apps/desktop/src/i18n/types_gateway_host.ts@@ -30,6 +30,8 @@ export interface WebAccessTranslations {unavailableDetail: (reason: string) => stringrestartBusy: stringrestartFailed: string+ /** A restart that exited without replacing the gateway, with the last line it wrote. */+ restartFailedBecause: (reason: string) => stringstartTimedOut: stringstopTimedOut: stringstart: stringdiff --git a/apps/desktop/src/i18n/zh-hant_settings.ts b/apps/desktop/src/i18n/zh-hant_settings.tsindex 60b8d74d086..ed04807839a 100644--- a/apps/desktop/src/i18n/zh-hant_settings.ts+++ b/apps/desktop/src/i18n/zh-hant_settings.ts@@ -997,6 +997,7 @@ export const zhHantSettings = {unavailableDetail: reason => `閘道無法提供網頁應用程式:${reason}`,restartBusy: '已儲存。有對話正在進行,因此閘道沒有重新啟動。對話結束後請選擇「重新啟動閘道」。',restartFailed: '已儲存,但閘道無法重新啟動。請選擇「重新啟動閘道」重試。',+ restartFailedBecause: reason => `閘道無法重新啟動:${reason}`,startTimedOut: '閘道未能在 90 秒內提供網頁應用程式。',stopTimedOut: '閘道未能在 90 秒內停止提供網頁應用程式。',start: '啟動',diff --git a/apps/desktop/src/i18n/zh_gateway_host.ts b/apps/desktop/src/i18n/zh_gateway_host.tsindex 47e8f45a00d..fdb9e74267f 100644--- a/apps/desktop/src/i18n/zh_gateway_host.ts+++ b/apps/desktop/src/i18n/zh_gateway_host.ts@@ -27,6 +27,7 @@ export const zhGatewayHost: GatewayHostTranslations = {unavailableDetail: reason => `网关无法提供网页应用:${reason}`,restartBusy: '已保存。有对话正在进行,因此网关没有重启。对话结束后请选择“重启网关”。',restartFailed: '已保存,但网关无法重启。请选择“重启网关”重试。',+ restartFailedBecause: reason => `网关无法重启:${reason}`,startTimedOut: '网关未能在 90 秒内提供网页应用。',stopTimedOut: '网关未能在 90 秒内停止提供网页应用。',start: '启动',diff --git a/hermes_cli/dashboard_auth/middleware.py b/hermes_cli/dashboard_auth/middleware.pyindex de66b031cc5..654eb041cd0 100644--- a/hermes_cli/dashboard_auth/middleware.py+++ b/hermes_cli/dashboard_auth/middleware.py@@ -46,12 +46,17 @@ _GATE_PUBLIC_PREFIXES: tuple[str, ...] = ("/api/auth/providers", "/api/mcp/oauth/callback/","/assets/", "/dashboard-plugins/", "/favicon.ico", "/ds-assets/", "/fonts/", "/fonts-terminal/")+# Page icons, matched exactly. Browsers fetch them without cookies (the Webapp's page icon and+# home-screen icon are ``/apple-touch-icon.png``), so behind the gate they hit the sign-in redirect+# and log an auto-SSO ``login_start`` with no sign-in behind it.+_GATE_PUBLIC_ICONS: frozenset[str] = frozenset({"/apple-touch-icon.png"})+def _path_is_public(path: str) -> bool:- """:data:`PUBLIC_API_PATHS` (shared with the legacy middleware) matched exactly so- ``/api/status`` never exposes ``/api/status/extension``; :data:`_GATE_PUBLIC_PREFIXES`- prefix-matched."""- return path in PUBLIC_API_PATHS or any(+ """:data:`PUBLIC_API_PATHS` (shared with the legacy middleware) and :data:`_GATE_PUBLIC_ICONS`+ matched exactly so ``/api/status`` never exposes ``/api/status/extension``;+ :data:`_GATE_PUBLIC_PREFIXES` prefix-matched."""+ return path in PUBLIC_API_PATHS or path in _GATE_PUBLIC_ICONS or any(path == p or path.startswith(p) for p in _GATE_PUBLIC_PREFIXES)diff --git a/hermes_cli/web_routers/webapp_access.py b/hermes_cli/web_routers/webapp_access.pyindex 9218e9fa68e..1dc6bcdf120 100644--- a/hermes_cli/web_routers/webapp_access.py+++ b/hermes_cli/web_routers/webapp_access.py@@ -27,6 +27,7 @@ from hermes_cli.web_routers._common import ()_restart_gateway_after = late("_restart_gateway_after", "hermes_cli.web_server_gateway")+_gateway_restart_failure = late("gateway_restart_failure", "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.@@ -113,7 +114,10 @@ async def _restart(gateway: Optional[str], what: str) -> dict:@router.get("/api/webapp-access/status")async def webapp_access_status(profile: Optional[str] = None):- return await _scoped(profile, lambda _gateway: webapp_access.access_status())+ """``restart_failure``: the newest restart of this gateway exited without replacing it, and why;+ the pane waiting on that restart stops and says so instead of timing out."""+ return await _scoped(profile, lambda gateway: {+ **webapp_access.access_status(), "restart_failure": _gateway_restart_failure(gateway)})@router.post("/api/webapp-access/start")diff --git a/hermes_cli/web_server_gateway.py b/hermes_cli/web_server_gateway.pyindex 716030090e4..3d23569503a 100644--- a/hermes_cli/web_server_gateway.py+++ b/hermes_cli/web_server_gateway.py@@ -690,6 +690,44 @@ def _restart_gateway_after(profile: Optional[str], *, what: str, label: str) ->return {"restart_started": True, "restart_action": "gateway-restart", "restart_pid": proc.pid}+_ANSI_ESCAPE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")+_RESTART_REASON_MAX = 300+++def _last_restart_log_line() -> str:+ """The last line the newest ``gateway-restart`` child wrote to its log, or ``""``. Each spawn+ starts its section with ``=== gateway-restart started ... ===`` (``_spawn_hermes_action``)."""+ log_path = _ACTION_LOG_DIR / _ACTION_LOG_FILES["gateway-restart"]+ try:+ with log_path.open("rb") as log:+ log.seek(max(0, log.seek(0, os.SEEK_END) - 64 * 1024))+ tail = log.read().decode("utf-8", errors="replace")+ except OSError:+ return ""+ section = tail.rsplit("=== gateway-restart started", 1)[-1].split("\n", 1)[-1]+ lines = [_ANSI_ESCAPE.sub("", line).strip() for line in section.splitlines()]+ last = next((line for line in reversed(lines) if line), "")+ return last[:_RESTART_REASON_MAX]+++def gateway_restart_failure(profile: Optional[str]) -> Optional[dict[str, Any]]:+ """Why the newest restart of the *profile* gateway failed, or ``None`` while it runs, after it+ succeeded, or when this process started none. A child that exits nonzero leaves the old+ gateway serving the old config, so a UI waiting for the new one learns here that none is coming.+ ``pid`` is the ``restart_pid`` the restart answered, so the UI ignores an older restart."""+ from hermes_cli import web_server+ recent = web_server._LAST_GATEWAY_RESTART+ if recent is None:+ return None+ _spawned_at, proc, command = recent+ if tuple(arg for arg in command if arg != "--interrupt") != tuple(_gateway_subcommand(profile, "restart")):+ return None+ exit_code = proc.poll()+ if not exit_code:+ return None+ return {"pid": proc.pid, "exit_code": exit_code, "reason": _last_restart_log_line() or f"exit code {exit_code}"}++def _split_text_for_speak_stream(text: str, cap: int) -> list:"""Split *text* into provider-cap-sized pieces on sentence boundaries.diff --git a/tests/hermes_cli/test_dashboard_auth_page_icons.py b/tests/hermes_cli/test_dashboard_auth_page_icons.pynew file mode 100644index 00000000000..2c67dbb6c23--- /dev/null+++ b/tests/hermes_cli/test_dashboard_auth_page_icons.py@@ -0,0 +1,47 @@+"""Page icons answer without a session, like ``/favicon.ico``; other public files stay gated.++Browsers fetch the page icon and the home-screen icon without cookies, so a gated icon answers+with the sign-in redirect and logs an auto-SSO ``login_start`` with no sign-in behind it.+"""+from __future__ import annotations++import pytest+from fastapi.testclient import TestClient++from hermes_cli import web_server+from hermes_cli.dashboard_auth import clear_providers, register_provider+from tests.hermes_cli.conftest_dashboard_auth import StubAuthProvider+++def gated_webapp(monkeypatch, tmp_path):+ """The gateway's Webapp behind the sign-in gate, serving a renderer dist with its icons."""+ dist = tmp_path / "dist-webapp"+ dist.mkdir()+ (dist / "index.html").write_text("<!doctype html><title>Hermes</title>", encoding="utf-8")+ for name in ("apple-touch-icon.png", "favicon.ico", "hermes.png"):+ (dist / name).write_bytes(b"\x89PNG icon bytes")+ clear_providers()+ register_provider(StubAuthProvider())+ for key, value in (("bound_host", "0.0.0.0"), ("bound_port", 9119), ("auth_required", True),+ ("trusted_public_hosts", frozenset()), ("ui_surface", "webapp"),+ ("listener_public_url", ""), ("web_dist", dist)):+ monkeypatch.setattr(web_server.app.state, key, value, raising=False)+ yield TestClient(web_server.app, base_url="http://127.0.0.1:9119")+ clear_providers()++[email protected]("path", ["/apple-touch-icon.png", "/favicon.ico"])+def test_page_icons_answer_without_a_session(gated_webapp, path):+ response = gated_webapp.get(path, follow_redirects=False)++ assert response.status_code == 200, response.headers.get("location")+ assert response.content == b"\x89PNG icon bytes"++[email protected]("path", ["/hermes.png", "/apple-touch-icon.png.map", "/apple-touch-icon.pngx"])+def test_other_files_still_require_sign_in(gated_webapp, path):+ response = gated_webapp.get(path, follow_redirects=False)++ assert response.status_code == 302+ assert "/login" in response.headers["location"]diff --git a/tests/hermes_cli/test_webapp_access_restart_failure.py b/tests/hermes_cli/test_webapp_access_restart_failure.pynew file mode 100644index 00000000000..2b8bef1016b--- /dev/null+++ b/tests/hermes_cli/test_webapp_access_restart_failure.py@@ -0,0 +1,103 @@+"""A Web Access restart whose child exits without replacing the gateway says why on ``/status``.++The restart route answers ``restart_started: true`` as soon as ``hermes gateway restart`` is+spawned. When that child exits at once (a missing dependency environment prints ``run `hermes pm+repair```), the old gateway keeps serving the old config, so the pane polling ``/status`` for the+new one needs the failure and its cause there, not a 90-second timeout.+"""++from __future__ import annotations++import os+import sys++import pytest++pytest.importorskip("fastapi")+++def client(monkeypatch):+ from tests.hermes_cli.native_gateway_client import native_desktop_client++ return native_desktop_client(monkeypatch)+++def restart_child(monkeypatch, tmp_path):+ """The real restart spawn (``_spawn_gateway_restart`` → ``_spawn_hermes_action``, log header+ included), with the ``hermes gateway restart`` argv swapped for a stand-in child whose output+ and exit code each test picks: no gateway lifecycle code runs."""+ import hermes_cli._launchers as launchers+ from hermes_cli import web_server+ import hermes_cli.web_server_gateway as gw+ from hermes_cli import webapp_access++ monkeypatch.setattr(gw, "_ACTION_LOG_DIR", tmp_path / "logs")+ monkeypatch.setattr(gw, "_action_targets_system_gateway", lambda _subcommand: False)+ monkeypatch.setattr(gw, "_profile_action_environment", lambda _subcommand, _overrides=None: {+ "PATH": os.environ.get("PATH", "")})+ monkeypatch.setattr(gw, "live_session_refusal", lambda _profile, _verb: None)+ monkeypatch.setattr(web_server, "_LAST_GATEWAY_RESTART", None)+ monkeypatch.setattr(webapp_access, "lan_address", lambda: "192.168.1.50")+ child: dict[str, str] = {}++ def _runtime_command(_root, _subcommand):+ return [sys.executable, "-c", child["script"]]++ monkeypatch.setattr(launchers, "runtime_command", _runtime_command)+ yield child+ recent = web_server._LAST_GATEWAY_RESTART+ if recent is not None:+ recent[1].wait(timeout=10)+++def _status_after_child_exits(client, pid: int) -> dict:+ from hermes_cli import web_server++ web_server._LAST_GATEWAY_RESTART[1].wait(timeout=10)+ assert web_server._LAST_GATEWAY_RESTART[1].pid == pid+ response = client.get("/api/webapp-access/status")+ assert response.status_code == 200, response.text+ return response.json()+++def test_a_restart_child_that_exits_at_once_reports_its_last_error_line(client, restart_child):+ restart_child["script"] = (+ "import sys; print('Starting gateway restart...');"+ "print(\"error: Hermes's dependency environment is missing; run `hermes pm repair`\");"+ "sys.exit(1)"+ )++ answer = client.post("/api/webapp-access/restart").json()+ assert answer["restart_started"] is True++ failure = _status_after_child_exits(client, answer["restart_pid"])["restart_failure"]+ assert failure == {+ "pid": answer["restart_pid"],+ "exit_code": 1,+ "reason": "error: Hermes's dependency environment is missing; run `hermes pm repair`",+ }+++def test_a_restart_child_that_succeeds_reports_no_failure(client, restart_child):+ restart_child["script"] = "print('Gateway restarted.')"++ answer = client.post("/api/webapp-access/restart").json()+ assert answer["restart_started"] is True++ assert _status_after_child_exits(client, answer["restart_pid"])["restart_failure"] is None+++def test_a_silent_failure_names_its_exit_code_not_an_earlier_runs_error(client, restart_child):+ import hermes_cli.web_server_gateway as gw++ gw._ACTION_LOG_DIR.mkdir(parents=True)+ (gw._ACTION_LOG_DIR / "gateway-restart.log").write_text(+ "\n=== gateway-restart started 2026-10-01 09:00:00 ===\nan earlier run's error\n")+ restart_child["script"] = "import sys; sys.exit(3)"++ answer = client.post("/api/webapp-access/restart").json()++ failure = _status_after_child_exits(client, answer["restart_pid"])["restart_failure"]+ assert failure["reason"] == "exit code 3"