The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): a tab opened on ?profile=<name> sees its own running turn
Teknium44cc9f491518
diff --git a/hermes_cli/web_routers/chat_ws.py b/hermes_cli/web_routers/chat_ws.pyindex 4261981e078..e10181dda1e 100644--- a/hermes_cli/web_routers/chat_ws.py+++ b/hermes_cli/web_routers/chat_ws.py@@ -630,6 +630,17 @@ async def pty_ws(ws: WebSocket) -> None:# session id, so agent emits fan out to both sinks.+def _authority_for_ticket_home(authority, home: str):+ """The authority serving *home*: *authority* itself for its own home, else the served sibling,+ or None when this process does not serve it."""+ from pathlib import Path++ from gateway.session_authorities import authority_for_home+ if Path(authority.profile_id).resolve() == Path(home).resolve():+ return authority+ return authority_for_home(getattr(authority, 'runner', None), home)++@router.websocket("/api/ws")async def gateway_ws(ws: WebSocket) -> None:if not await _close_unless_sidecar_allowed(ws, allow_internal=True, socket=GATEWAY_SOCKET):@@ -657,6 +668,17 @@ async def gateway_ws(ws: WebSocket) -> None:# The dashboard gate authorizes the whole host (its REST routes take ``?profile=`` for# every profile), so its socket may select any served sibling too.identity = {**identity, 'profile_scope': 'host'}+ ticket_home = getattr(ws, "_hermes_ticket_profile_home", None)+ if ticket_home and authority is not None and identity is not None:+ # A Webapp tab's ticket names its profile (``webapp.issue_gateway_ticket``): bind the socket+ # to that home's authority, as a native ticket does (``gateway/run_api.py``), so a request+ # that names no profile is answered for the tab's profile, not the launch profile.+ served = _authority_for_ticket_home(authority, ticket_home)+ if served is None:+ await ws.close(code=4403)+ return+ ws.scope['hermes.session_authority'] = served+ identity = {**identity, 'profile_id': served.profile_id, 'instance_id': served.instance_id}await handle_ws(ws,auth_identity=identity,diff --git a/hermes_cli/web_routers/webapp.py b/hermes_cli/web_routers/webapp.pyindex 6b95bb5a3b1..2369c1c80e8 100644--- a/hermes_cli/web_routers/webapp.py+++ b/hermes_cli/web_routers/webapp.py@@ -176,12 +176,13 @@ def _ticket_principal(request: Request) -> tuple[dict, str | None]:def mint_socket_ticket(identity: dict, socket: str, *, session_token: str | None = None,- sign_in: str | None = None) -> str:+ sign_in: str | None = None, profile_home: str | None = None) -> str:"""A one-use ticket that opens only *socket* (``web_session_sockets.GATEWAY_SOCKET``,``HOST_TERMINAL_SOCKET`` or one of ``AUDIO_SOCKETS``) as *identity*. Minted with*session_token*, or by a login whose sign-in binding was checked against the credential withdigest *sign_in* (``hermes_cli.webapp_sign_in``), it opens nothing once that credential is- replaced, and the socket it opens closes when the browser signs out."""+ replaced, and the socket it opens closes when the browser signs out. With *profile_home* the+ socket it opens answers for that profile (``chat_ws.gateway_ws``)."""from hermes_cli.dashboard_auth.ws_tickets import mint_ticketfrom hermes_cli.web_session_sockets import token_digest@@ -190,15 +191,19 @@ def mint_socket_ticket(identity: dict, socket: str, *, session_token: str | Noneextra["session_token"] = token_digest(session_token)if sign_in is not None:extra["sign_in"] = sign_in+ if profile_home is not None:+ extra["profile_home"] = profile_homereturn mint_ticket(user_id=identity["user_id"], provider=identity["provider"],issuer=identity.get("issuer", ""), extra=extra)-def _socket_ticket_response(request: Request, identity: dict, socket: str, session_token: str | None) -> JSONResponse:+def _socket_ticket_response(request: Request, identity: dict, socket: str, session_token: str | None,+ profile_home: str | None = None) -> JSONResponse:from hermes_cli.dashboard_auth.ws_tickets import TTL_SECONDSfrom hermes_cli.webapp_sign_in import sign_in_of- ticket = mint_socket_ticket(identity, socket, session_token=session_token, sign_in=sign_in_of(request))+ ticket = mint_socket_ticket(identity, socket, session_token=session_token, sign_in=sign_in_of(request),+ profile_home=profile_home)return JSONResponse({"ticket": ticket, "ttl_seconds": TTL_SECONDS}, headers={"Cache-Control": "no-store"})@@ -209,14 +214,16 @@ async def issue_gateway_ticket(request: Request, profile: str | None = None):(``web_server_chat._consume_ws_ticket``) as this caller's login. It opens no other socket.Minted locally: the server that serves this page runs the socket's sessions. *profile* isvalidated (400/404) so a stale tab learns its profile is gone here rather than from a socket- that keeps closing."""+ that keeps closing, and the ticket names it: the socket answers a request that names no profile+ for the tab's profile, as a native ticket does, never for the gateway's launch profile."""from hermes_cli.web_server_cron import _cron_profile_homeif not policy(request.app.state).gateway_ticket:raise HTTPException(404, "Webapp gateway tickets are unavailable on this surface")identity, session_token = _ticket_principal(request)- _cron_profile_home(profile)- return _socket_ticket_response(request, identity, GATEWAY_SOCKET, session_token)+ _name, home = _cron_profile_home(profile)+ return _socket_ticket_response(request, identity, GATEWAY_SOCKET, session_token,+ profile_home=str(home) if profile else None)@router.post("/api/webapp/terminal-ticket")diff --git a/hermes_cli/web_server_chat.py b/hermes_cli/web_server_chat.pyindex 60b81d640e7..982edf74bfe 100644--- a/hermes_cli/web_server_chat.py+++ b/hermes_cli/web_server_chat.py@@ -382,6 +382,8 @@ def _consume_ws_ticket(ws: WebSocket, reject, socket: Optional[str] = None, *,ws._hermes_auth_identity = {"user_id": info.get("user_id"), "provider": info.get("provider")}if info.get("issuer"):ws._hermes_auth_identity["issuer"] = info["issuer"]+ if info.get("profile_home"):+ ws._hermes_ticket_profile_home = info["profile_home"]if (admitted := admitted_with(info)) is not None:track(ws, admitted)if not protocol_ticket:diff --git a/tests/hermes_cli/test_webapp_gateway_ticket.py b/tests/hermes_cli/test_webapp_gateway_ticket.pyindex 5811ba01376..60752ad9796 100644--- a/tests/hermes_cli/test_webapp_gateway_ticket.py+++ b/tests/hermes_cli/test_webapp_gateway_ticket.py@@ -2,7 +2,8 @@``POST /api/webapp/gateway-ticket?profile=<name>`` hands the browser a one-use ticket for``/api/ws`` on the same origin (offered as the ``hermes-gateway-ticket.`` subprotocol). It names the-caller's login, never a pinned home, and the upgrade gate redeems it exactly once.+caller's login (and the profile it names, ``test_webapp_ticket_profile.py``), and the upgrade gate+redeems it exactly once."""from types import SimpleNamespacediff --git a/tests/hermes_cli/test_webapp_ticket_profile.py b/tests/hermes_cli/test_webapp_ticket_profile.pyindex 00c73ce6ea1..8394721a5c7 100644--- a/tests/hermes_cli/test_webapp_ticket_profile.py+++ b/tests/hermes_cli/test_webapp_ticket_profile.py@@ -32,10 +32,9 @@ def two_profiles(monkeypatch, tmp_path):monkeypatch.setenv("HERMES_HOME", str(launch))registry = SessionAuthorities(launch, multiplexed=True)runner = SimpleNamespace(_draining=False, session_authorities=registry)- authorities, dbs = {}, []+ authorities, dbs = {}, {}for name, home in (("default", launch), ("beta", beta)):- db = SessionDB(home / "state.db")- dbs.append(db)+ db = dbs[name] = SessionDB(home / "state.db")authorities[name] = SessionAuthority(runner, profile_id=str(home), instance_id="ticket-profile", db=db,epoch=begin_runtime_epoch(db, instance_id="ticket-profile"))registry.add(home, authorities[name], name=name)@@ -45,37 +44,46 @@ def two_profiles(monkeypatch, tmp_path):monkeypatch.setattr(server.app.state, "auth_required", False, raising=False)monkeypatch.setattr(server.app.state, "bound_host", "127.0.0.1", raising=False)monkeypatch.setattr(server, "_SESSION_TOKEN", _TOKEN)+ monkeypatch.setattr(server, "_DASHBOARD_EMBEDDED_CHAT_ENABLED", True)try:- yield TestClient(server.app, base_url="http://127.0.0.1"), launch, beta+ yield TestClient(server.app, base_url="http://127.0.0.1"), {"default": launch, "beta": beta}finally:- for db in dbs:+ for db in dbs.values():db.close()-def _answering_home(client, profile=None, request_profile=None):- """The profile home ``runtime.describe`` answers from on a tab socket opened for *profile*."""+def _ask(client, method, params, profile=None):+ """*method*'s reply on a tab socket opened for *profile* (``?profile=`` on the page)."""query = f"?profile={profile}" if profile else ""minted = client.post(f"/api/webapp/gateway-ticket{query}", headers={"X-Hermes-Session-Token": _TOKEN})assert minted.status_code == 200, minted.textticket = minted.json()["ticket"]socket_query = f"&profile={profile}" if profile else ""- params = {"profile": request_profile} if request_profile else {}- with client.websocket_connect(f"/api/ws?native_dial=browser&ticket={ticket}{socket_query}") as ws:- ws.send_json({"jsonrpc": "2.0", "id": "describe", "method": "runtime.describe", "params": params})+ # TestClient's WS default Host is "testserver", which the upgrade gate refuses.+ with client.websocket_connect(f"/api/ws?native_dial=browser&ticket={ticket}{socket_query}",+ headers={"host": "127.0.0.1"}) as ws:+ ws.send_json({"jsonrpc": "2.0", "id": "ask", "method": method, "params": params})while True:frame = ws.receive_json()- if frame.get("id") == "describe":- assert "result" in frame, frame- return Path(frame["result"]["profile_id"])+ if frame.get("id") == "ask":+ return frame+++def _answering_home(client, profile=None):+ reply = _ask(client, "runtime.describe", {}, profile)+ assert "result" in reply, reply+ return Path(reply["result"]["profile_id"])def test_a_tab_opened_on_a_profile_is_answered_for_it_and_keeps_its_host_scope(two_profiles):- client, launch, beta = two_profiles- assert _answering_home(client, profile="beta") == beta- # The ticket keeps the dashboard gate's host scope: naming the launch profile still reaches it.- assert _answering_home(client, profile="beta", request_profile="default") == launch+ client, homes = two_profiles+ assert _answering_home(client, profile="beta") == homes["beta"]+ # Still the dashboard gate's host scope: naming another served profile reaches it, where a+ # profile-bound grant would be refused with ``profile_mismatch``.+ reply = _ask(client, "session.active_list", {"profile": "default"}, profile="beta")+ assert reply.get("result") == {"sessions": []}, replydef test_a_tab_opened_without_a_profile_is_answered_for_the_launch_profile(two_profiles):- client, launch, _beta = two_profiles- assert _answering_home(client) == launch+ client, homes = two_profiles+ assert _answering_home(client) == homes["default"]