The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(peer): resolve hidden canonical Bot Chats in hermes peer dm
Teknium231e613d3d66
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex 25402eba027..88fe3d7cd55 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -4203,6 +4203,15 @@ class APIServerAdapter(BasePlatformAdapter):offset = self._parse_nonnegative_int(request.query.get("offset"), default=0, maximum=1_000_000)source = request.query.get("source") or Noneinclude_children = _coerce_request_bool(request.query.get("include_children"), default=False)+ # Exact-title lookup, used by `hermes peer dm` to resolve a peer's+ # canonical "Bot Chat" session. ``include_hidden`` is honored ONLY+ # alongside a title filter: Bot Mode hides canonical chats, so a+ # title-scoped lookup must see them (issue #91583), but a blanket+ # hidden listing stays off this client surface.+ title_filter = (request.query.get("title") or "").strip() or None+ include_hidden = bool(title_filter) and _coerce_request_bool(+ request.query.get("include_hidden"), default=False+ )sessions = await asyncio.to_thread(db.list_sessions_rich,source=source,limit=limit,@@ -4212,7 +4221,14 @@ class APIServerAdapter(BasePlatformAdapter):# A pin means "always reachable", so a pinned conversation that has# aged past the recency window is back-filled rather than dropped.include_pinned=True,+ # Push the title needle into SQL so a hidden/old canonical row is+ # found even when it falls outside the recency window, then apply+ # the exact-match contract below (search_query is substring-based).+ search_query=title_filter,+ include_hidden=include_hidden,)+ if title_filter:+ sessions = [s for s in sessions if (s.get("title") or "").strip() == title_filter]# Back-filled pins arrive PAST the limit, so counting them would report# another page that doesn't exist. Only the recency window decides.windowed = sum(1 for s in sessions if not s.get("pinned"))diff --git a/hermes_cli/subcommands/peer.py b/hermes_cli/subcommands/peer.pyindex 13d10637a6a..2cd710a79b9 100644--- a/hermes_cli/subcommands/peer.py+++ b/hermes_cli/subcommands/peer.py@@ -108,8 +108,18 @@ def _base_url(peer: dict, profile: str | None) -> str:def _find_bot_chat(base: str, key: str) -> str | None:- """The remote canonical Bot Chat's session id, or None."""- listing = _request(f"{base}/api/sessions?limit=200", key)+ """The remote canonical Bot Chat's session id, or None.++ Bot Mode always HIDES canonical chats, so the plain listing (which+ excludes hidden sessions) misses an existing Bot Chat and the caller+ would try to create a duplicate that the peer's UNIQUE(title) guard+ rejects (issue #91583). Newer peers support an exact-title lookup with+ ``include_hidden=1``; older peers ignore the unknown query params and+ return the ordinary visible listing, so this single request degrades+ to exactly the previous behavior against them.+ """+ query = urllib.parse.urlencode({"limit": 200, "title": BOT_CHAT_TITLE, "include_hidden": 1})+ listing = _request(f"{base}/api/sessions?{query}", key)for session in listing.get("data") or []:if isinstance(session, dict) and (session.get("title") or "").strip() == BOT_CHAT_TITLE:return str(session.get("id") or "") or None@@ -120,12 +130,26 @@ def _ensure_bot_chat(base: str, key: str) -> str:existing = _find_bot_chat(base, key)if existing:return existing- created = _request(- f"{base}/api/sessions",- key,- method="POST",- body={"title": BOT_CHAT_TITLE, "source": "bot_peer_dm"},- )+ try:+ created = _request(+ f"{base}/api/sessions",+ key,+ method="POST",+ body={"title": BOT_CHAT_TITLE, "source": "bot_peer_dm"},+ )+ except urllib.error.HTTPError as exc:+ detail = _http_error_detail(exc)+ if exc.code == 400 and "title" in detail.lower():+ # Older peer (no title/include_hidden lookup support): its+ # canonical Bot Chat exists but is hidden, so we couldn't see it+ # and the create collided with the UNIQUE(title) guard.+ raise RuntimeError(+ f"Peer already has a '{BOT_CHAT_TITLE}' session but it is hidden and the "+ f"peer's gateway is too old to expose hidden sessions to this lookup "+ f"(HTTP 400: {detail}). Update the peer's hermes-agent, or unhide the "+ f"session there: PATCH /api/sessions/<id> {{\"hidden\": false}}."+ ) from exc+ raise# Real api_server wraps the row: {"object": "hermes.session", "session": {...}}.session = created.get("session") if isinstance(created.get("session"), dict) else createdsession_id = str(session.get("id") or session.get("session_id") or "")@@ -248,7 +272,10 @@ def cmd_peer(args) -> int:except urllib.error.HTTPError as exc:print(f"Peer '{peer_name}' rejected the request (HTTP {exc.code}): {_http_error_detail(exc)}", file=sys.stderr)return 1- except (urllib.error.URLError, TimeoutError, OSError, RuntimeError) as exc:+ except RuntimeError as exc:+ print(f"Peer '{peer_name}': {exc}", file=sys.stderr)+ return 1+ except (urllib.error.URLError, TimeoutError, OSError) as exc:print(f"Could not reach peer '{peer_name}': {exc}", file=sys.stderr)return 1diff --git a/tests/gateway/test_peer_dm_hidden_e2e.py b/tests/gateway/test_peer_dm_hidden_e2e.pynew file mode 100644index 00000000000..166697603f6--- /dev/null+++ b/tests/gateway/test_peer_dm_hidden_e2e.py@@ -0,0 +1,143 @@+"""E2E: ``hermes peer dm`` against a REAL api_server gateway whose canonical+Bot Chat session is HIDDEN (issue #91583).++Two real HERMES homes in spirit: the "peer" side is a real+:class:`APIServerAdapter` bound to a real loopback TCP socket over a real+SQLite ``state.db`` (its own tmp HERMES_HOME) containing a hidden+``Bot Chat`` row — exactly what Bot Mode leaves behind. The "local" side is+the stock ``hermes peer dm`` client code (``hermes_cli.subcommands.peer``),+untouched, talking real HTTP with the real API key auth.++Only the model turn itself is stubbed (``_run_agent``); every HTTP handler,+auth check, and SQLite query in the resolution chain is the real thing.+"""++import asyncio+import json+import threading+from types import SimpleNamespace++import pytest+from aiohttp import web++from gateway.config import PlatformConfig+from gateway.platforms.api_server import APIServerAdapter+from hermes_cli.subcommands import peer as peer_cmd+from hermes_state import SessionDB++API_KEY = "sk-peer-e2e-key-123456"+++def _build_app(adapter: APIServerAdapter) -> web.Application:+ app = web.Application()+ app.router.add_get("/api/sessions", adapter._handle_list_sessions)+ app.router.add_post("/api/sessions", adapter._handle_create_session)+ app.router.add_post("/api/sessions/{session_id}/chat", adapter._handle_session_chat)+ return app+++def peer_gateway(tmp_path, monkeypatch):+ """A real api_server gateway (own HERMES_HOME + state.db) on a real socket."""+ peer_home = tmp_path / "peer_home"+ peer_home.mkdir()+ db = SessionDB(peer_home / "state.db")++ # Bot Mode's footprint: the canonical Bot Chat exists and is HIDDEN.+ hidden_id = db.create_session("botchat_hidden_1", "gateway_botmode")+ assert db.set_session_title(hidden_id, "Bot Chat")+ assert db.set_session_hidden(hidden_id, True)+ # And a decoy visible session, so the listing isn't trivially empty.+ other_id = db.create_session("ordinary_1", "api_server")+ db.set_session_title(other_id, "Ordinary Chat")++ adapter = APIServerAdapter(PlatformConfig(enabled=True, extra={"key": API_KEY}))+ adapter._session_db = db++ async def fake_run_agent(user_message, **kwargs):+ return (+ {+ "final_response": f"e2e reply to: {user_message}",+ "session_id": kwargs.get("session_id"),+ },+ {},+ )++ adapter._run_agent = fake_run_agent++ loop = asyncio.new_event_loop()+ started = threading.Event()+ state = {}++ def _serve():+ asyncio.set_event_loop(loop)++ async def _start():+ runner = web.AppRunner(_build_app(adapter))+ await runner.setup()+ site = web.TCPSite(runner, "127.0.0.1", 0)+ await site.start()+ state["runner"] = runner+ state["port"] = runner.addresses[0][1]+ started.set()++ loop.run_until_complete(_start())+ loop.run_forever()++ thread = threading.Thread(target=_serve, daemon=True)+ thread.start()+ assert started.wait(timeout=10), "peer gateway failed to start"+ try:+ yield SimpleNamespace(+ url=f"http://127.0.0.1:{state['port']}",+ db=db,+ hidden_id=hidden_id,+ )+ finally:+ async def _stop():+ await state["runner"].cleanup()++ asyncio.run_coroutine_threadsafe(_stop(), loop).result(timeout=10)+ loop.call_soon_threadsafe(loop.stop)+ thread.join(timeout=10)+ close = getattr(db, "close", None)+ if callable(close):+ close()+++def test_peer_dm_reaches_hidden_canonical_bot_chat_e2e(peer_gateway, monkeypatch, capsys):+ """The stock peer dm client resolves the HIDDEN canonical Bot Chat on a+ real gateway, runs the chat turn on it, and creates no duplicate row."""+ monkeypatch.setattr(peer_cmd, "_load_peers", lambda: {"spark": {"url": peer_gateway.url}})+ monkeypatch.setattr(peer_cmd, "_peer_secret", lambda name: API_KEY)++ rc = peer_cmd.cmd_peer(+ SimpleNamespace(peer_action="dm", target="spark", message="disk status?", json=True)+ )++ assert rc == 0+ payload = json.loads(capsys.readouterr().out)+ assert payload["reply"] == "e2e reply to: disk status?"+ assert payload["session_id"] == peer_gateway.hidden_id++ # The real DB still holds exactly ONE Bot Chat row and it is still hidden.+ rows = peer_gateway.db.list_sessions_rich(limit=200, include_hidden=True)+ bot_chats = [r for r in rows if (r.get("title") or "").strip() == "Bot Chat"]+ assert [r["id"] for r in bot_chats] == [peer_gateway.hidden_id]+ assert bool(bot_chats[0].get("hidden"))+++def test_hidden_lookup_requires_title_filter_e2e(peer_gateway):+ """Server-side bound: include_hidden without a title filter stays a+ visible-only listing (no blanket hidden exposure on this surface)."""+ import urllib.request++ req = urllib.request.Request(+ f"{peer_gateway.url}/api/sessions?limit=200&include_hidden=1",+ headers={"Authorization": f"Bearer {API_KEY}"},+ )+ with urllib.request.urlopen(req, timeout=10) as resp:+ listing = json.loads(resp.read().decode())+ ids = [s["id"] for s in listing["data"]]+ assert peer_gateway.hidden_id not in ids+ assert "ordinary_1" in idsdiff --git a/tests/hermes_cli/test_peer_cmd.py b/tests/hermes_cli/test_peer_cmd.pyindex a3e4d15ae37..6a261625621 100644--- a/tests/hermes_cli/test_peer_cmd.py+++ b/tests/hermes_cli/test_peer_cmd.py@@ -186,3 +186,137 @@ def test_dm_reuses_existing_bot_chat(monkeypatch, capsys, fake_peer_server):assert payload["reply"] == "reply from the other machine"# No new session was created — the existing canonical chat was reused.assert _FakePeer.sessions == ["bc_existing"]+++# ── hidden canonical Bot Chat (issue #91583) ─────────────────────────────────+++class _HiddenBotChatPeer(_FakePeer):+ """A NEW-style peer: its Bot Chat exists but is HIDDEN (Bot Mode hides+ canonical chats), so it only appears in the listing when the client+ sends the exact-title + include_hidden lookup."""++ hidden_sessions: list = []+ get_queries: list = []++ def do_GET(self):+ type(self).auth_seen.append(self.headers.get("Authorization", ""))+ if self.path.startswith("/api/sessions"):+ from urllib.parse import parse_qs, urlparse++ query = parse_qs(urlparse(self.path).query)+ type(self).get_queries.append(query)+ data = [{"id": s, "title": "Bot Chat", "hidden": False} for s in type(self).sessions]+ if query.get("title", [""])[0] == "Bot Chat" and query.get("include_hidden", ["0"])[0] in ("1", "true"):+ data += [{"id": s, "title": "Bot Chat", "hidden": True} for s in type(self).hidden_sessions]+ return self._json({"object": "list", "data": data})+ return self._json({"error": {"message": "not found"}}, 404)+++class _OldHiddenBotChatPeer(_FakePeer):+ """An OLD peer: ignores title/include_hidden, its hidden Bot Chat is+ invisible in every listing, and the duplicate create trips the DB's+ UNIQUE(title) guard with the real api_server 400 shape."""++ def do_GET(self):+ type(self).auth_seen.append(self.headers.get("Authorization", ""))+ if self.path.startswith("/api/sessions"):+ return self._json({"object": "list", "data": []})+ return self._json({"error": {"message": "not found"}}, 404)++ def do_POST(self):+ type(self).auth_seen.append(self.headers.get("Authorization", ""))+ length = int(self.headers.get("Content-Length", 0))+ self.rfile.read(length)+ if self.path == "/api/sessions":+ return self._json(+ {"error": {"message": "Title already in use by session hidden_bc_1", "code": "invalid_title"}},+ 400,+ )+ return self._json({"error": {"message": "not found"}}, 404)+++def hidden_peer_server():+ _HiddenBotChatPeer.sessions = []+ _HiddenBotChatPeer.hidden_sessions = ["bc_hidden"]+ _HiddenBotChatPeer.chats = []+ _HiddenBotChatPeer.auth_seen = []+ _HiddenBotChatPeer.get_queries = []+ server = HTTPServer(("127.0.0.1", 0), _HiddenBotChatPeer)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield f"http://127.0.0.1:{server.server_port}"+ finally:+ server.shutdown()+ thread.join(timeout=5)+++def old_hidden_peer_server():+ _OldHiddenBotChatPeer.sessions = []+ _OldHiddenBotChatPeer.chats = []+ _OldHiddenBotChatPeer.auth_seen = []+ server = HTTPServer(("127.0.0.1", 0), _OldHiddenBotChatPeer)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield f"http://127.0.0.1:{server.server_port}"+ finally:+ server.shutdown()+ thread.join(timeout=5)+++def test_find_bot_chat_sends_hidden_aware_lookup(hidden_peer_server):+ """The lookup carries title + include_hidden so a hidden canonical row resolves."""+ found = peer_cmd._find_bot_chat(hidden_peer_server, "secret-key-123456")+ assert found == "bc_hidden"+ query = _HiddenBotChatPeer.get_queries[-1]+ assert query.get("title") == ["Bot Chat"]+ assert query.get("include_hidden") == ["1"]+++def test_dm_resolves_hidden_bot_chat_without_duplicate_create(monkeypatch, capsys, hidden_peer_server):+ """Regression for issue #91583: hidden canonical Bot Chat must be reused,+ never re-created (the peer's UNIQUE(title) guard rejects the duplicate)."""+ monkeypatch.setattr(peer_cmd, "_load_peers", lambda: {"spark": {"url": hidden_peer_server}})+ monkeypatch.setattr(peer_cmd, "_peer_secret", lambda name: "secret-key-123456")++ rc = peer_cmd.cmd_peer(SimpleNamespace(peer_action="dm", target="spark", message="ping", json=True))++ assert rc == 0+ payload = json.loads(capsys.readouterr().out)+ assert payload["reply"] == "reply from the other machine"+ # No create was attempted: the hidden canonical chat resolved directly.+ assert _HiddenBotChatPeer.sessions == []+ assert _HiddenBotChatPeer.chats == ["ping"]+++def test_dm_older_peer_hidden_duplicate_gives_clear_error(monkeypatch, capsys, old_hidden_peer_server):+ """Against an older peer that can't expose hidden sessions, the UNIQUE(title)+ rejection must surface a diagnosable error naming the hidden canonical chat."""+ monkeypatch.setattr(peer_cmd, "_load_peers", lambda: {"spark": {"url": old_hidden_peer_server}})+ monkeypatch.setattr(peer_cmd, "_peer_secret", lambda name: "secret-key-123456")++ rc = peer_cmd.cmd_peer(SimpleNamespace(peer_action="dm", target="spark", message="ping", json=False))++ assert rc == 1+ err = capsys.readouterr().err+ assert "hidden" in err+ assert "Bot Chat" in err+ assert "Title already in use" in err+++def test_dm_older_peer_with_visible_bot_chat_still_works(monkeypatch, capsys, fake_peer_server):+ """Backward compat: an older peer ignores the new query params and returns+ the plain visible listing — a visible Bot Chat must still resolve."""+ _FakePeer.sessions = ["bc_visible"]+ monkeypatch.setattr(peer_cmd, "_load_peers", lambda: {"spark": {"url": fake_peer_server}})+ monkeypatch.setattr(peer_cmd, "_peer_secret", lambda name: "secret-key-123456")++ rc = peer_cmd.cmd_peer(SimpleNamespace(peer_action="dm", target="spark", message="ping", json=True))++ assert rc == 0+ assert json.loads(capsys.readouterr().out)["reply"] == "reply from the other machine"+ assert _FakePeer.sessions == ["bc_visible"]