Skip to content

The agent that grows with you

fix(gateway): /browser connect and disconnect run in the session's profile

Teknium084d1189a94c
diff --git a/hermes_cli/cli_browser_gateway.py b/hermes_cli/cli_browser_gateway.py
index 0ec7adfa51b..1f0f4ed4a2a 100644
--- a/hermes_cli/cli_browser_gateway.py
+++ b/hermes_cli/cli_browser_gateway.py
@@ -8,10 +8,6 @@ from urllib.parse import urlparse
from hermes_cli.browser_connect import DEFAULT_BROWSER_CDP_URL
from hermes_cli.cli_commands_session_tools import _say_block, _t
-# The gateway's bounded refusal codes for browser.manage -> this CLI's catalog text (the client
-# sanitizes the owner's prose, so the code is what crosses the wire).
-_REFUSALS = {"browser_profile_shared": "browser.profile_shared"}
-
def _gateway_is_remote() -> bool:
"""True when this CLI attaches to an explicitly named gateway WebSocket that is not loopback
@@ -27,8 +23,8 @@ def gateway_browser(cli, connection, word: str, rest: str) -> None:
"""``/browser`` on the shared gateway (#134889 CLI-9): ``browser.manage``, the verb Ink and
Desktop send. The browser tools run in the gateway, so changing this process's
``BROWSER_CDP_URL`` would change nothing the agent uses. ``connect``/``disconnect`` manage a
- browser on the gateway HOST: only against a local gateway (Desktop's rule). The gateway refuses
- them by name when it serves several profiles."""
+ browser on the gateway HOST: only against a local gateway (Desktop's rule). The gateway scopes
+ them to this session's profile."""
from hermes_cli.gateway_client import GatewayClientError
if word in {"connect", "disconnect"} and _gateway_is_remote():
return _say_block(_t("browser.remote_gateway"))
@@ -49,8 +45,7 @@ def gateway_browser(cli, connection, word: str, rest: str) -> None:
try:
result = connection.call("browser.manage", **params) or {}
except GatewayClientError as exc:
- key = _REFUSALS.get(str(exc))
- return _say_block(f" ⚠ {_t(key) if key else exc}")
+ return _say_block(f" ⚠ {exc}")
for message in result.get("messages") or ():
print(f" {message}")
if word == "use":
diff --git a/locales/af.yaml b/locales/af.yaml
index 163fa1caa2c..65e020d215a 100644
--- a/locales/af.yaml
+++ b/locales/af.yaml
@@ -3010,7 +3010,6 @@ cli:
usage_status: "status Wys die huidige blaaiermodus"
usage_use: "use [off] Skakel oor na Browser Use-modus (CLI 3.0) / terug na ingeboude gereedskap"
remote_gateway: "/browser connect en /browser disconnect bestuur 'n Chromium-blaaier op die gateway-gasheer — slegs beskikbaar wanneer aan 'n plaaslike gateway gekoppel."
- profile_shared: "/browser connect en /browser disconnect is nie beskikbaar op 'n gateway wat verskeie profiele bedien nie: die lewendige blaaierverbinding sou deur elke profiel se kletse gedeel word. Stel eerder browser.cdp_url in hierdie profiel se config.yaml."
checking: "Kontroleer Chromium-blaaier se afstandontfouting by {url}..."
new_sessions_only: "Geld vir nuwe sessies — hierdie een behou sy huidige gereedskap (/new om een te begin)."
status_gateway_default: "🌐 Blaaier: die gateway se verstek-blaaier (geen lewendige CDP-verbinding nie)"
diff --git a/locales/ar.yaml b/locales/ar.yaml
index 8c5d039bf45..fb47bac2849 100644
--- a/locales/ar.yaml
+++ b/locales/ar.yaml
@@ -3010,7 +3010,6 @@ cli:
usage_status: "status عرض وضع المتصفح الحالي"
usage_use: "use [off] التبديل إلى وضع Browser Use (CLI 3.0) / الرجوع إلى الأدوات المضمّنة"
remote_gateway: "‏/browser connect و /browser disconnect يديران متصفحًا من عائلة Chromium على مضيف البوابة — متاح فقط عند الاتصال ببوابة محلية."
- profile_shared: "‏/browser connect و /browser disconnect غير متاحين على بوابة تخدم عدة ملفات تعريف: سيُشارَك اتصال المتصفح المباشر بين محادثات كل ملف تعريف. اضبط browser.cdp_url في config.yaml لهذا الملف بدلًا من ذلك."
checking: "جارٍ التحقق من التصحيح عن بُعد لمتصفح Chromium على {url}..."
new_sessions_only: "ينطبق على الجلسات الجديدة — تحتفظ هذه الجلسة بأدواتها الحالية (‏/new لبدء جلسة)."
status_gateway_default: "🌐 المتصفح: الواجهة الافتراضية لمتصفح البوابة (لا يوجد اتصال CDP مباشر)"
diff --git a/locales/de.yaml b/locales/de.yaml
index 7907eb2c7bd..79e13ad9bf6 100644
--- a/locales/de.yaml
+++ b/locales/de.yaml
@@ -3010,7 +3010,6 @@ cli:
usage_status: "status Aktuellen Browser-Modus anzeigen"
usage_use: "use [off] In den Browser-Use-Modus (CLI 3.0) wechseln / zurück zu den integrierten Tools"
remote_gateway: "/browser connect und /browser disconnect verwalten einen Chromium-Browser auf dem Gateway-Host — nur mit einem lokalen Gateway verfügbar."
- profile_shared: "/browser connect und /browser disconnect sind auf einem Gateway, das mehrere Profile bedient, nicht verfügbar: Die Live-Browserverbindung würde von den Chats aller Profile geteilt. Setze stattdessen browser.cdp_url in der config.yaml dieses Profils."
checking: "Prüfe Remote-Debugging des Chromium-Browsers unter {url}..."
new_sessions_only: "Gilt für neue Sitzungen — diese behält ihre aktuellen Tools (/new startet eine neue)."
status_gateway_default: "🌐 Browser: Standard-Browser-Backend des Gateways (keine Live-CDP-Verbindung)"
diff --git a/locales/en.yaml b/locales/en.yaml
index b9eba55d279..3a3c6e7e680 100644
--- a/locales/en.yaml
+++ b/locales/en.yaml
@@ -3110,7 +3110,6 @@ cli:
usage_status: "status Show current browser mode"
usage_use: "use [off] Switch to Browser Use mode (CLI 3.0) / back to built-in tools"
remote_gateway: "/browser connect and /browser disconnect manage a Chromium-family browser on the gateway host — only available when connected to a local gateway."
- profile_shared: "/browser connect and /browser disconnect are unavailable on a gateway that serves several profiles: the live browser connection would be shared by every profile's chats. Set browser.cdp_url in this profile's config.yaml instead."
checking: "Checking Chromium-family browser remote debugging at {url}..."
new_sessions_only: "Applies to new sessions — this one keeps its current tools (/new to start one)."
status_gateway_default: "🌐 Browser: the gateway's default browser backend (no live CDP connection)"
diff --git a/locales/es.yaml b/locales/es.yaml
index e985a8a8ca7..4b6e63cd09b 100644
--- a/locales/es.yaml
+++ b/locales/es.yaml
@@ -3010,7 +3010,6 @@ cli:
usage_status: "status Mostrar el modo de navegador actual"
usage_use: "use [off] Cambiar al modo Browser Use (CLI 3.0) / volver a las herramientas integradas"
remote_gateway: "/browser connect y /browser disconnect gestionan un navegador Chromium en el host del gateway — solo disponible con un gateway local."
- profile_shared: "/browser connect y /browser disconnect no están disponibles en un gateway que sirve varios perfiles: la conexión del navegador se compartiría entre los chats de todos los perfiles. Configura browser.cdp_url en el config.yaml de este perfil."
checking: "Comprobando la depuración remota del navegador Chromium en {url}..."
new_sessions_only: "Se aplica a sesiones nuevas — esta conserva sus herramientas actuales (/new para iniciar una)."
status_gateway_default: "🌐 Navegador: backend de navegador predeterminado del gateway (sin conexión CDP en vivo)"
diff --git a/locales/fr.yaml b/locales/fr.yaml
index 58941e75973..7775ab10b11 100644
--- a/locales/fr.yaml
+++ b/locales/fr.yaml
@@ -3315,7 +3315,6 @@ cli:
usage_status: "status Afficher le mode de navigateur actuel"
usage_use: "use [off] Passer en mode Browser Use (CLI 3.0) / revenir aux outils intégrés"
remote_gateway: "/browser connect et /browser disconnect gèrent un navigateur Chromium sur l'hôte de la passerelle — disponible uniquement avec une passerelle locale."
- profile_shared: "/browser connect et /browser disconnect ne sont pas disponibles sur une passerelle qui sert plusieurs profils : la connexion au navigateur serait partagée par les discussions de tous les profils. Définissez plutôt browser.cdp_url dans le config.yaml de ce profil."
checking: "Vérification du débogage distant du navigateur Chromium à {url}..."
new_sessions_only: "S'applique aux nouvelles sessions — celle-ci garde ses outils actuels (/new pour en démarrer une)."
status_gateway_default: "🌐 Navigateur : backend de navigateur par défaut de la passerelle (pas de connexion CDP en direct)"
diff --git a/locales/ga.yaml b/locales/ga.yaml
index a32d9f15fc0..4aae78d7e02 100644
--- a/locales/ga.yaml
+++ b/locales/ga.yaml
@@ -3010,7 +3010,6 @@ cli:
usage_status: "status Taispeáin mód reatha an bhrabhsálaí"
usage_use: "use [off] Athraigh go mód Browser Use (CLI 3.0) / ar ais go huirlisí ionsuite"
remote_gateway: "Bainistíonn /browser connect agus /browser disconnect brabhsálaí Chromium ar óstach an gheata — ar fáil ach amháin le geata áitiúil."
- profile_shared: "Níl /browser connect ná /browser disconnect ar fáil ar gheata a fhreastalaíonn ar roinnt próifílí: roinnfí an nasc beo brabhsálaí idir comhráite gach próifíle. Socraigh browser.cdp_url i config.yaml na próifíle seo ina ionad."
checking: "Ag seiceáil dífhabhtú cianda an bhrabhsálaí Chromium ag {url}..."
new_sessions_only: "Baineann sé le seisiúin nua — coinníonn an ceann seo a uirlisí reatha (/new chun ceann a thosú)."
status_gateway_default: "🌐 Brabhsálaí: inneall réamhshocraithe brabhsálaí an gheata (gan nasc beo CDP)"
diff --git a/locales/hu.yaml b/locales/hu.yaml
index a40ceece7d7..b9905c09579 100644
--- a/locales/hu.yaml
+++ b/locales/hu.yaml
@@ -3027,7 +3027,6 @@ cli:
usage_status: "status Jelenlegi böngészőmód megjelenítése"
usage_use: "use [off] Átváltás Browser Use módra (CLI 3.0) / vissza a beépített eszközökre"
remote_gateway: "A /browser connect és /browser disconnect egy Chromium böngészőt kezel az átjáró gépén — csak helyi átjáróval érhető el."
- profile_shared: "A /browser connect és /browser disconnect nem érhető el több profilt kiszolgáló átjárón: az élő böngészőkapcsolaton minden profil csevegései osztoznának. Inkább állítsd be a browser.cdp_url értéket ennek a profilnak a config.yaml fájljában."
checking: "A Chromium böngésző távoli hibakeresésének ellenőrzése: {url}..."
new_sessions_only: "Új munkamenetekre vonatkozik — ez megtartja a jelenlegi eszközeit (/new újat indít)."
status_gateway_default: "🌐 Böngésző: az átjáró alapértelmezett böngésző-háttere (nincs élő CDP-kapcsolat)"
diff --git a/locales/it.yaml b/locales/it.yaml
index 2d421786023..3b43d108c82 100644
--- a/locales/it.yaml
+++ b/locales/it.yaml
@@ -3010,7 +3010,6 @@ cli:
usage_status: "status Mostra la modalità browser attuale"
usage_use: "use [off] Passa alla modalità Browser Use (CLI 3.0) / torna agli strumenti integrati"
remote_gateway: "/browser connect e /browser disconnect gestiscono un browser Chromium sull'host del gateway — disponibile solo con un gateway locale."
- profile_shared: "/browser connect e /browser disconnect non sono disponibili su un gateway che serve più profili: la connessione al browser sarebbe condivisa dalle chat di ogni profilo. Imposta invece browser.cdp_url nel config.yaml di questo profilo."
checking: "Verifica del debug remoto del browser Chromium su {url}..."
new_sessions_only: "Si applica alle nuove sessioni — questa mantiene gli strumenti attuali (/new per avviarne una)."
status_gateway_default: "🌐 Browser: backend browser predefinito del gateway (nessuna connessione CDP attiva)"
diff --git a/locales/ja.yaml b/locales/ja.yaml
index f1afe8eaf31..ed72db7b3db 100644
--- a/locales/ja.yaml
+++ b/locales/ja.yaml
@@ -3010,7 +3010,6 @@ cli:
usage_status: "status 現在のブラウザモードを表示します"
usage_use: "use [off] Browser Use モード (CLI 3.0) に切り替え / 組み込みツールに戻します"
remote_gateway: "/browser connect と /browser disconnect はゲートウェイホスト上の Chromium 系ブラウザーを管理します — ローカルゲートウェイ接続時のみ利用できます。"
- profile_shared: "複数のプロファイルを提供するゲートウェイでは /browser connect と /browser disconnect は使用できません。ライブのブラウザー接続がすべてのプロファイルのチャットで共有されるためです。代わりにこのプロファイルの config.yaml で browser.cdp_url を設定してください。"
checking: "{url} で Chromium 系ブラウザーのリモートデバッグを確認しています..."
new_sessions_only: "新しいセッションに適用されます — このセッションは現在のツールを維持します(/new で開始)。"
status_gateway_default: "🌐 ブラウザー: ゲートウェイの既定ブラウザーバックエンド(ライブ CDP 接続なし)"
diff --git a/locales/ko.yaml b/locales/ko.yaml
index e673e6ac26f..2aaad1977b4 100644
--- a/locales/ko.yaml
+++ b/locales/ko.yaml
@@ -3010,7 +3010,6 @@ cli:
usage_status: "status 현재 브라우저 모드 표시"
usage_use: "use [off] Browser Use 모드(CLI 3.0)로 전환 / 내장 도구로 복귀"
remote_gateway: "/browser connect 및 /browser disconnect는 게이트웨이 호스트의 Chromium 계열 브라우저를 관리합니다 — 로컬 게이트웨이에 연결된 경우에만 사용할 수 있습니다."
- profile_shared: "여러 프로필을 제공하는 게이트웨이에서는 /browser connect 및 /browser disconnect를 사용할 수 없습니다. 실시간 브라우저 연결이 모든 프로필의 채팅에서 공유되기 때문입니다. 대신 이 프로필의 config.yaml에 browser.cdp_url을 설정하세요."
checking: "{url}에서 Chromium 계열 브라우저 원격 디버깅을 확인하는 중..."
new_sessions_only: "새 세션에 적용됩니다 — 이 세션은 현재 도구를 유지합니다 (/new로 새로 시작)."
status_gateway_default: "🌐 브라우저: 게이트웨이 기본 브라우저 백엔드 (실시간 CDP 연결 없음)"
diff --git a/locales/pt.yaml b/locales/pt.yaml
index ee69ac1b6ee..f50e29e3c65 100644
--- a/locales/pt.yaml
+++ b/locales/pt.yaml
@@ -3010,7 +3010,6 @@ cli:
usage_status: "status Mostra o modo atual do navegador"
usage_use: "use [off] Muda para o modo Browser Use (CLI 3.0) / volta às ferramentas integradas"
remote_gateway: "/browser connect e /browser disconnect gerenciam um navegador Chromium no host do gateway — disponível apenas com um gateway local."
- profile_shared: "/browser connect e /browser disconnect não estão disponíveis em um gateway que atende vários perfis: a conexão do navegador seria compartilhada pelos chats de todos os perfis. Defina browser.cdp_url no config.yaml deste perfil."
checking: "Verificando a depuração remota do navegador Chromium em {url}..."
new_sessions_only: "Aplica-se a novas sessões — esta mantém as ferramentas atuais (/new para iniciar uma)."
status_gateway_default: "🌐 Navegador: backend de navegador padrão do gateway (sem conexão CDP ao vivo)"
diff --git a/locales/ru.yaml b/locales/ru.yaml
index b331d97d0ca..743a2f4b7db 100644
--- a/locales/ru.yaml
+++ b/locales/ru.yaml
@@ -3010,7 +3010,6 @@ cli:
usage_status: "status Показать текущий режим браузера"
usage_use: "use [off] Переключиться в режим Browser Use (CLI 3.0) / обратно к встроенным инструментам"
remote_gateway: "/browser connect и /browser disconnect управляют браузером Chromium на хосте шлюза — доступно только при подключении к локальному шлюзу."
- profile_shared: "/browser connect и /browser disconnect недоступны на шлюзе, обслуживающем несколько профилей: живое подключение к браузеру стало бы общим для чатов всех профилей. Вместо этого задайте browser.cdp_url в config.yaml этого профиля."
checking: "Проверка удалённой отладки браузера Chromium по адресу {url}..."
new_sessions_only: "Применяется к новым сеансам — этот сохраняет текущие инструменты (/new, чтобы начать новый)."
status_gateway_default: "🌐 Браузер: стандартный браузер шлюза (нет активного CDP-подключения)"
diff --git a/locales/tr.yaml b/locales/tr.yaml
index d3070c62b92..71e5c870832 100644
--- a/locales/tr.yaml
+++ b/locales/tr.yaml
@@ -3010,7 +3010,6 @@ cli:
usage_status: "status Geçerli tarayıcı modunu gösterir"
usage_use: "use [off] Browser Use moduna (CLI 3.0) geçer / yerleşik araçlara döner"
remote_gateway: "/browser connect ve /browser disconnect ağ geçidi ana makinesindeki bir Chromium tarayıcısını yönetir — yalnızca yerel ağ geçidine bağlıyken kullanılabilir."
- profile_shared: "/browser connect ve /browser disconnect birden çok profile hizmet veren bir ağ geçidinde kullanılamaz: canlı tarayıcı bağlantısı tüm profillerin sohbetleri tarafından paylaşılır. Bunun yerine bu profilin config.yaml dosyasında browser.cdp_url ayarlayın."
checking: "{url} adresinde Chromium tarayıcısı uzaktan hata ayıklaması denetleniyor..."
new_sessions_only: "Yeni oturumlara uygulanır — bu oturum mevcut araçlarını korur (/new ile yeni başlatın)."
status_gateway_default: "🌐 Tarayıcı: ağ geçidinin varsayılan tarayıcı arka ucu (canlı CDP bağlantısı yok)"
diff --git a/locales/uk.yaml b/locales/uk.yaml
index 84f4435e9bd..93af9de3b88 100644
--- a/locales/uk.yaml
+++ b/locales/uk.yaml
@@ -3010,7 +3010,6 @@ cli:
usage_status: "status Показати поточний режим браузера"
usage_use: "use [off] Перемкнутися в режим Browser Use (CLI 3.0) / назад до вбудованих інструментів"
remote_gateway: "/browser connect і /browser disconnect керують браузером Chromium на хості шлюзу — доступно лише з локальним шлюзом."
- profile_shared: "/browser connect і /browser disconnect недоступні на шлюзі, що обслуговує кілька профілів: живе з'єднання з браузером стало б спільним для чатів усіх профілів. Натомість задайте browser.cdp_url у config.yaml цього профілю."
checking: "Перевірка віддаленого налагодження браузера Chromium за адресою {url}..."
new_sessions_only: "Застосовується до нових сеансів — цей зберігає поточні інструменти (/new, щоб почати новий)."
status_gateway_default: "🌐 Браузер: типовий браузер шлюзу (немає активного CDP-з'єднання)"
diff --git a/locales/zh-hant.yaml b/locales/zh-hant.yaml
index 356ac0d0bb0..90b6e88cfb1 100644
--- a/locales/zh-hant.yaml
+++ b/locales/zh-hant.yaml
@@ -3010,7 +3010,6 @@ cli:
usage_status: "status 顯示目前的瀏覽器模式"
usage_use: "use [off] 切換至 Browser Use 模式(CLI 3.0)/切回內建工具"
remote_gateway: "/browser connect 與 /browser disconnect 管理閘道主機上的 Chromium 系瀏覽器 — 僅在連線至本機閘道時可用。"
- profile_shared: "在服務多個設定檔的閘道上無法使用 /browser connect 與 /browser disconnect:即時瀏覽器連線會由所有設定檔的對話共用。請改為在此設定檔的 config.yaml 中設定 browser.cdp_url。"
checking: "正在檢查 {url} 的 Chromium 系瀏覽器遠端偵錯..."
new_sessions_only: "套用於新工作階段 — 此工作階段保留目前工具(/new 開始新的)。"
status_gateway_default: "🌐 瀏覽器:閘道的預設瀏覽器後端(無即時 CDP 連線)"
diff --git a/locales/zh.yaml b/locales/zh.yaml
index d2665e95e22..3ef33a65d88 100644
--- a/locales/zh.yaml
+++ b/locales/zh.yaml
@@ -3010,7 +3010,6 @@ cli:
usage_status: "status 显示当前浏览器模式"
usage_use: "use [off] 切换到 Browser Use 模式(CLI 3.0)/ 切回内置工具"
remote_gateway: "/browser connect 和 /browser disconnect 管理网关主机上的 Chromium 系浏览器 — 仅在连接到本地网关时可用。"
- profile_shared: "在服务多个配置文件的网关上无法使用 /browser connect 和 /browser disconnect:实时浏览器连接会被所有配置文件的对话共享。请改为在此配置文件的 config.yaml 中设置 browser.cdp_url。"
checking: "正在检查 {url} 的 Chromium 系浏览器远程调试..."
new_sessions_only: "应用于新会话 — 此会话保留当前工具(/new 开始新的)。"
status_gateway_default: "🌐 浏览器:网关的默认浏览器后端(无实时 CDP 连接)"
diff --git a/tests/gateway/fixtures/browser_scope_peer.py b/tests/gateway/fixtures/browser_scope_peer.py
index a9c712472e2..85c00f8ded8 100644
--- a/tests/gateway/fixtures/browser_scope_peer.py
+++ b/tests/gateway/fixtures/browser_scope_peer.py
@@ -1,4 +1,5 @@
-"""Authenticated WS fixture: browser.manage actions on the shared owner; no inference, no browser."""
+"""Authenticated WS fixture: browser.manage actions on the shared owner, scoped to the session's
+profile (CLI-9); no inference, no browser."""
import asyncio
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
@@ -36,34 +37,46 @@ async def probe():
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 = {}
+ lifecycle.cleanup_profile_browsers = reaps.append # only this profile's browsers are closed here
+ lifecycle.cleanup_all_browsers = lambda: reaps.append('ALL') # every profile's would be
+ os.environ['BROWSER_CDP_URL'] = 'http://127.0.0.1:9333' # the operator's env endpoint
+ bee = home / 'profiles' / 'bee'
+ bee.mkdir(parents=True)
+ (bee / 'config.yaml').write_text('browser:\n cdp_url: ws://bee.invalid/devtools/browser/PROFILE-B\n')
+ from gateway.run import _profile_runtime_scope
+ from hermes_constants import hermes_home_key
+ from tools import browser_tool_cdp
+
+ def resolved(profile):
+ with _profile_runtime_scope(profile, hydrate_secrets=False):
+ return browser_tool_cdp._get_cdp_override_raw()
+ receipt = {'home_key': hermes_home_key(home)}
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']
- # CLI-9: phase 1 serves ONE profile (its chats are all this profile's), phase 2 TWO.
+ # CLI-9: phase 1 serves ONE profile, phase 2 TWO (bee already holds its own live connection).
real = runner.session_authorities if hasattr(runner, 'session_authorities') else None
for phase, serving in (('one', None), ('two', 2)):
if serving:
import types
- other = types.SimpleNamespace(profile_id=str(home / 'profiles' / 'bee'), retiring=False)
+ other = types.SimpleNamespace(profile_id=str(bee), retiring=False)
runner.session_authorities = types.SimpleNamespace(
- serving=lambda: [runner.session_authority, other])
- os.environ['BROWSER_CDP_URL'] = 'http://127.0.0.1:9333' # another chat is driving this browser
+ serving=lambda: [runner.session_authority, other], multiplexed=True)
+ with _profile_runtime_scope(bee, hydrate_secrets=False):
+ browser_tool_cdp.set_live_cdp_override('http://127.0.0.1:9444')
reaps.clear()
for action, extra in [('connect', {'url': f'http://127.0.0.1:{cdp.server_port}'}),
- ('disconnect', {}), ('status', {}), (None, {})]:
+ ('status', {}), ('disconnect', {}), (None, {})]:
params = {'session_id': sid, **extra, **({'action': action} if action else {})}
reply = await rpc(ws, 'browser.manage', **params)
receipt[f"{phase}:{action or 'missing'}"] = {
'code': reply.get('error', {}).get('code'), 'result': reply.get('result'),
- 'message': reply.get('error', {}).get('message'),
- 'cdp': os.environ.get('BROWSER_CDP_URL'), 'reaps': len(reaps),
- 'cdp_port': cdp.server_port}
+ 'env': os.environ.get('BROWSER_CDP_URL'), 'reaps': list(reaps),
+ 'own': browser_tool_cdp._live_overrides.get(receipt['home_key']),
+ 'bee': resolved(bee), 'cdp_port': cdp.server_port}
runner.session_authorities = real
finally:
cdp.shutdown()
diff --git a/tests/gateway/test_browser_manage_shared_owner.py b/tests/gateway/test_browser_manage_shared_owner.py
index 8b1e11ca910..48ce5814800 100644
--- a/tests/gateway/test_browser_manage_shared_owner.py
+++ b/tests/gateway/test_browser_manage_shared_owner.py
@@ -1,8 +1,8 @@
"""/browser connect|disconnect through the real WS legacy fallback (dokterdok N25, #134889 CLI-9).
-An owner serving ONE profile runs them: every chat on it is that profile's, and Ink, Desktop and the
-classic CLI all send /browser here. An owner serving SEVERAL profiles refuses them by name, so a
-browser one profile connects never reaches another profile's sessions; status still answers."""
+Ink, Desktop and the classic CLI all send /browser here. On an owner serving one profile or several,
+connect/disconnect run in the session's profile: the live endpoint and the browser reap are that
+profile's, so a browser one profile connects never reaches another profile's sessions."""
import json
from pathlib import Path
import subprocess
@@ -12,8 +12,6 @@ import pytest
from tests.gateway.fixtures.local_recovery_probe import child_env
-_OTHER_CHAT = 'http://127.0.0.1:9333'
-
@pytest.fixture(scope='module')
def receipt(tmp_path_factory):
@@ -31,21 +29,22 @@ def receipt(tmp_path_factory):
return json.loads((home / 'receipt.json').read_text())
[email protected]('action', ['connect', 'disconnect', 'status', 'missing'])
-def test_several_served_profiles_keep_the_process_wide_cdp(receipt, action):
- row = receipt['two:' + action]
- assert row['cdp'] == _OTHER_CHAT and row['reaps'] == 0, row # nothing process-wide changed
- if action in ('connect', 'disconnect'):
- assert row['code'] == 4030 and row['result'] is None, row # refused in words, not -32601
- assert 'several profiles' in row['message'], row
- else:
- assert row['code'] is None and row['result']['url'] == _OTHER_CHAT, row
-
-
-def test_one_served_profile_connects_and_disconnects_the_gateways_browser(receipt):
- connect = receipt['one:connect']
- assert connect['code'] is None and connect['result']['connected'] is True, connect
- assert connect['cdp'] == f"http://127.0.0.1:{connect['cdp_port']}" and connect['reaps'] > 0, connect
- disconnect = receipt['one:disconnect']
- assert disconnect['code'] is None and disconnect['cdp'] is None, disconnect
- assert receipt['one:status']['result']['connected'] is False
[email protected]('phase', ['one', 'two'])
+def test_connect_and_disconnect_are_the_sessions_profiles_alone(receipt, phase):
+ """One served profile or several: connect publishes THIS profile's endpoint and reaps only its
+ browsers; the operator's env endpoint and the other profile's own live connection stay."""
+ url, key = f"http://127.0.0.1:{receipt['one:connect']['cdp_port']}", receipt['home_key']
+ # The other profile keeps its own live connection, or the operator's env (which outranks its
+ # browser.cdp_url, as before); never this profile's.
+ bee = 'http://127.0.0.1:9444' if phase == 'two' else 'http://127.0.0.1:9333'
+ connect = receipt[f'{phase}:connect']
+ assert connect['code'] is None and connect['result'] == {'connected': True, 'url': url}, connect
+ assert connect['own'] == url and connect['reaps'] == [key, key], connect # never 'ALL'
+ assert connect['env'] == 'http://127.0.0.1:9333' and connect['bee'] == bee, connect
+ assert receipt[f'{phase}:status']['result']['url'] == url
+ disconnect = receipt[f'{phase}:disconnect']
+ assert disconnect['code'] is None and disconnect['result'] == {'connected': False}, disconnect
+ assert disconnect['own'] is None and disconnect['reaps'] == [key] * 4, disconnect
+ assert disconnect['env'] == 'http://127.0.0.1:9333' and disconnect['bee'] == bee, disconnect
+ # Back on the operator's env endpoint (a missing action means status).
+ assert receipt[f'{phase}:missing']['result']['url'] == 'http://127.0.0.1:9333'
diff --git a/tests/hermes_cli/test_classic_browser_manage.py b/tests/hermes_cli/test_classic_browser_manage.py
index 6131b051ecc..487b4053522 100644
--- a/tests/hermes_cli/test_classic_browser_manage.py
+++ b/tests/hermes_cli/test_classic_browser_manage.py
@@ -2,8 +2,8 @@
Browser tools run in the gateway, so a ``/browser connect`` that only rewrites the CLI process's
``BROWSER_CDP_URL`` changes nothing the agent uses. ``connect``/``disconnect`` follow Desktop's rule
-(local gateway only); on a gateway serving several profiles they are refused by name, because the
-live CDP endpoint is process-wide and must never reach another profile's sessions.
+(local gateway only) and are scoped to the session's profile on every gateway: on a multiplexed
+gateway one profile's live browser never reaches another profile's sessions.
"""
import threading
import types
@@ -83,23 +83,6 @@ def test_classic_browser_connect_against_a_remote_gateway_is_refused(gateway_cli
assert _browser_calls(conn) == [{"action": "status", "session_id": "local-s"}]
-def test_classic_browser_shows_the_gateways_named_refusal(gateway_cli, monkeypatch, capsys):
- """Review #141357 F5: the real client sanitizes the owner's prose to a bounded code, so the
- refusal crosses as ``data.reason`` and the CLI prints its own catalog text, not request_failed."""
- from hermes_cli.gateway_client import rpc_error
- from tui_gateway.ws_legacy_fallback import _PROCESS_GLOBAL_ACTIONS
- monkeypatch.delenv("HERMES_TUI_GATEWAY_URL", raising=False)
- _actions, reason, prose = _PROCESS_GLOBAL_ACTIONS["browser.manage"]
-
- def refuse(params):
- raise rpc_error({"code": 4030, "message": prose, "data": {"reason": reason}})
- cli, _conn = gateway_cli(**{"browser.manage": refuse})
- cli.process_command("/browser disconnect")
- out = capsys.readouterr().out
- assert "request_failed" not in out and "browser_profile_shared" not in out, out
- assert "several profiles" in out and "browser.cdp_url" in out, out
-
-
# --- the gateway side: browser.manage on a multiplexed owner -------------------------------------
class _Cdp(BaseHTTPRequestHandler):
@@ -122,8 +105,11 @@ def homes(tmp_path, monkeypatch):
monkeypatch.setattr(server, "_hermes_home", launch)
monkeypatch.delenv("BROWSER_CDP_URL", raising=False)
import tools.browser_tool_lifecycle as lifecycle
+ from tools import browser_tool_cdp
+ monkeypatch.setattr(browser_tool_cdp, "_live_overrides", {})
reaps = []
- monkeypatch.setattr(lifecycle, "cleanup_all_browsers", lambda: reaps.append(1))
+ monkeypatch.setattr(lifecycle, "cleanup_profile_browsers", reaps.append)
+ monkeypatch.setattr(lifecycle, "cleanup_all_browsers", lambda: reaps.append("ALL"))
cdp = ThreadingHTTPServer(("127.0.0.1", 0), _Cdp)
threading.Thread(target=cdp.serve_forever, daemon=True).start()
yield server, launch, bee, f"http://127.0.0.1:{cdp.server_port}", reaps
@@ -148,56 +134,71 @@ def _call(server, profile_id, params):
return reply if reply is not None else (done.wait(10) and written[0])
+def _registry(launch, *homes):
+ from gateway.session_authorities import SessionAuthorities
+ registry = SessionAuthorities(launch, multiplexed=True)
+ for home in (launch, *homes):
+ registry.add(home, types.SimpleNamespace(profile_id=str(home), retiring=False), name=home.name)
+ return registry
+
+
+def _resolved(home):
+ from gateway.run import _profile_runtime_scope
+ from tools.browser_tool_cdp import _get_cdp_override_raw
+ with _profile_runtime_scope(home, hydrate_secrets=False):
+ return _get_cdp_override_raw()
+
+
def test_a_browser_one_profile_connects_never_reaches_another_profiles_session(homes, monkeypatch):
- """Multiplexed owner: connect/disconnect from ANY profile are refused by name, so the
- process-wide CDP endpoint never changes under another profile's sessions; status still answers."""
+ """CLI-9 (a, c): a multiplexed owner serving A (launch) and B. Connect from A is A's alone: A's
+ browser tools resolve A's URL, B keeps its own browser.cdp_url, only A's browsers are reaped, and
+ disconnect from A leaves B's own live connection standing."""
import os
from gateway import run_api
+ from hermes_constants import hermes_home_key
server, launch, bee, url, reaps = homes
- monkeypatch.setattr(run_api, "_ACTIVE_RUNNER", _runner_serving("default", "bee"))
- for home in (launch, bee):
- for action in ("connect", "disconnect"):
- reply = _call(server, home, {"action": action, "url": url})
- assert reply["error"]["code"] == 4030, reply
- assert "profile" in reply["error"]["message"], reply
- assert "BROWSER_CDP_URL" not in os.environ and reaps == []
- status = _call(server, bee, {"action": "status"})
- assert status["result"]["connected"] is False, status
+ (bee / "config.yaml").write_text("browser:\n cdp_url: ws://bee.invalid/devtools/browser/PROFILE-B\n")
+ monkeypatch.setattr(run_api, "_ACTIVE_RUNNER", types.SimpleNamespace(session_authorities=_registry(launch, bee)))
+ reply = _call(server, launch, {"action": "connect", "url": url})
+ assert reply["result"] == {"connected": True, "url": url}, reply
+ assert _resolved(launch) == url and _resolved(bee).endswith("/PROFILE-B")
+ assert reaps == [hermes_home_key(launch)] * 2 and "BROWSER_CDP_URL" not in os.environ
+ assert _call(server, launch, {"action": "status"})["result"]["url"] == url
+ assert _call(server, bee, {"action": "status"})["result"]["url"].endswith("/PROFILE-B")
+ reaps.clear()
+ assert _call(server, bee, {"action": "connect", "url": url + "/"})["result"]["connected"] is True
+ assert reaps == [hermes_home_key(bee)] * 2
+ reaps.clear()
+ assert _call(server, launch, {"action": "disconnect"})["result"]["connected"] is False
+ assert reaps == [hermes_home_key(launch)] * 2 # B's browsers are not reaped
+ assert _resolved(launch) == "" and _resolved(bee) == url # B's live connection stands
+ assert _call(server, bee, {"action": "status"})["result"]["url"] == url
def test_single_profile_standalone_owner_connects_the_gateways_browser(homes, monkeypatch):
- """A standalone owner (never multiplexes, so it can never hot-serve another profile): the
- gateway's browser tools are that profile's alone, so connect/disconnect run (what Ink, Desktop
- and now the classic CLI send)."""
+ """CLI-9 (d): a standalone owner connects and disconnects as before."""
import os
from gateway import run_api
server, launch, _bee, url, reaps = homes
monkeypatch.setattr(run_api, "_ACTIVE_RUNNER", _runner_serving("default", multiplexed=False))
reply = _call(server, launch, {"action": "connect", "url": url})
assert reply["result"]["connected"] is True, reply
- assert os.environ["BROWSER_CDP_URL"] == url and reaps
+ assert _resolved(launch) == url and reaps and "ALL" not in reaps
assert _call(server, launch, {"action": "status"})["result"]["url"] == url
assert _call(server, launch, {"action": "disconnect"})["result"]["connected"] is False
- assert "BROWSER_CDP_URL" not in os.environ
+ assert _resolved(launch) == "" and "BROWSER_CDP_URL" not in os.environ
def test_connect_then_hot_serve_never_hands_one_profiles_browser_to_the_next(homes, monkeypatch):
- """Review #141357 P1: a multiplexing owner serving ONE profile must still refuse connect, or a
- profile hot-served afterwards inherits the process-wide override over its own browser.cdp_url
- (and disconnect is then refused, so it can never be withdrawn)."""
- import os
+ """CLI-9 (b), review #141357 P1: A connects while it is the only profile served; B, hot-served
+ afterwards, still resolves its own browser.cdp_url, and A can still disconnect."""
from gateway import run_api
- from gateway.session_authorities import SessionAuthorities
- from tools.browser_tool_cdp import _get_cdp_override_raw
- from gateway.run import _profile_runtime_scope
- server, launch, bee, url, reaps = homes
+ server, launch, bee, url, _reaps = homes
(bee / "config.yaml").write_text("browser:\n cdp_url: ws://bee.invalid/devtools/browser/PROFILE-B\n")
- registry = SessionAuthorities(launch, multiplexed=True)
- registry.add(launch, types.SimpleNamespace(profile_id=str(launch), retiring=False), name="default")
+ registry = _registry(launch)
monkeypatch.setattr(run_api, "_ACTIVE_RUNNER", types.SimpleNamespace(session_authorities=registry))
- reply = _call(server, launch, {"action": "connect", "url": url})
- assert reply["error"]["code"] == 4030 and reply["error"]["data"]["reason"] == "browser_profile_shared", reply
+ assert _call(server, launch, {"action": "connect", "url": url})["result"]["connected"] is True
registry.add(bee, types.SimpleNamespace(profile_id=str(bee), retiring=False), name="bee") # hot-serve
- assert "BROWSER_CDP_URL" not in os.environ and reaps == []
- with _profile_runtime_scope(bee):
- assert _get_cdp_override_raw().endswith("/PROFILE-B")
+ assert _resolved(bee).endswith("/PROFILE-B") and _resolved(launch) == url
+ assert _call(server, launch, {"action": "disconnect"})["result"]["connected"] is False
+ assert _resolved(launch) == "" and _resolved(bee).endswith("/PROFILE-B")
diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.py
index fd1987cb74f..ec6edf2f3bc 100644
--- a/tests/tui_gateway/test_tui_gateway_server.py
+++ b/tests/tui_gateway/test_tui_gateway_server.py
@@ -18024,19 +18024,32 @@ def test_browser_manage_use_swaps_the_profiles_browser_tools_for_new_agents(monk
assert (backend(other_home), backend(get_hermes_home())) == ("off", "browser-use")
[email protected](autouse=True)
+def _no_live_cdp(monkeypatch):
+ """Each test starts with no profile's live ``/browser connect`` endpoint."""
+ from tools import browser_tool_cdp
+ monkeypatch.setattr(browser_tool_cdp, "_live_overrides", {})
+
+
+def _live_cdp() -> str:
+ """The launch profile's live ``/browser connect`` endpoint (per profile since CLI-9)."""
+ from tools.browser_tool_cdp import live_cdp_override
+ return live_cdp_override()
+
+
def test_browser_manage_connect_sets_env_and_cleans_twice(monkeypatch):
- """`/browser connect` must reach the live process: set env, reap browser
+ """`/browser connect` must reach the live process: set this profile's endpoint, reap its browser
sessions before AND after publishing the new URL. The double-cleanup
closes the supervisor swap window where ``_ensure_cdp_supervisor``
could re-attach to the *old* CDP endpoint between steps."""
monkeypatch.delenv("BROWSER_CDP_URL", raising=False)
cleanup_calls: list[str] = []
- def _cleanup_all():
- cleanup_calls.append(os.environ.get("BROWSER_CDP_URL", ""))
+ def _cleanup_all(_key):
+ cleanup_calls.append(_live_cdp())
fake = types.SimpleNamespace(
- cleanup_all_browsers=_cleanup_all,
+ cleanup_profile_browsers=_cleanup_all,
_get_cdp_override=lambda: os.environ.get("BROWSER_CDP_URL", ""),
)
with patch.dict(sys.modules, {"tools.browser_tool_lifecycle": fake}):
@@ -18051,7 +18064,7 @@ def test_browser_manage_connect_sets_env_and_cleans_twice(monkeypatch):
assert resp["result"]["connected"] is True
assert resp["result"]["url"] == "http://127.0.0.1:9222"
- assert os.environ.get("BROWSER_CDP_URL") == "http://127.0.0.1:9222"
+ assert _live_cdp() == "http://127.0.0.1:9222"
# First cleanup runs against the OLD env (none here), second against the NEW.
assert cleanup_calls == ["", "http://127.0.0.1:9222"]
@@ -18059,7 +18072,7 @@ def test_browser_manage_connect_sets_env_and_cleans_twice(monkeypatch):
def test_browser_manage_connect_defaults_to_loopback(monkeypatch):
monkeypatch.delenv("BROWSER_CDP_URL", raising=False)
fake = types.SimpleNamespace(
- cleanup_all_browsers=lambda: None,
+ cleanup_profile_browsers=lambda _key: None,
_get_cdp_override=lambda: os.environ.get("BROWSER_CDP_URL", ""),
)
with patch.dict(sys.modules, {"tools.browser_tool_lifecycle": fake}):
@@ -18086,7 +18099,7 @@ def test_browser_manage_connect_default_local_reports_launch_hint(monkeypatch):
lambda evt, sid, payload=None: emitted.append((evt, payload or {})),
)
fake = types.SimpleNamespace(
- cleanup_all_browsers=lambda: None,
+ cleanup_profile_browsers=lambda _key: None,
_get_cdp_override=lambda: os.environ.get("BROWSER_CDP_URL", ""),
)
with patch.dict(sys.modules, {"tools.browser_tool_lifecycle": fake}):
@@ -18135,7 +18148,7 @@ def test_browser_manage_connect_no_session_skips_progress_events(monkeypatch):
lambda evt, sid, payload=None: emitted.append((evt, payload or {})),
)
fake = types.SimpleNamespace(
- cleanup_all_browsers=lambda: None,
+ cleanup_profile_browsers=lambda _key: None,
_get_cdp_override=lambda: os.environ.get("BROWSER_CDP_URL", ""),
)
with patch.dict(sys.modules, {"tools.browser_tool_lifecycle": fake}):
@@ -18170,7 +18183,7 @@ def test_browser_manage_connect_handles_null_url(monkeypatch):
by the outer 5031 catch."""
monkeypatch.delenv("BROWSER_CDP_URL", raising=False)
fake = types.SimpleNamespace(
- cleanup_all_browsers=lambda: None,
+ cleanup_profile_browsers=lambda _key: None,
_get_cdp_override=lambda: os.environ.get("BROWSER_CDP_URL", ""),
)
with patch.dict(sys.modules, {"tools.browser_tool_lifecycle": fake}):
@@ -18205,7 +18218,7 @@ def test_browser_manage_connect_default_local_retries_after_launch(monkeypatch):
monkeypatch.delenv("BROWSER_CDP_URL", raising=False)
monkeypatch.setattr(server.time, "sleep", lambda _seconds: None)
fake = types.SimpleNamespace(
- cleanup_all_browsers=lambda: None,
+ cleanup_profile_browsers=lambda _key: None,
_get_cdp_override=lambda: os.environ.get("BROWSER_CDP_URL", ""),
)
@@ -18248,7 +18261,7 @@ def test_browser_manage_connect_default_local_retries_after_launch(monkeypatch):
assert resp["result"]["connected"] is True
assert resp["result"]["url"] == "http://127.0.0.1:9222"
- assert os.environ["BROWSER_CDP_URL"] == "http://127.0.0.1:9222"
+ assert _live_cdp() == "http://127.0.0.1:9222"
def test_browser_manage_connect_finds_ipv6_only_browser(monkeypatch):
@@ -18257,7 +18270,7 @@ def test_browser_manage_connect_finds_ipv6_only_browser(monkeypatch):
endpoint instead of timing out against the squatter."""
monkeypatch.delenv("BROWSER_CDP_URL", raising=False)
fake = types.SimpleNamespace(
- cleanup_all_browsers=lambda: None,
+ cleanup_profile_browsers=lambda _key: None,
_get_cdp_override=lambda: os.environ.get("BROWSER_CDP_URL", ""),
)
@@ -18285,7 +18298,7 @@ def test_browser_manage_connect_finds_ipv6_only_browser(monkeypatch):
assert resp["result"]["connected"] is True
assert resp["result"]["url"] == "http://[::1]:9222"
- assert os.environ["BROWSER_CDP_URL"] == "http://[::1]:9222"
+ assert _live_cdp() == "http://[::1]:9222"
def test_browser_manage_connect_squatted_port_launches_on_alternate(monkeypatch):
@@ -18295,7 +18308,7 @@ def test_browser_manage_connect_squatted_port_launches_on_alternate(monkeypatch)
monkeypatch.delenv("BROWSER_CDP_URL", raising=False)
monkeypatch.setattr(server.time, "sleep", lambda _seconds: None)
fake = types.SimpleNamespace(
- cleanup_all_browsers=lambda: None,
+ cleanup_profile_browsers=lambda _key: None,
_get_cdp_override=lambda: os.environ.get("BROWSER_CDP_URL", ""),
)
@@ -18335,16 +18348,17 @@ def test_browser_manage_connect_squatted_port_launches_on_alternate(monkeypatch)
assert launch_ports == [9223]
assert resp["result"]["connected"] is True
assert resp["result"]["url"] == "http://127.0.0.1:9223"
- assert os.environ["BROWSER_CDP_URL"] == "http://127.0.0.1:9223"
+ assert _live_cdp() == "http://127.0.0.1:9223"
def test_browser_manage_connect_rejects_unreachable_endpoint(monkeypatch):
"""An unreachable endpoint must NOT mutate the env or reap sessions."""
- monkeypatch.setenv("BROWSER_CDP_URL", "http://existing:9222")
+ from tools.browser_tool_cdp import set_live_cdp_override
+ set_live_cdp_override("http://existing:9222")
cleanup_calls: list[str] = []
fake = types.SimpleNamespace(
- cleanup_all_browsers=lambda: cleanup_calls.append(
- os.environ.get("BROWSER_CDP_URL", "")
+ cleanup_profile_browsers=lambda _key: cleanup_calls.append(
+ _live_cdp()
),
_get_cdp_override=lambda: os.environ.get("BROWSER_CDP_URL", ""),
)
@@ -18360,7 +18374,7 @@ def test_browser_manage_connect_rejects_unreachable_endpoint(monkeypatch):
assert "error" in resp
# Env preserved; nothing reaped.
- assert os.environ["BROWSER_CDP_URL"] == "http://existing:9222"
+ assert _live_cdp() == "http://existing:9222"
assert cleanup_calls == []
@@ -18370,7 +18384,7 @@ def test_browser_manage_connect_normalizes_bare_host_port(monkeypatch):
tool calls (Copilot review on #17120)."""
monkeypatch.delenv("BROWSER_CDP_URL", raising=False)
fake = types.SimpleNamespace(
- cleanup_all_browsers=lambda: None,
+ cleanup_profile_browsers=lambda _key: None,
_get_cdp_override=lambda: os.environ.get("BROWSER_CDP_URL", ""),
)
with patch.dict(sys.modules, {"tools.browser_tool_lifecycle": fake}):
@@ -18386,7 +18400,7 @@ def test_browser_manage_connect_normalizes_bare_host_port(monkeypatch):
assert resp["result"]["connected"] is True
# Bare host:port got promoted to a full URL with explicit scheme.
assert resp["result"]["url"].startswith("http://")
- assert os.environ["BROWSER_CDP_URL"].startswith("http://")
+ assert _live_cdp().startswith("http://")
def test_browser_manage_connect_strips_discovery_path(monkeypatch):
@@ -18396,7 +18410,7 @@ def test_browser_manage_connect_strips_discovery_path(monkeypatch):
produce a duplicate path (Copilot review round-2 on #17120)."""
monkeypatch.delenv("BROWSER_CDP_URL", raising=False)
fake = types.SimpleNamespace(
- cleanup_all_browsers=lambda: None,
+ cleanup_profile_browsers=lambda _key: None,
_get_cdp_override=lambda: os.environ.get("BROWSER_CDP_URL", ""),
)
with patch.dict(sys.modules, {"tools.browser_tool_lifecycle": fake}):
@@ -18411,7 +18425,7 @@ def test_browser_manage_connect_strips_discovery_path(monkeypatch):
assert resp["result"]["connected"] is True
assert resp["result"]["url"] == "http://127.0.0.1:9222"
- assert os.environ["BROWSER_CDP_URL"] == "http://127.0.0.1:9222"
+ assert _live_cdp() == "http://127.0.0.1:9222"
def test_browser_manage_connect_preserves_devtools_browser_endpoint(monkeypatch):
@@ -18419,7 +18433,7 @@ def test_browser_manage_connect_preserves_devtools_browser_endpoint(monkeypatch)
survive verbatim — we only collapse discovery-style paths."""
monkeypatch.delenv("BROWSER_CDP_URL", raising=False)
fake = types.SimpleNamespace(
- cleanup_all_browsers=lambda: None,
+ cleanup_profile_browsers=lambda _key: None,
_get_cdp_override=lambda: os.environ.get("BROWSER_CDP_URL", ""),
)
concrete = "ws://browserbase.example/devtools/browser/abc123"
@@ -18449,7 +18463,7 @@ def test_browser_manage_connect_preserves_devtools_browser_endpoint(monkeypatch)
assert resp["result"]["connected"] is True
assert resp["result"]["url"] == concrete
- assert os.environ["BROWSER_CDP_URL"] == concrete
+ assert _live_cdp() == concrete
def test_browser_manage_connect_local_devtools_ws_preserves_path(monkeypatch):
@@ -18458,7 +18472,7 @@ def test_browser_manage_connect_local_devtools_ws_preserves_path(monkeypatch):
``/devtools/browser/...`` path or it breaks valid local CDP connects."""
monkeypatch.delenv("BROWSER_CDP_URL", raising=False)
fake = types.SimpleNamespace(
- cleanup_all_browsers=lambda: None,
+ cleanup_profile_browsers=lambda _key: None,
_get_cdp_override=lambda: os.environ.get("BROWSER_CDP_URL", ""),
)
concrete = "ws://127.0.0.1:9222/devtools/browser/abc123"
@@ -18482,7 +18496,7 @@ def test_browser_manage_connect_local_devtools_ws_preserves_path(monkeypatch):
assert resp["result"]["connected"] is True
assert resp["result"]["url"] == concrete
- assert os.environ["BROWSER_CDP_URL"] == concrete
+ assert _live_cdp() == concrete
def test_browser_manage_connect_rejects_invalid_port(monkeypatch):
@@ -18519,7 +18533,7 @@ def test_browser_manage_connect_concrete_ws_skips_http_probe(monkeypatch):
The HTTP probe used to reject these even though they're valid."""
monkeypatch.delenv("BROWSER_CDP_URL", raising=False)
fake = types.SimpleNamespace(
- cleanup_all_browsers=lambda: None,
+ cleanup_profile_browsers=lambda _key: None,
_get_cdp_override=lambda: os.environ.get("BROWSER_CDP_URL", ""),
)
concrete = "wss://chrome.browserless.io/devtools/browser/sess-1"
@@ -18563,7 +18577,7 @@ def test_browser_manage_connect_concrete_ws_tcp_unreachable(monkeypatch):
can never succeed for these URLs anyway)."""
monkeypatch.delenv("BROWSER_CDP_URL", raising=False)
fake = types.SimpleNamespace(
- cleanup_all_browsers=lambda: None,
+ cleanup_profile_browsers=lambda _key: None,
_get_cdp_override=lambda: os.environ.get("BROWSER_CDP_URL", ""),
)
concrete = "ws://offline.example/devtools/browser/missing"
@@ -18583,10 +18597,12 @@ def test_browser_manage_connect_concrete_ws_tcp_unreachable(monkeypatch):
def test_browser_manage_disconnect_drops_env_and_cleans(monkeypatch):
- monkeypatch.setenv("BROWSER_CDP_URL", "http://127.0.0.1:9222")
+ from tools.browser_tool_cdp import set_live_cdp_override
+ monkeypatch.setenv("BROWSER_CDP_URL", "http://operator:9222") # an operator's env is not the live connect
+ set_live_cdp_override("http://127.0.0.1:9222")
cleanup_count = {"n": 0}
fake = types.SimpleNamespace(
- cleanup_all_browsers=lambda: cleanup_count.__setitem__(
+ cleanup_profile_browsers=lambda _key: cleanup_count.__setitem__(
"n", cleanup_count["n"] + 1
),
_get_cdp_override=lambda: os.environ.get("BROWSER_CDP_URL", ""),
@@ -18597,8 +18613,8 @@ def test_browser_manage_disconnect_drops_env_and_cleans(monkeypatch):
)
assert resp["result"] == {"connected": False}
- assert "BROWSER_CDP_URL" not in os.environ
- # Two cleanups: once before env removal, once after, matching connect.
+ assert _live_cdp() == "" and os.environ["BROWSER_CDP_URL"] == "http://operator:9222"
+ # Two cleanups: once before the override is dropped, once after, matching connect.
assert cleanup_count["n"] == 2
diff --git a/tui_gateway/methods_browser.py b/tui_gateway/methods_browser.py
index 603f066da3d..6ab282b91aa 100644
--- a/tui_gateway/methods_browser.py
+++ b/tui_gateway/methods_browser.py
@@ -12,9 +12,11 @@ _CDP_SCHEMES = {"http", "https", "ws", "wss"}
def _resolve_browser_cdp_url() -> str:
"""Configured browser CDP override without network I/O (``/browser status`` must be fast;
- ``tools.browser_tool_cdp._get_cdp_override`` HTTP-probes discovery URLs). Same precedence (env,
- then ``browser.cdp_url``) minus WS resolution; ``browser_navigate`` normalizes on the next call."""
- if env_url := os.environ.get("BROWSER_CDP_URL", "").strip():
+ ``tools.browser_tool_cdp._get_cdp_override`` HTTP-probes discovery URLs). Same precedence (this
+ profile's live connect, env, then ``browser.cdp_url``) minus WS resolution; ``browser_navigate``
+ normalizes on the next call."""
+ from tools.browser_tool_cdp import live_cdp_override
+ if env_url := live_cdp_override() or os.environ.get("BROWSER_CDP_URL", "").strip():
return env_url
with contextlib.suppress(Exception):
from hermes_cli.config import read_raw_config
@@ -93,10 +95,18 @@ def _connect_local_default(port: int, system: str, announce) -> str | None:
return None
+def _reap_profile_browsers() -> None:
+ """Close the current profile's browsers only: the live connection is per profile, so other
+ profiles' sessions on a multiplexed gateway keep theirs."""
+ from hermes_constants import hermes_home_key
+ from tools.browser_tool_lifecycle import cleanup_profile_browsers
+ cleanup_profile_browsers(hermes_home_key())
+
+
def _browser_connect(rid, params: dict) -> dict:
import platform
from hermes_cli.browser_connect import DEFAULT_BROWSER_CDP_URL
- from tools.browser_tool_lifecycle import cleanup_all_browsers
+ from tools.browser_tool_cdp import set_live_cdp_override
from urllib.parse import urlparse
raw_url = params.get("url")
if raw_url is not None and not isinstance(raw_url, str):
@@ -146,11 +156,11 @@ def _browser_connect(rid, params: dict) -> dict:
# to ``scheme://host:port`` so ``_resolve_cdp_override`` can append ``/json/version``.
normalized = (parsed.geturl() if parsed.path.startswith("/devtools/browser/")
else parsed._replace(path="", params="", query="", fragment="").geturl())
- # Reap BEFORE publishing the new env (an in-flight tool call sees the old supervisor closed)
- # and AFTER (the default task's cached supervisor drains against the new URL).
- cleanup_all_browsers()
- os.environ["BROWSER_CDP_URL"] = normalized
- cleanup_all_browsers()
+ # Reap BEFORE publishing this profile's endpoint (an in-flight tool call sees the old
+ # supervisor closed) and AFTER (the default task's cached supervisor drains against the new URL).
+ _reap_profile_browsers()
+ set_live_cdp_override(normalized)
+ _reap_profile_browsers()
except Exception as e:
return _err(rid, 5031, str(e))
return _ok(rid, {"connected": True, "url": normalized,
@@ -158,14 +168,15 @@ def _browser_connect(rid, params: dict) -> dict:
def _browser_disconnect(rid) -> dict:
- # Reap, drop the override, reap again — same swap window as ``_browser_connect``.
+ # Reap, drop this profile's override, reap again — same swap window as ``_browser_connect``.
+ from tools.browser_tool_cdp import set_live_cdp_override
+
def reap() -> None:
with contextlib.suppress(Exception):
- from tools.browser_tool_lifecycle import cleanup_all_browsers
- cleanup_all_browsers()
+ _reap_profile_browsers()
reap()
- os.environ.pop("BROWSER_CDP_URL", None)
+ set_live_cdp_override(None)
reap()
return _ok(rid, {"connected": False})
diff --git a/tui_gateway/ws_legacy_fallback.py b/tui_gateway/ws_legacy_fallback.py
index bbeab77307b..7f1baed3f74 100644
--- a/tui_gateway/ws_legacy_fallback.py
+++ b/tui_gateway/ws_legacy_fallback.py
@@ -44,36 +44,10 @@ _SESSION_FALLBACK_ALLOWED = frozenset({
# (``gateway/session_tui_ops.py``); listing them here keeps the sidecar handler unreachable.
# ``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 browser tools read first (dokterdok N25); ``status`` and ``use``
-# (the profile's ``browser.backend``) stay. A missing action means ``status``.
-#
-# CLI-9 (#134889): on an owner that serves ONE profile and never multiplexes (a standalone gateway)
-# those chats are all that profile's, so the live connect is the user's own choice and runs (Ink,
-# Desktop and the classic CLI all send it here). An owner that CAN multiplex refuses by name even
-# while it serves one profile: a later hot-served profile would inherit the process-wide override
-# (which wins over its own ``browser.cdp_url``), and the browser state has no per-profile scope yet
-# (``cleanup_all_browsers`` reaps every task's browser). ``data.reason`` is the client's bounded code.
-_PROCESS_GLOBAL_ACTIONS = {"browser.manage": ({"connect", "disconnect"}, "browser_profile_shared", (
- "/browser connect and /browser disconnect are unavailable on a gateway that serves several profiles: "
- "the live browser connection is shared by every profile's chats. Set browser.cdp_url in this "
- "profile's config.yaml instead."))}
-
-
-def _owner_may_multiplex() -> bool:
- """Whether this owner serves, or can hot-serve, more than one profile (the running gateway's
- authority registry: multiplex mode, or a second profile ever served); without a registered
- runner, whether the process multiplexes at all (fail closed)."""
- from agent.secret_scope import is_multiplex_active
- from gateway import run_api
- runner = getattr(run_api, "_ACTIVE_RUNNER", None)
- registry = getattr(runner, "session_authorities", None)
- if registry is None:
- return is_multiplex_active()
- from gateway.session_authorities import serving_authorities
- return getattr(registry, "multiplexed", False) or len(serving_authorities(runner)) > 1
+# ``browser.manage`` is NOT here: connect/disconnect run in the requesting profile's scope (the
+# ticket's home, or the session's ``profile_home`` via ``_profile_scoped``) and the live endpoint, the
+# reap and the CDP supervisors are keyed by that profile home (CLI-9, #134889), so a multiplexed
+# owner serves them without reaching another profile's browser.
def legacy_fallback_allowed(actor: Any, method: str) -> bool:
@@ -163,10 +137,6 @@ def _own_profile_read(server: Any, req: dict, home: str) -> dict:
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, reason, refusal = _PROCESS_GLOBAL_ACTIONS.get(req.get("method"), ((), "", ""))
- if (req.get("params") or {}).get("action", "status") in actions and _owner_may_multiplex():
- return {"jsonrpc": "2.0", "id": req.get("id"),
- "error": {"code": 4030, "message": refusal, "data": {"reason": reason}}}
try:
home = _foreign_profile_home(server, getattr(actor, "profile_id", None))
except OSError: