The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(profiles): report a settle-pending delete as a typed partial success
xieleviaa90c01e9a61
diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.pyindex 2361888988d..e09121174a6 100644--- a/hermes_cli/profiles.py+++ b/hermes_cli/profiles.py@@ -1292,6 +1292,25 @@ def _print_delete_summary(canon: str, profile_dir: Path, gw_running: bool, wrappprint(" ⚠ Gateway is running — it will be stopped.")+class ProfileIdentitySettlementPending(RuntimeError):+ """The profile's directory was deleted, but its durable session/routing identity was not+ settled (``hermes_cli.profile_identity.purge_profile_identity`` returned False).++ Subclasses ``RuntimeError`` so delete-failure handling that treats the error as fatal (the+ CLI's ``hermes profile delete``) keeps working unchanged; surfaces that can report a partial+ success (the dashboard's ``DELETE /api/profiles/{name}``) catch this type — it carries the+ profile, its now-removed path, and the retry command — instead of matching on the message.+ """++ def __init__(self, profile: str, path: Path):+ self.profile = profile+ self.path = path+ self.retry_command = f"hermes profile purge-identity {profile}"+ super().__init__(+ f"Profile '{profile}' was deleted, but its session/routing identity settlement is "+ f"still pending — run: {self.retry_command}")++def delete_profile(name: str, yes: bool = False) -> Path:"""Delete a profile, its wrapper script, and its gateway service (service disabled firstto prevent auto-restart, gateway stopped if running)."""@@ -1376,11 +1395,10 @@ def delete_profile(name: str, yes: bool = False) -> Path:print(f"\nProfile '{canon}' deleted.")if not identity_settled:# Filesystem work and runtime teardown are done; the durable identity is not. Report the- # partial settlement as a failure (same shape as the rmtree error above) instead of a clean- # success, and name the retry.- raise RuntimeError(- f"Profile '{canon}' was deleted, but its session/routing identity settlement is still "- f"pending — run: hermes profile purge-identity {canon}")+ # partial settlement as a typed failure (still a RuntimeError for the CLI's handler)+ # instead of a clean success; the type carries the path and the retry for surfaces that+ # can report a partial success.+ raise ProfileIdentitySettlementPending(canon, profile_dir)return profile_dirdiff --git a/hermes_cli/web_routers/profiles.py b/hermes_cli/web_routers/profiles.pyindex f9b682b6d4b..61243e75c8d 100644--- a/hermes_cli/web_routers/profiles.py+++ b/hermes_cli/web_routers/profiles.py@@ -29,6 +29,7 @@ from fastapi import APIRouter, HTTPException, Queryfrom hermes_cli.web_deps import latefrom hermes_cli.config import get_process_hermes_home+from hermes_cli.profiles import ProfileIdentitySettlementPendingfrom hermes_cli.web_server_config import (_apply_main_model_assignment, _normalize_main_model_assignment, _validated_main_model_selection,)@@ -149,7 +150,9 @@ _MISSING = object()def _profile_errors(log_msg: str, *args, not_found=(FileNotFoundError,),bad_request=(ValueError,)):"""Map hermes_cli.profiles exceptions to HTTP: ``not_found`` -> 404, ``bad_request`` -> 400- (in that order), anything else is logged with ``log_msg`` -> 500. HTTPException passes."""+ (in that order), anything else is logged with ``log_msg`` -> 500. HTTPException passes, and so+ does ``ProfileIdentitySettlementPending`` — a typed partial success the calling endpoint (the+ delete route) owns; it must not flatten into the generic 500."""try:yieldexcept HTTPException:@@ -158,6 +161,8 @@ def _profile_errors(log_msg: str, *args, not_found=(FileNotFoundError,),raise HTTPException(status_code=404, detail=str(e))except bad_request as e:raise HTTPException(status_code=400, detail=str(e))+ except ProfileIdentitySettlementPending:+ raiseexcept Exception as e:_log.exception(log_msg, *args)raise HTTPException(status_code=500, detail=str(e))@@ -828,12 +833,21 @@ async def rename_profile_endpoint(name: str, body: ProfileRename):@router.delete("/api/profiles/{name}")async def delete_profile_endpoint(name: str):"""The dashboard collects the user's confirmation in its own dialog, so ``yes=True``- always skips the CLI's interactive prompt."""+ always skips the CLI's interactive prompt.++ A delete whose identity settlement stays pending answers ``ok`` with ``settlement_pending``+ and the retry command: the profile directory is already gone, and folding that state into+ the generic 500 made a dashboard client read a completed delete as a failure (its retry+ then 404'd)."""from hermes_cli import profiles as profiles_mod- with _profile_errors("DELETE /api/profiles/%s failed", name):- # Polls a running gateway's PID for up to 10 s, then rmtree()s the directory; on the- # loop that parks every request past the desktop's 10 s WebSocket ready-probe.- path = await run_in_threadpool(profiles_mod.delete_profile, name, yes=True)+ try:+ with _profile_errors("DELETE /api/profiles/%s failed", name):+ # Polls a running gateway's PID for up to 10 s, then rmtree()s the directory; on the+ # loop that parks every request past the desktop's 10 s WebSocket ready-probe.+ path = await run_in_threadpool(profiles_mod.delete_profile, name, yes=True)+ except ProfileIdentitySettlementPending as exc:+ return {"ok": True, "path": str(exc.path), "identity_settled": False,+ "settlement_pending": True, "retry_command": exc.retry_command}return {"ok": True, "path": str(path)}diff --git a/tests/hermes_cli/test_profiles.py b/tests/hermes_cli/test_profiles.pyindex 664f9161498..4cfa4e11b91 100644--- a/tests/hermes_cli/test_profiles.py+++ b/tests/hermes_cli/test_profiles.py@@ -448,6 +448,7 @@ class TestDeleteProfile:success: the identity settlement is reported as pending, with the retry named."""from hermes_state import SessionDB+ from hermes_cli.profiles import ProfileIdentitySettlementPendingtmp_path = profile_envcreate_profile("gone", no_alias=True)@@ -461,9 +462,17 @@ class TestDeleteProfile:with patch("hermes_cli.profiles._cleanup_gateway_service"), \patch("hermes_cli.profiles._live_default_multiplexer", return_value=True):- with pytest.raises(RuntimeError, match="identity settlement is still pending"):+ with pytest.raises(ProfileIdentitySettlementPending,+ match="identity settlement is still pending") as ei:delete_profile("gone", yes=True)+ # Typed partial success: the filesystem delete completed, the identity did not, and the+ # payload carries what a surfacing caller needs to report it and retry.+ assert ei.value.profile == "gone"+ assert ei.value.retry_command == "hermes profile purge-identity gone"+ assert not ei.value.path.exists()+ assert isinstance(ei.value, RuntimeError) # the CLI handler catches RuntimeError+assert "hermes profile purge-identity gone" in capsys.readouterr().errcheck = SessionDB(tmp_path / ".hermes" / "state.db")try:diff --git a/tests/hermes_cli/test_web_profile_delete_settlement.py b/tests/hermes_cli/test_web_profile_delete_settlement.pynew file mode 100644index 00000000000..ffafca8e851--- /dev/null+++ b/tests/hermes_cli/test_web_profile_delete_settlement.py@@ -0,0 +1,79 @@+"""``DELETE /api/profiles/{name}``: a settle-pending delete reports a partial success, not a 500.++Deleting a profile can end with the directory gone and the durable session/routing identity+settlement still pending (#112727, delete side of #111926); ``delete_profile`` reports that as+``ProfileIdentitySettlementPending`` *after* the filesystem half completed. Flattened by the+router's generic exception mapping into HTTP 500, it read as "delete failed" — a dashboard client+then retried into a 404. The endpoint owns the partial-success shape; a genuine filesystem+failure (rmtree) must keep the 500.+"""++from __future__ import annotations++from pathlib import Path++import pytest++pytest.importorskip("fastapi")+from fastapi.testclient import TestClient # noqa: E402+++def profile_env(tmp_path, monkeypatch):+ """Path.home() and HERMES_HOME both point into the temp dir (profile ops are HOME-anchored)."""+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ home = tmp_path / ".hermes"+ home.mkdir(exist_ok=True)+ monkeypatch.setenv("HERMES_HOME", str(home))+ return tmp_path+++def client(profile_env):+ from hermes_cli import web_server++ with TestClient(web_server.app, raise_server_exceptions=False) as c:+ c.headers["Authorization"] = f"Bearer {web_server._SESSION_TOKEN}"+ yield c+++def test_settle_pending_delete_reports_partial_success(client, monkeypatch):+ """The profile really is deleted; only the identity settlement is missing — report both."""+ from hermes_cli import profiles as profiles_mod++ monkeypatch.setattr(profiles_mod, "_cleanup_gateway_service", lambda *a, **k: None)+ # A live multiplexer owns the routing index and none is reachable here, so the settlement+ # stays pending — the exact state delete_profile reports after the directory is gone.+ monkeypatch.setattr(profiles_mod, "_live_default_multiplexer", lambda: True)+ profiles_mod.create_profile("gone", no_alias=True)+ gone_dir = profiles_mod.get_profile_dir("gone")++ resp = client.delete("/api/profiles/gone")++ assert resp.status_code == 200, resp.text+ body = resp.json()+ assert body["ok"] is True+ assert body["settlement_pending"] is True+ assert body["identity_settled"] is False+ assert body["retry_command"] == "hermes profile purge-identity gone"+ assert body["path"] == str(gone_dir)+ # Not lying about the filesystem half: the directory is really gone.+ assert not gone_dir.exists()+++def test_filesystem_remove_failure_still_reports_500(client, monkeypatch):+ """A plain rmtree failure keeps the generic 500 — not every delete error is a partial success."""+ from hermes_cli import profiles as profiles_mod++ monkeypatch.setattr(profiles_mod, "_cleanup_gateway_service", lambda *a, **k: None)++ def boom(profile_dir, onexc_handler):+ raise OSError("device busy")++ monkeypatch.setattr(profiles_mod, "_rmtree_with_retry", boom)+ profiles_mod.create_profile("gone", no_alias=True)++ resp = client.delete("/api/profiles/gone")++ assert resp.status_code == 500+ assert "Could not remove profile directory" in resp.json()["detail"]