The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): /browser connect|disconnect stay off the shared owner's process-wide CDP
Teknium4478b4ec006b
diff --git a/tests/gateway/fixtures/browser_scope_peer.py b/tests/gateway/fixtures/browser_scope_peer.pynew file mode 100644index 00000000000..acf796fe5ec--- /dev/null+++ b/tests/gateway/fixtures/browser_scope_peer.py@@ -0,0 +1,70 @@+"""Authenticated WS fixture: browser.manage actions on the shared owner; no inference, no browser."""+import asyncio+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+import os+from pathlib import Path+import sys+import threading+import traceback+++class _Cdp(BaseHTTPRequestHandler):+ def do_GET(self): # /json/version: this operator's logged-in browser answers+ self.send_response(200)+ self.end_headers()+ self.wfile.write(b'{"webSocketDebuggerUrl": "ws://127.0.0.1/devtools/browser/x"}')++ def log_message(self, *args):+ pass+++async def probe():+ from gateway.run import GatewayRunner+ from gateway.session_authority import initialize_session_authority+ from gateway.run_api import start_gateway_api, stop_gateway_api+ from hermes_cli import web_server+ from hermes_cli.dashboard_auth.ws_tickets import mint_ticket+ from tests.gateway.fixtures.local_recovery_probe import rpc+ import tools.browser_tool_lifecycle as lifecycle+ from websockets.asyncio.client import connect++ home = Path(os.environ['HERMES_HOME'])+ (home / 'config.yaml').write_text('gateway:\n multiplex_profiles: false\nmodel:\n provider: custom\n default: no-inference\n base_url: http://127.0.0.1:1/v1\nauxiliary:\n title_generation:\n enabled: false\n')+ runner = GatewayRunner()+ await initialize_session_authority(runner, profile_id=str(home), instance_id='browser-scope')+ api = await start_gateway_api(runner)+ web_server.app.state.auth_required = True+ reaps = []+ lifecycle.cleanup_all_browsers = lambda: reaps.append(1) # every chat's browser would be closed here+ os.environ['BROWSER_CDP_URL'] = 'http://127.0.0.1:9333' # another chat is driving this browser+ receipt = {}+ cdp = ThreadingHTTPServer(('127.0.0.1', 0), _Cdp)+ threading.Thread(target=cdp.serve_forever, daemon=True).start()+ try:+ ticket = mint_ticket(user_id='owner', provider='fixture')+ async with connect(api.api_origin.replace('http:', 'ws:') + '/api/ws?ticket=' + ticket) as ws:+ sid = (await rpc(ws, 'session.create', request_id='browser', source='tui', toolsets=[]))['result']['session_id']+ for action, extra in [('connect', {'url': f'http://127.0.0.1:{cdp.server_port}'}),+ ('disconnect', {}), ('status', {}), (None, {})]:+ params = {'session_id': sid, **extra, **({'action': action} if action else {})}+ reply = await rpc(ws, 'browser.manage', **params)+ receipt[action or 'missing'] = {+ 'code': reply.get('error', {}).get('code'), 'result': reply.get('result'),+ 'cdp': os.environ.get('BROWSER_CDP_URL'), 'reaps': len(reaps)}+ finally:+ cdp.shutdown()+ await stop_gateway_api(api)+ (home / 'receipt.json').write_text(json.dumps(receipt))+++if __name__ == '__main__':+ status = 0+ try:+ asyncio.run(probe())+ except BaseException:+ traceback.print_exc()+ status = 1+ sys.stdout.flush()+ sys.stderr.flush()+ os._exit(status)diff --git a/tests/gateway/test_browser_manage_shared_owner.py b/tests/gateway/test_browser_manage_shared_owner.pynew file mode 100644index 00000000000..106b0b3e970--- /dev/null+++ b/tests/gateway/test_browser_manage_shared_owner.py@@ -0,0 +1,40 @@+"""/browser connect|disconnect from one TUI or Desktop chat never rewrites the shared owner's+process-wide CDP endpoint or reaps other chats' browsers (dokterdok N25); /browser status and+/browser use still answer. One row per browser.manage action reaching the legacy fallback."""+import json+from pathlib import Path+import subprocess+import sys++import pytest++from tests.gateway.fixtures.local_recovery_probe import child_env++_OTHER_CHAT = 'http://127.0.0.1:9333'++[email protected](scope='module')+def receipt(tmp_path_factory):+ root = Path(__file__).resolve().parents[2]+ tmp = tmp_path_factory.mktemp('browser-scope')+ home, user = tmp / 'state', tmp / 'user'+ home.mkdir()+ user.mkdir()+ env = child_env()+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ PYTHONUNBUFFERED='1')+ result = subprocess.run([sys.executable, str(root / 'tests/gateway/fixtures/browser_scope_peer.py')],+ cwd=root, env=env, capture_output=True, text=True, timeout=90, check=False)+ assert result.returncode == 0, result.stdout + result.stderr+ return json.loads((home / 'receipt.json').read_text())++[email protected]('action,refused', [+ ('connect', True), ('disconnect', True), ('status', False), ('missing', False)])+def test_browser_manage_on_the_shared_owner_keeps_process_wide_cdp(receipt, action, refused):+ row = receipt[action]+ assert row['cdp'] == _OTHER_CHAT and row['reaps'] == 0, row # nothing process-wide changed+ if refused:+ assert row['code'] == 4030 and row['result'] is None, row # refused in words, not -32601+ else:+ assert row['code'] is None and row['result']['url'] == _OTHER_CHAT, rowdiff --git a/tui_gateway/ws_legacy_fallback.py b/tui_gateway/ws_legacy_fallback.pyindex a98f3233a25..406dff16255 100644--- a/tui_gateway/ws_legacy_fallback.py+++ b/tui_gateway/ws_legacy_fallback.py@@ -42,6 +42,14 @@ _SESSION_FALLBACK_ALLOWED = frozenset({# = every chat's process commands. The owner serves the session-scoped ``process.stop`` itself# (``gateway/session_ancillary.py``); ``process.kill`` stays: its handler is already session-scoped._PROCESS_GLOBAL = frozenset({"process.stop", "delegation.pause", "reload.mcp", "reload.env", "agents.list"})+# Process-global ACTIONS of a verb whose other actions are fine on the shared owner (the gate above is+# method-level, and refusing the whole verb turns its safe actions into the client's -32601 version-skew+# notice). ``browser.manage`` connect/disconnect reap every task's browser and rewrite the process-wide+# ``BROWSER_CDP_URL`` that every chat's and served profile's browser tools read first (dokterdok N25);+# ``status`` and ``use`` (the profile's ``browser.backend``) stay. A missing action means ``status``.+_PROCESS_GLOBAL_ACTIONS = {"browser.manage": ({"connect", "disconnect"}, (+ "/browser connect and /browser disconnect would switch the browser for every chat on this shared "+ "gateway. Set browser.cdp_url in config.yaml instead, or use the classic CLI (hermes --cli)."))}def legacy_fallback_allowed(actor: Any, method: str) -> bool:@@ -73,6 +81,9 @@ def _foreign_profile_home(server: Any, profile_id: Any) -> str | None:def dispatch_legacy(server: Any, req: dict, transport: Any, actor: Any) -> dict | None:"""Run ``server.dispatch`` with the ticket's profile home bound (call from a worker thread;the pool path copies this context, so long handlers see it too)."""+ actions, refusal = _PROCESS_GLOBAL_ACTIONS.get(req.get("method"), ((), ""))+ if (req.get("params") or {}).get("action", "status") in actions:+ return {"jsonrpc": "2.0", "id": req.get("id"), "error": {"code": 4030, "message": refusal}}token = _connection_profile_home.set(_foreign_profile_home(server, getattr(actor, "profile_id", None)))try:return server.dispatch(req, transport)