The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(dashboard): Desktop and dashboard read the update receipt instead of inferring success (#91277 Phase-1 bullet 3)
Teknium8804e78354c9
diff --git a/apps/desktop/src/store/updates.ts b/apps/desktop/src/store/updates.tsindex 476354e1b7d..0cf80596516 100644--- a/apps/desktop/src/store/updates.ts+++ b/apps/desktop/src/store/updates.ts@@ -587,6 +587,30 @@ function completedAfterRestart(return !!actionId && status.lines.some(line => line === `=== hermes-update completed ${actionId} ===`)}+/** Whether the durable update receipt attached to the status proves the+ * outcome of THIS apply (#91277 bullet 3). Only a finished receipt whose+ * run started at-or-after we kicked the update off counts — an older+ * receipt describes a previous update, and a still-running one proves+ * nothing yet. The 60s slack absorbs client/backend clock skew. */+function receiptProvesOutcome(+ status: Awaited<ReturnType<typeof getActionStatus>>,+ applyStartedAtMs: number+): boolean {+ const receipt = status.receipt++ if (!receipt || !receipt.finished_at || !receipt.started_at) {+ return false+ }++ if (receipt.outcome !== 'success' && receipt.outcome !== 'partial' && receipt.outcome !== 'failed') {+ return false+ }++ const startedMs = Date.parse(receipt.started_at)++ return Number.isFinite(startedMs) && startedMs >= applyStartedAtMs - 60_000+}+function legacyBackendReachedTarget(status: BackendUpdateCheckResponse,targetSha: string | undefined,@@ -623,6 +647,7 @@ async function runBackendUpdate(): Promise<DesktopUpdateApplyResult> {: undefinedconst started = await updateHermes()+ const applyStartedAtMs = Date.now()if (!started.ok) {const message = (started as { message?: string }).message || translateNow('updates.applyStatus.notAvailable')@@ -686,6 +711,14 @@ async function runBackendUpdate(): Promise<DesktopUpdateApplyResult> {return finishBackendApply(true)}+ // #91277 bullet 3: the backend now attaches the durable update+ // receipt to the status. A receipt whose run STARTED after we kicked+ // this update off is authoritative — read its outcome instead of+ // inferring from log markers or timing out across the restart gap.+ if (last.exit_code === null && receiptProvesOutcome(last, applyStartedAtMs)) {+ return finishBackendApply(last.receipt!.outcome === 'success')+ }+if (!started.action_id && last.exit_code === null) {try {const status = await checkHermesUpdate(true)diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.tsindex 2c80596c6ac..0cf405680fe 100644--- a/apps/desktop/src/types/hermes.ts+++ b/apps/desktop/src/types/hermes.ts@@ -1224,12 +1224,28 @@ export interface ActionResponse {already_running?: boolean}+export interface UpdateReceiptSummary {+ outcome: 'running' | 'success' | 'partial' | 'failed' | 'refused' | string+ started_at: string | null+ finished_at: string | null+ pre_sha: string | null+ post_sha: string | null+ post_version: string | null+ fleet_states: string[]+}+export interface ActionStatusResponse {exit_code: number | nulllines: string[]name: stringpid: number | nullrunning: boolean+ /** hermes-update only: durable completion identity recovered from update.log. */+ action_id?: string+ /** hermes-update only: summary of the durable update receipt (#91277 bullet 3) —+ * the authoritative outcome record, present even when the dashboard+ * restarted itself mid-action and lost its in-memory registries. */+ receipt?: UpdateReceiptSummary}export interface BackendUpdateCommit {diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex cc689f07b0b..0fce1edb94b 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -5530,6 +5530,7 @@ async def get_action_status(name: str, lines: int = 200):tail = _tail_lines(log_path, requested_lines)durable_update_action_id = None+ update_receipt_summary = Noneif name == "hermes-update":durable_lines = _tail_lines(_ACTION_LOG_DIR / "update.log", 2000)durable_update_action_id = _durable_completed_update_action_id(durable_lines)@@ -5537,6 +5538,14 @@ async def get_action_status(name: str, lines: int = 200):marker = f"=== hermes-update completed {durable_update_action_id} ==="if marker not in tail:tail = [*tail, marker][-requested_lines:]+ # Phase-1 bullet 3 (#91277): the update receipt is the durable,+ # structured truth about the last update — written by every run+ # including refused/failed ones, and it survives the dashboard+ # restarting itself mid-action. Surface its summary alongside the+ # log-marker recovery so clients (Desktop, dashboard) READ the+ # outcome instead of inferring it from liveness probes+ # (#81193/#87359 class).+ update_receipt_summary = _latest_update_receipt_summary()proc = _ACTION_PROCS.get(name)if proc is None:@@ -5546,6 +5555,17 @@ async def get_action_status(name: str, lines: int = 200):pid = result.get("pid") if result else Noneif result is None and durable_update_action_id:exit_code = 0+ if (+ result is None+ and exit_code is None+ and update_receipt_summary is not None+ and update_receipt_summary.get("outcome") in ("success", "partial")+ ):+ # No in-memory result and no log marker (e.g. log rotated), but+ # the receipt proves a completed run: report its outcome rather+ # than a null that clients time out on. ``partial`` maps to+ # exit 1 exactly like the CLI run itself did.+ exit_code = 0 if update_receipt_summary["outcome"] == "success" else 1else:exit_code = proc.poll()running = exit_code is None@@ -5569,9 +5589,69 @@ async def get_action_status(name: str, lines: int = 200):}if durable_update_action_id:response["action_id"] = durable_update_action_id+ if update_receipt_summary is not None:+ response["receipt"] = update_receipt_summaryreturn response+def _latest_update_receipt_summary() -> Optional[Dict[str, Any]]:+ """Compact summary of the most recent update receipt, or None.++ Phase-1 bullet 3 (#91277): the receipt (written by EVERY ``hermes+ update`` run since #91283, including refused and failed ones, with a+ ``latest.json`` pointer) is the durable success signal the Desktop and+ dashboard should read instead of inferring outcomes from liveness+ probes across the update's stop/start gap (#81193, #87359). Summary+ only — steps and skips stay in the full receipt endpoint.+ Never raises.+ """+ try:+ from hermes_cli.update_receipt import read_latest_receipt++ receipt = read_latest_receipt()+ if not receipt:+ return None+ fleet = receipt.get("fleet") or []+ return {+ "outcome": receipt.get("outcome"),+ "started_at": receipt.get("started_at"),+ "finished_at": receipt.get("finished_at"),+ "pre_sha": (receipt.get("pre_update") or {}).get("sha"),+ "post_sha": (receipt.get("post_update") or {}).get("sha"),+ "post_version": (receipt.get("post_update") or {}).get("version"),+ "fleet_states": sorted(+ {str(e.get("state")) for e in fleet if isinstance(e, dict)}+ ),+ }+ except Exception:+ return None++[email protected]("/api/hermes/update/receipt")+async def get_update_receipt():+ """The most recent update receipt — the durable update-outcome record.++ Phase-1 bullet 3 (#91277): dashboards and the Desktop read this instead+ of inferring update success from backend liveness (the inference misread+ the update's own restart gap as 'Backend update failed' / 'boot failed'+ — #81193, #87359). Returns the FULL receipt (steps, skips, gateway+ restart outcome, fleet matrix) plus a compact ``summary``; 404 when no+ update has run since receipts landed.+ """+ try:+ from hermes_cli.update_receipt import read_latest_receipt++ receipt = read_latest_receipt()+ except Exception:+ receipt = None+ if not receipt:+ raise HTTPException(+ status_code=404,+ detail="No update receipt found (no `hermes update` run recorded).",+ )+ return {"receipt": receipt, "summary": _latest_update_receipt_summary()}++# Per-row fields that no session LIST consumer reads but that dominate the# payload. ``system_prompt`` is the fully rendered prompt — tens of KB per# row — and made a 21-row /api/sessions response 528KB (96% dead weight),diff --git a/tests/hermes_cli/test_update_receipt_endpoint.py b/tests/hermes_cli/test_update_receipt_endpoint.pynew file mode 100644index 00000000000..cca062d3ef3--- /dev/null+++ b/tests/hermes_cli/test_update_receipt_endpoint.py@@ -0,0 +1,145 @@+"""Phase-1 bullet 3 (#91277): the dashboard/Desktop READ the update receipt.++The update receipt (written by every `hermes update` run since #91283,+`latest.json` pointer) is the durable outcome record. These tests pin:++- GET /api/hermes/update/receipt returns the full receipt + summary; 404+ when none exists.+- GET /api/actions/hermes-update/status attaches the receipt summary, and+ uses a finished receipt as the outcome when both in-memory registries AND+ the log marker are gone (dashboard restarted + log rotated).+"""++import json+from pathlib import Path++import pytest++import hermes_cli.web_server as web_server+++def client():+ try:+ from starlette.testclient import TestClient+ except ImportError:+ pytest.skip("fastapi/starlette not installed")+ from hermes_cli.web_server import _SESSION_HEADER_NAME, _SESSION_TOKEN, app++ c = TestClient(app)+ c.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN+ return c+++def _write_receipt(tmp_path: Path, monkeypatch, *, outcome="success") -> dict:+ receipt = {+ "schema": 1,+ "started_at": "2026-08-23T07:00:00+00:00",+ "finished_at": "2026-08-23T07:03:20+00:00",+ "argv": ["hermes", "update"],+ "pid": 12345,+ "outcome": outcome,+ "pre_update": {"sha": "a" * 40, "version": "0.20.4"},+ "post_update": {"sha": "b" * 40, "version": "0.20.5"},+ "steps": [{"name": "pre_update_backup", "ok": True, "detail": "", "at": ""}],+ "skips": [],+ "gateway_restart": {},+ "fleet": [+ {"profile": "default", "pid": 1, "code_sha": "b" * 40, "state": "current"}+ ],+ }+ receipt_dir = tmp_path / "logs" / "update_receipts"+ receipt_dir.mkdir(parents=True)+ (receipt_dir / "latest.json").write_text(json.dumps(receipt), encoding="utf-8")+ import hermes_cli.update_receipt as ur++ monkeypatch.setattr(ur, "_receipt_dir", lambda: receipt_dir)+ return receipt+++class TestUpdateReceiptEndpoint:++ def test_receipt_endpoint_returns_full_receipt_and_summary(self, client, tmp_path, monkeypatch):+ receipt = _write_receipt(tmp_path, monkeypatch)++ resp = client.get("/api/hermes/update/receipt")++ assert resp.status_code == 200+ data = resp.json()+ assert data["receipt"]["outcome"] == "success"+ assert data["receipt"]["steps"] == receipt["steps"]+ summary = data["summary"]+ assert summary["outcome"] == "success"+ assert summary["pre_sha"] == "a" * 40+ assert summary["post_sha"] == "b" * 40+ assert summary["post_version"] == "0.20.5"+ assert summary["fleet_states"] == ["current"]++ def test_receipt_endpoint_404_when_no_receipt(self, client, tmp_path, monkeypatch):+ import hermes_cli.update_receipt as ur++ monkeypatch.setattr(ur, "_receipt_dir", lambda: tmp_path / "none")++ resp = client.get("/api/hermes/update/receipt")++ assert resp.status_code == 404+++class TestUpdateStatusReadsReceipt:++ def _clear_registries(self, monkeypatch, tmp_path):+ monkeypatch.setattr(web_server, "_ACTION_LOG_DIR", tmp_path / "actions")+ (tmp_path / "actions").mkdir(exist_ok=True)+ monkeypatch.setattr(web_server, "_ACTION_PROCS", {})+ monkeypatch.setattr(web_server, "_ACTION_RESULTS", {})+ monkeypatch.setattr(web_server, "_ACTION_COMMANDS", {})+ monkeypatch.setattr(web_server, "_ACTION_IDS", {})++ def test_status_attaches_receipt_summary(self, client, tmp_path, monkeypatch):+ _write_receipt(tmp_path, monkeypatch)+ self._clear_registries(monkeypatch, tmp_path)++ resp = client.get("/api/actions/hermes-update/status")++ assert resp.status_code == 200+ data = resp.json()+ assert data["receipt"]["outcome"] == "success"++ def test_finished_receipt_is_the_outcome_when_marker_and_memory_gone(self, client, tmp_path, monkeypatch):+ """Dashboard restarted (registries lost) AND update.log has no+ completion marker (rotated): the receipt alone reports success."""+ _write_receipt(tmp_path, monkeypatch, outcome="success")+ self._clear_registries(monkeypatch, tmp_path)++ resp = client.get("/api/actions/hermes-update/status")++ data = resp.json()+ assert data["running"] is False+ assert data["exit_code"] == 0++ def test_partial_receipt_maps_to_exit_1(self, client, tmp_path, monkeypatch):+ _write_receipt(tmp_path, monkeypatch, outcome="partial")+ self._clear_registries(monkeypatch, tmp_path)++ resp = client.get("/api/actions/hermes-update/status")++ assert resp.json()["exit_code"] == 1++ def test_running_receipt_proves_nothing(self, client, tmp_path, monkeypatch):+ """An unfinished receipt (crashed run / mid-update) must not report+ an outcome — clients keep polling."""+ receipt = _write_receipt(tmp_path, monkeypatch, outcome="running")+ self._clear_registries(monkeypatch, tmp_path)++ resp = client.get("/api/actions/hermes-update/status")++ assert resp.json()["exit_code"] is None++ def test_non_update_actions_untouched(self, client, tmp_path, monkeypatch):+ _write_receipt(tmp_path, monkeypatch)+ self._clear_registries(monkeypatch, tmp_path)++ resp = client.get("/api/actions/gateway-restart/status")++ data = resp.json()+ assert "receipt" not in data