The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(web-access): tie a restart's reason to its own log section; a failed Stop says why
Tekniumc835469cea40
diff --git a/apps/desktop/src/app/settings/web-access-settings.test.tsx b/apps/desktop/src/app/settings/web-access-settings.test.tsxindex 4676a0af460..0272a2bc00d 100644--- a/apps/desktop/src/app/settings/web-access-settings.test.tsx+++ b/apps/desktop/src/app/settings/web-access-settings.test.tsx@@ -265,6 +265,24 @@ describe('WebAccessSettings', () => {expect(toast.message).toBe("The gateway couldn't restart: run `hermes pm repair`")}, 15_000)+ it('names the cause when a Stop restart fails while the gateway could not serve the web app', async () => {+ // Saved `enabled: false` reads as applied at once (the gateway serves nothing), but the restart+ // the user asked for exited.+ const unavailable: WebAccessStatus = { ...OFF, gateway: { reason: 'port 9120 is in use', state: 'unavailable', url: null } }+ mocked.stopWebAccess.mockResolvedValue({ ...unavailable, restart_pid: 7, restart_started: true })+ renderPane({ ...unavailable, enabled: true, mode: 'lan' })+ const stop = await screen.findByRole('button', { name: 'Stop' })+ mocked.getWebAccessStatus.mockResolvedValue({+ ...unavailable,+ restart_failure: { exit_code: 1, pid: 7, reason: 'run `hermes pm repair`' }+ })++ fireEvent.click(stop)++ await waitFor(() => expect($notifications.get()).toHaveLength(1), { timeout: 8000 })+ expect($notifications.get()[0].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' }))diff --git a/apps/desktop/src/app/settings/web-access-settings.tsx b/apps/desktop/src/app/settings/web-access-settings.tsxindex 113b2f754bb..0246c7f0c18 100644--- a/apps/desktop/src/app/settings/web-access-settings.tsx+++ b/apps/desktop/src/app/settings/web-access-settings.tsx@@ -89,13 +89,15 @@ async function waitForRestart(restartPid?: number): Promise<WebAccessStatus> {// The backend answering this may be the gateway being restarted.const status = await getWebAccessStatus().catch(() => null)- if (status && appliesConfig(status)) {- return status- }-+ // Before the config check: a Stop of a web app the gateway could not serve reads as applied+ // while the restart the user asked for failed.if (restartPid !== undefined && status?.restart_failure?.pid === restartPid) {throw new RestartFailed(status.restart_failure.reason)}++ if (status && appliesConfig(status)) {+ return status+ }}throw new Error('timeout')diff --git a/hermes_cli/web_server_gateway.py b/hermes_cli/web_server_gateway.pyindex 3d23569503a..5bba58c233a 100644--- a/hermes_cli/web_server_gateway.py+++ b/hermes_cli/web_server_gateway.py@@ -314,6 +314,9 @@ _ACTION_COMMANDS: dict[str, tuple[str, ...]] = {}_ACTION_IDS: dict[str, str] = {}# ``name`` → synthetic result for actions handled without a subprocess (e.g. unsupported Docker updates)._ACTION_RESULTS: dict[str, dict[str, Any]] = {}+# ``name`` → (pid, byte offset of that child's section in its log): a later spawn that fails after+# writing its own header must not lend its text to the child that is still on record.+_ACTION_LOG_STARTS: dict[str, tuple[int, int]] = {}def _terminate_desktop_managed_gateway() -> None:@@ -479,6 +482,7 @@ def _spawn_hermes_action(from hermes_cli.web_server import PROJECT_ROOT_ACTION_LOG_DIR.mkdir(parents=True, exist_ok=True)log_file = open(_ACTION_LOG_DIR / _ACTION_LOG_FILES[name], "ab", buffering=0)+ section_start = os.fstat(log_file.fileno()).st_size# The header carries the action id durably: the update's completion marker lands in the ROOT# update.log every profile shares, and only this id ties one to the action THIS log started.action_id = (env_overrides or {}).get("HERMES_ACTION_ID")@@ -550,6 +554,7 @@ def _spawn_hermes_action(_ACTION_RESULTS.pop(name, None)_ACTION_COMMANDS[name] = tuple(subcommand)_ACTION_PROCS[name] = proc+ _ACTION_LOG_STARTS[name] = (proc.pid, section_start)if action_id:_ACTION_IDS[name] = action_idelse:@@ -694,18 +699,24 @@ _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``)."""+def _restart_log_last_line(pid: int) -> str:+ """The last line the ``gateway-restart`` child *pid* wrote to its log, or ``""``: its section+ runs from the offset ``_spawn_hermes_action`` recorded to the next spawn's header."""+ start = _ACTION_LOG_STARTS.get("gateway-restart")+ if start is None or start[0] != pid:+ return ""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")+ log.seek(start[1])+ section = log.read(256 * 1024).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()]+ header, _, body = section.lstrip("\n").partition("\n")+ if not header.startswith("=== gateway-restart started"):+ return "" # the log was rotated or truncated since+ body = body.split("\n=== gateway-restart started", 1)[0]+ lines = [_ANSI_ESCAPE.sub("", line).strip() for line in body.splitlines()]last = next((line for line in reversed(lines) if line), "")return last[:_RESTART_REASON_MAX]@@ -725,7 +736,7 @@ def gateway_restart_failure(profile: Optional[str]) -> Optional[dict[str, Any]]: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}"}+ return {"pid": proc.pid, "exit_code": exit_code, "reason": _restart_log_last_line(proc.pid) or f"exit code {exit_code}"}def _split_text_for_speak_stream(text: str, cap: int) -> list:diff --git a/tests/hermes_cli/test_webapp_access_restart_failure.py b/tests/hermes_cli/test_webapp_access_restart_failure.pyindex 2b8bef1016b..1fa26fb7203 100644--- a/tests/hermes_cli/test_webapp_access_restart_failure.py+++ b/tests/hermes_cli/test_webapp_access_restart_failure.py@@ -101,3 +101,28 @@ def test_a_silent_failure_names_its_exit_code_not_an_earlier_runs_error(client,failure = _status_after_child_exits(client, answer["restart_pid"])["restart_failure"]assert failure["reason"] == "exit code 3"+++def test_a_retry_that_fails_to_spawn_does_not_lend_its_error_to_the_recorded_child(+ client, restart_child, monkeypatch):+ """A retry writes its own log header before it spawns; when that spawn fails, the child still on+ record keeps its own reason."""+ from hermes_cli import web_server++ monkeypatch.setattr(web_server, "GATEWAY_RESTART_COOLDOWN_SECONDS", 0.0)+ restart_child["script"] = "import sys; print('first child: run `hermes pm repair`'); sys.exit(1)"+ first = client.post("/api/webapp-access/restart").json()+ web_server._LAST_GATEWAY_RESTART[1].wait(timeout=10)++ import hermes_cli.web_server_gateway as gw++ def _spawn_refused(_subcommand, _overrides=None):+ raise RuntimeError("retry could not start")++ monkeypatch.setattr(gw, "_profile_action_environment", _spawn_refused)+ retry = client.post("/api/webapp-access/restart").json()+ assert retry["restart_started"] is False++ failure = client.get("/api/webapp-access/status").json()["restart_failure"]+ assert failure["pid"] == first["restart_pid"]+ assert failure["reason"] == "first child: run `hermes pm repair`"