Skip to content

The agent that grows with you

Merge origin/main: browser fence composed with the dispatch/retry split (#115184); server registration, i18n, contracts

teknium17ed6534c7e2f
diff --cc apps/desktop/src/app/routes.ts
index 87723bbd921,503928aeba5..3ed1c01c2b4
--- a/apps/desktop/src/app/routes.ts
+++ b/apps/desktop/src/app/routes.ts
@@@ -133,27 -134,10 +134,29 @@@ export interface SidebarNavContributio
label: string
/** Route to navigate to (usually a contributed page's path). */
path: string
+ /** `'advanced'` keeps the row out of Simple mode; unset shows it everywhere. */
+ tier?: InterfaceTier
}
+// ── Contributed profile-group header — the `sidebar.profileGroup.header` area ─
+// A RENDER contribution mounted at the top of each gateway/profile group in the
+// Sessions sidebar (above its session rows) while the group is expanded. The
+// contribution's `data` is a `ProfileGroupHeaderContribution`; core calls
+// `render(route)` with the group's connection + profile so one contribution
+// serves every group. First consumer: the Bots plugin's Screen portal.
+
+export const SIDEBAR_PROFILE_GROUP_HEADER_AREA = 'sidebar.profileGroup.header'
+
+export interface ProfileGroupRoute {
+ connectionId: null | string
+ profile: string
+}
+
+/** Payload of a `sidebar.profileGroup.header` data contribution. */
+export interface ProfileGroupHeaderContribution {
+ render: (route: ProfileGroupRoute) => ReactNode
+}
+
// Views that render as a full-screen modal card (OverlayView) over the shell.
// While one is open the app's titlebar control clusters must hide so they don't
// bleed over the overlay (they sit at a higher z-index than the overlay card).
diff --cc apps/desktop/src/i18n/ar.ts
index de80ade52c5,8b50efee12f..24941aaedf6
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@@ -3122,9 -3226,9 +3226,10 @@@ export const ar = defineLocale(
sudoSendFailed: 'فشل إرسال كلمة مرور sudo',
secretSendFailed: 'فشل إرسال السر',
sudoTitle: 'مطلوب sudo',
- sudoDesc: 'راجع الأمر قبل إدخال كلمة مرور sudo. تُرسل كلمة المرور إلى الوكيل الذي ينفّذه وتُحفظ مؤقتًا لهذه الجلسة.',
+ sudoDesc:
+ 'راجع الأمر قبل إدخال كلمة مرور sudo. تُرسل كلمة المرور إلى الوكيل الذي ينفّذه وتُحفظ مؤقتًا لهذه الجلسة.',
sudoCommandUnavailable: 'لم يقدّم هذا الوكيل الأمر. ألغِ الطلب إذا لم تتمكن من التحقق منه في المحادثة.',
+ sudoInstallDesc: 'يحتاج Hermes إلى كلمة مرور sudo لتثبيت حزم Bot Screen (TigerVNC + Xfce) على مضيف البوابة. تُرسل إلى ذلك المضيف فقط.',
sudoPlaceholder: 'كلمة المرور',
secretTitle: 'مطلوب سر',
secretDesc: 'أدخل القيمة المطلوبة لمتابعة المهمة.',
diff --cc apps/desktop/src/i18n/en.ts
index c0902a24904,dbc98a57b1b..537f49286e0
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@@ -4370,9 -4742,10 +4742,11 @@@ export const en: Translations =
sudoSendFailed: 'Could not send sudo password',
secretSendFailed: 'Could not send secret',
sudoTitle: 'Administrator password',
- sudoDesc: 'Review the command before entering your sudo password. Your password is sent to the agent running it and cached for this session.',
- sudoCommandUnavailable: 'This agent did not provide the command. Cancel if you cannot verify it in the conversation.',
+ sudoDesc:
+ 'Review the command before entering your sudo password. Your password is sent to the agent running it and cached for this session.',
+ sudoCommandUnavailable:
+ 'This agent did not provide the command. Cancel if you cannot verify it in the conversation.',
+ sudoInstallDesc: 'Hermes needs your sudo password to install the Bot Screen packages (TigerVNC + Xfce) on the gateway host. It is sent only to that host.',
sudoPlaceholder: 'sudo password',
secretTitle: 'Secret required',
secretDesc: 'Hermes needs a credential to continue.',
diff --cc apps/desktop/src/i18n/ja.ts
index 331e6b1a2c6,ab6b4b73651..9da64f72cdf
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@@ -3545,8 -3642,8 +3642,9 @@@ export const ja = defineLocale(
sudoTitle: '管理者パスワード',
sudoDesc:
'sudo パスワードを入力する前にコマンドを確認してください。パスワードは実行するエージェントに送信され、このセッション中キャッシュされます。',
- sudoCommandUnavailable: 'エージェントからコマンドが提供されていません。会話で確認できない場合はキャンセルしてください。',
+ sudoCommandUnavailable:
+ 'エージェントからコマンドが提供されていません。会話で確認できない場合はキャンセルしてください。',
+ sudoInstallDesc: 'Bot Screen のパッケージ(TigerVNC + Xfce)をゲートウェイホストにインストールするため、sudo パスワードが必要です。そのホストにのみ送信されます。',
sudoPlaceholder: 'sudo パスワード',
secretTitle: 'シークレットが必要です',
secretDesc: 'Hermes は続行するための認証情報が必要です。',
diff --cc apps/desktop/src/plugins/hermes-bots/plugin.tsx
index 98fb65b68a3,38e54faa782..1faaff3b38a
--- a/apps/desktop/src/plugins/hermes-bots/plugin.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/plugin.tsx
@@@ -15,8 -15,15 +15,16 @@@
* bot-initiated sends use `hermes -p <bot> chat --in ~ -c "Bot Chat"`.
*/
- import { CHAT_EMPTY_AREA, COMPOSER_AREAS, host, PALETTE_AREA, SIDEBAR_PROFILE_GROUP_HEADER_AREA, translateNow } from '@hermes/plugin-sdk'
+ import {
+ CHAT_EMPTY_AREA,
+ COMPOSER_AREAS,
+ host,
+ LocalizedTabTitle,
+ PALETTE_AREA,
++ SIDEBAR_PROFILE_GROUP_HEADER_AREA,
+ translateNow
+ } from '@hermes/plugin-sdk'
-import type { ChatEmptyProps, PluginContext } from '@hermes/plugin-sdk'
+import type { ChatEmptyProps, PluginContext, ProfileGroupRoute } from '@hermes/plugin-sdk'
import { startFaceClock, stopFaceClock } from './avatar'
import {
diff --cc apps/shared/src/gateway-contract.generated.ts
index 86060b16e03,b48bd92b98c..fd32bc2ce72
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@@ -941,106 -850,286 +850,386 @@@ export interface VerificationEvidenceRo
output_summary?: string | null
[key: string]: unknown
}
+ export interface ConnectionOperationParams {
+ profile?: string | null
+ owner: SessionOwner | AccountOwner
+ op_id: string
+ }
+ export interface SessionOwner {
+ type: 'session'
+ session_id: string
+ }
+ export interface AccountOwner {
+ type: 'account'
+ }
+ /** ``methods_connectors._operation_view``: the operation's full snapshot. */
+ export interface ConnectionOperationStatus {
+ op_id: string
+ seq: number
+ deadline_at: number
+ settled: boolean
+ settled_at?: number | null
+ settled_by?: ConnectionSettleReason | null
+ targets: ConnectionOperationTarget[]
+ }
+ /** ``tools/connectors/contract.py::SettleReason``. */
+ export type ConnectionSettleReason = 'all_resolved' | 'continue' | 'deadline' | 'interrupt'
+ /** ``Target.snapshot``: the link minted up front rides here, never in the model result. ``extra`` keys a leg records (``tools``, ``hint``) are typed here as they appear. */
+ export interface ConnectionOperationTarget {
+ name: string
+ kind: ConnectionTargetKind
+ action: ConnectionTargetAction
+ state: ConnectionTargetState
+ detail?: string | null
+ instructions?: string | null
+ discovery_error?: string | null
+ connect_url?: string | null
+ connection_id?: string | null
+ attempt?: string | null
+ required_env?: ConnectionTargetEnvField[] | null
+ tools?: string[] | null
+ hint?: string | null
+ display?: string | null
+ description?: string | null
+ tier?: CatalogTier | null
+ platforms?: string[] | null
+ repo?: string | null
+ sha?: string | null
+ subdir?: string | null
+ scan?: CatalogScan | null
+ requirements?: string[] | null
+ has_desktop_half?: boolean | null
+ target_profile?: string | null
+ app_state?: CatalogAppState | null
+ skill?: string | null
+ }
+ export type ConnectionTargetKind = 'connector' | 'mcp' | 'plugin' | 'skill'
+ export type ConnectionTargetAction = 'authorize' | 'connect' | 'enable' | 'install' | 'reconnect'
+ /** ``tools/connectors/contract.py::TargetState``. */
+ export type ConnectionTargetState = 'pending' | 'initiated' | 'connected' | 'skipped' | 'failed' | 'expired' | 'not_connected'
+ /** One credential an MCP install still needs; the card renders a field per entry and sends the values back with the approval. */
+ export interface ConnectionTargetEnvField {
+ name: string
+ required: boolean
+ secret: boolean
+ default: string
+ prompt?: string | null
+ }
+ export type CatalogTier = 'official' | 'community'
+ /** The catalog's security scan of the pinned commit; read-only on the card. */
+ export interface CatalogScan {
+ status: CatalogScanStatus
+ summary: string
+ }
+ export type CatalogScanStatus = 'passed' | 'warnings' | 'failed'
+ /** The desktop app a catalog plugin drives, from its ``hermes_platform`` declaration. */
+ export type CatalogAppState = 'present' | 'missing_app' | 'app_not_running' | 'unknown'
+ export interface ConnectionWakeResult {
+ status: 'ok'
+ }
+ export interface ConnectionRespondParams {
+ profile?: string | null
+ owner: SessionOwner | AccountOwner
+ op_id: string
+ result: ConnectionAnswer
+ }
+ /** The card's answer: per-target outcomes and an optional Continue (``settled_by: "continue"``). Settlement is derived from target states afterwards. */
+ export interface ConnectionAnswer {
+ targets?: ConnectionAnswerTarget[]
+ settled_by?: ConnectionSettleReason | null
+ }
+ /** One row's answer from the card. ``env`` carries the credential values an install asked for through ``required_env``. */
+ export interface ConnectionAnswerTarget {
+ name: string
+ status: ConnectionAnswerStatus
+ detail?: string | null
+ env?: Record<string, string> | null
+ }
+ /** What the card says about one row: ``tools/connectors/mcp.py::apply_answer``. */
+ export type ConnectionAnswerStatus = 'approved' | 'skipped'
+ export interface ConnectionRespondResult {
+ status: 'ok'
+ settled: boolean
+ }
+ export interface ConnectorsListParams {
+ profile?: string | null
+ owner: SessionOwner | AccountOwner
+ }
+ export interface ConnectorsListResult {
+ available: boolean
+ connectors: ConnectorRow[]
+ }
+ export interface ConnectorRow {
+ connector: string
+ enabled: boolean
+ connected: boolean
+ connection_status: 'pending' | 'active' | 'failed' | 'expired' | 'revoked' | 'inactive' | null
+ status_reason: string | null
+ gateway_disabled_tools: string[]
+ }
+ export interface ConnectorsConnectParams {
+ profile?: string | null
+ owner: SessionOwner | AccountOwner
+ connectors: string[]
+ reconnect?: boolean
+ }
+ /** ``methods_connectors._reissue`` / ``managed._off_desktop_result``: the operation the connect opened; ``status``/``note`` ride along from the tool result. */
+ export interface ConnectorsConnectResult {
+ op_id: string
+ seq: number
+ deadline_at: number
+ settled: boolean
+ settled_at?: number | null
+ settled_by?: ConnectionSettleReason | null
+ targets: ConnectionOperationTarget[]
+ status?: 'initiated' | 'settled' | null
+ note?: string | null
+ }
+ export interface ConnectorToolsParams {
+ profile?: string | null
+ slug: string
+ refresh?: boolean
+ }
+ export interface ConnectorToolsResult {
+ connector: string
+ toolkit_version: string
+ etag: string
+ fetched_at: number
+ source: ConnectorToolsSource
+ stale: boolean
+ tools: ConnectorToolRow[]
+ }
+ export type ConnectorToolsSource = 'cache' | 'network' | 'revalidated'
+ export interface ConnectorToolRow {
+ slug: string
+ name: string
+ description: string
+ facet: ConnectorToolFacet
+ hints: string[]
+ categories: string[]
+ no_auth: boolean
+ deprecated: boolean
+ }
+ export type ConnectorToolFacet = 'read' | 'write' | 'destructive' | 'unclassified'
+ export interface ConnectorsCatalogResult {
+ connectors: ConnectorCatalogRow[]
+ }
+ export interface ConnectorCatalogRow {
+ slug: string
+ name: string
+ description: string
+ category: string
+ logo_url?: string | null
+ }
+ export interface ConnectorAccountsParams {
+ profile?: string | null
+ connector?: string | null
+ }
+ export interface ConnectorAccountsResult {
+ accounts: ConnectorAccountRow[]
+ }
+ export interface ConnectorAccountRow {
+ connection_id: string
+ connector: string
+ status: ConnectorAccountStatus
+ status_reason?: string | null
+ label: string
+ alias?: string | null
+ active: boolean
+ created_at: string
+ updated_at: string
+ }
+ export type ConnectorAccountStatus = 'pending' | 'active' | 'failed' | 'expired' | 'revoked' | 'inactive'
+ export interface ConnectorAccountsRemoveParams {
+ profile?: string | null
+ connection_id: string
+ }
+ export interface ConnectorAccountsRemoveResult {
+ connection_id: string
+ connector: string
+ status: 'removed'
+ }
+ export interface ConnectorPolicyGetResult {
+ layers: ConnectorPolicyLayer[]
+ effective: ConnectorPolicyEffectiveUnrestricted | ConnectorPolicyEffectiveDenyAll | ConnectorPolicyEffectiveAllow | ConnectorPolicyEffectiveDeny
+ }
+ export interface ConnectorPolicyLayer {
+ kind: ConnectorPolicyLayerKind
+ revision: string
+ body: ConnectorPolicyUnrestrictedBody | ConnectorPolicyDenyAllBody | ConnectorPolicyAllowBody | ConnectorPolicyDenyBody
+ }
+ export type ConnectorPolicyLayerKind = 'org' | 'role' | 'member'
+ export interface ConnectorPolicyUnrestrictedBody {
+ mode: 'unrestricted'
+ }
+ export interface ConnectorPolicyDenyAllBody {
+ mode: 'deny-all'
+ }
+ export interface ConnectorPolicyAllowBody {
+ mode: 'allow'
+ connectors: string[]
+ tools: Record<string, string[]>
+ tags?: ConnectorPolicyTags | null
+ }
+ export interface ConnectorPolicyTags {
+ enable?: string[] | null
+ disable?: string[] | null
+ }
+ export interface ConnectorPolicyDenyBody {
+ mode: 'deny'
+ disabled_connectors: string[]
+ tools: Record<string, string[]>
+ tags?: ConnectorPolicyTags | null
+ }
+ export interface ConnectorPolicyEffectiveUnrestricted {
+ version: 1
+ revision: string
+ issued_at_ms: number
+ mode: 'unrestricted'
+ }
+ export interface ConnectorPolicyEffectiveDenyAll {
+ version: 1
+ revision: string
+ issued_at_ms: number
+ mode: 'deny-all'
+ }
+ export interface ConnectorPolicyEffectiveAllow {
+ version: 1
+ revision: string
+ issued_at_ms: number
+ mode: 'allow'
+ connectors: string[]
+ tools: Record<string, string[]>
+ tags?: ConnectorPolicyTags | null
+ }
+ export interface ConnectorPolicyEffectiveDeny {
+ version: 1
+ revision: string
+ issued_at_ms: number
+ mode: 'deny'
+ disabled_connectors: string[]
+ tools: Record<string, string[]>
+ tags?: ConnectorPolicyTags | null
+ }
+ export interface ConnectorPolicySetParams {
+ profile?: string | null
+ change: ToolsChange | ConnectorChange
+ expected_revision: string
+ }
+ export interface ToolsChange {
+ type: 'tools'
+ connector: string
+ disabled_tools: string[]
+ }
+ export interface ConnectorChange {
+ type: 'connector'
+ connector: string
+ enabled: boolean
+ }
+ export interface ConnectorPolicySetResult {
+ revision: string
+ effective: ConnectorPolicyEffectiveUnrestricted | ConnectorPolicyEffectiveDenyAll | ConnectorPolicyEffectiveAllow | ConnectorPolicyEffectiveDeny
+ }
+/** ``tools/bot_desktop/runtime.py::DesktopStatus`` plus the lease and the profile it speaks for. */
+export interface DisplayStatus {
+ profile: string
+ supported: boolean
+ installed: boolean
+ missing: string[]
+ running: boolean
+ pid?: number | null
+ display?: string | null
+ socket?: string | null
+ geometry: string
+ install_command?: string | null
+ browser?: string | null
+ blocker?: string | null
+ memory_available_mb?: number | null
+ memory_limit_mb?: number | null
+ lease: DisplayLease
+ profile_key: string
+}
+/** ``tools/bot_desktop/lease.py::Lease`` as clients may see it: the holder's viewer id is a capability and never leaves the gateway; ``viewer_hash`` lets the holder recognise itself. */
+export interface DisplayLease {
+ holder: LeaseHolder
+ viewer_id?: null
+ viewer_hash?: string | null
+ since: number
+ epoch: number
+ reason?: string
+}
+export type LeaseHolder = 'agent' | 'human'
+/** ``data_url`` is null while the screen is stopped or while a human holds the lease (``suppressed``): the frame may show what they are typing. */
+export interface DisplayThumbnailResult {
+ data_url?: string | null
+ suppressed?: string | null
+}
+export interface DisplayStopParams {
+ profile?: string | null
+ force?: boolean | null
+}
+export interface DisplayStopResult {
+ profile: string
+ supported: boolean
+ installed: boolean
+ missing: string[]
+ running: boolean
+ pid?: number | null
+ display?: string | null
+ socket?: string | null
+ geometry: string
+ install_command?: string | null
+ browser?: string | null
+ blocker?: string | null
+ memory_available_mb?: number | null
+ memory_limit_mb?: number | null
+ lease: DisplayLease
+ profile_key: string
+ stopped: boolean
+}
+export interface DisplayObserveParams {
+ profile?: string | null
+ viewer_id?: string | null
+}
+export interface DisplayObserveResult {
+ profile: string
+ supported: boolean
+ installed: boolean
+ missing: string[]
+ running: boolean
+ pid?: number | null
+ display?: string | null
+ socket?: string | null
+ geometry: string
+ install_command?: string | null
+ browser?: string | null
+ blocker?: string | null
+ memory_available_mb?: number | null
+ memory_limit_mb?: number | null
+ lease: DisplayLease
+ profile_key: string
+ ticket: string
+ path: string
+ viewer_id: string
+}
+export interface DisplayInstallResult {
+ started: boolean
+ command?: string | null
+ profile_key: string
+}
+export interface DisplayLeaseAcquireParams {
+ profile?: string | null
+ viewer_id: string
+ reason?: string | null
+}
+export interface DisplayLeaseResult {
+ lease: DisplayLease
+}
+export interface DisplayLeaseReleaseParams {
+ profile?: string | null
+ viewer_id?: string | null
+ force?: boolean | null
+}
export interface GroupsCapabilitiesParams {
profile?: string | null
}
@@@ -3930,43 -4126,7 +4230,43 @@@ export interface ConnectionUpdatePayloa
detail?: string | null
}
/** ``tools/connectors/contract.py::Actor``. */
- export type ConnectionActor = 'user' | 'renderer_flow' | 'backend_watcher' | 'clock'
+ export type ConnectionActor = 'user' | 'backend_watcher' | 'clock'
+export interface RequestCancelPayload {
+ id: string
+ method: string
+ reason: string
+}
+export interface DisplayStatusPayload {
+ profile: string
+ supported: boolean
+ installed: boolean
+ missing: string[]
+ running: boolean
+ pid?: number | null
+ display?: string | null
+ socket?: string | null
+ geometry: string
+ install_command?: string | null
+ browser?: string | null
+ blocker?: string | null
+ memory_available_mb?: number | null
+ memory_limit_mb?: number | null
+ lease: DisplayLease
+ profile_key: string
+}
+export interface DisplayLeasePayload {
+ profile_key: string
+ lease: DisplayLease
+}
+export interface DisplayInstallLogPayload {
+ profile_key: string
+ line: string
+}
+export interface DisplayInstallDonePayload {
+ profile_key: string
+ code: number
+ status: DisplayStatus
+}
/** ``tui_gateway/entry.py`` (stdio) / ``tui_gateway/ws.py`` (WebSocket) first frame. */
export interface GatewayReadyPayload {
skin: SkinPayload
@@@ -4324,6 -4494,12 +4634,7 @@@ export interface PetHatchProgressPayloa
}
/** ``change_watcher._CHANGE_WATCHES`` payload fn — ``{}`` for every watch except pet.changed. */
export type ChangeSignalPayload = Record<string, unknown>
-export interface RequestCancelPayload {
- id: string
- method: string
- reason: string
-}
+ export type ConnectorErrorReason = 'INVALID_PARAMS' | 'NOT_OWNER' | 'UNSUPPORTED_RUNTIME' | 'CONNECTOR_REQUEST_FAILED' | 'INVALID_CONNECTOR_RESPONSE' | 'UNKNOWN_TARGET' | 'LINK_STILL_VALID' | 'REISSUE_REFUSED' | 'UNKNOWN_OPERATION' | 'INVALID_ANSWER' | 'NEEDS_NOUS_AUTH' | 'CONNECTOR_NOT_FOUND' | 'TOOLS_UNAVAILABLE' | 'CONNECTORS_UNAVAILABLE' | 'CATALOG_UNAVAILABLE' | 'ACCOUNTS_UNAVAILABLE' | 'CONNECTION_NOT_FOUND' | 'POLICY_UNAVAILABLE' | 'POLICY_CONFLICT' | 'FORBIDDEN_SCOPE' | 'ORG_REQUIRED' | 'ORG_ACCESS_DENIED' | 'INVALID_POLICY'
// ── Client→server methods ──
export interface RpcMethods {
diff --cc tests/hermes_cli/test_profiles.py
index c14fce074ae,152042ad916..3808c6f11eb
--- a/tests/hermes_cli/test_profiles.py
+++ b/tests/hermes_cli/test_profiles.py
@@@ -6,10 -6,8 +6,9 @@@ and shell completion generation
"""
import json
- import io
import os
import shutil
+import socket
import sys
import tarfile
import types
diff --cc tests/tools/test_bot_desktop_browser.py
index 0d2ce30188e,00000000000..61e57244bff
mode 100644,000000..100644
--- a/tests/tools/test_bot_desktop_browser.py
+++ b/tests/tools/test_bot_desktop_browser.py
@@@ -1,317 -1,0 +1,317 @@@
+"""The dock's Browser and agent-browser resolve to one identity: same executable, same user-data-dir —
+and when a human opened that browser first, the agent attaches to it instead of launching a second one
+(Chromium's profile singleton would forward the launch and kill it without a DevTools endpoint)."""
+
+from __future__ import annotations
+
+import os
+import socket
+from pathlib import Path
+
+import pytest
+
+from tools.bot_desktop import browser, runtime
+
+
+def test_dock_and_agent_share_browser_identity(tmp_path, monkeypatch):
+ exe = tmp_path / "chrome"
+ exe.write_text("#!/bin/sh\n", encoding="utf-8")
+ exe.chmod(0o755)
+ monkeypatch.setenv("AGENT_BROWSER_EXECUTABLE_PATH", str(exe))
+ monkeypatch.delenv("AGENT_BROWSER_PROFILE", raising=False)
+ monkeypatch.setattr(runtime, "state_dir", lambda: tmp_path / "bot-desktop")
+
+ dock_exe, dock_profile = browser.dock_launch()
+ agent_env = browser.env_for_agent({})
+
+ assert dock_exe == agent_env["AGENT_BROWSER_EXECUTABLE_PATH"] == str(exe)
+ assert dock_profile == agent_env["AGENT_BROWSER_PROFILE"] == str(tmp_path / "bot-desktop" / "browser-profile")
+
+
+def test_user_pinned_profile_wins(tmp_path, monkeypatch):
+ monkeypatch.setenv("AGENT_BROWSER_PROFILE", str(tmp_path / "mine"))
+ monkeypatch.setattr(runtime, "state_dir", lambda: tmp_path / "bot-desktop")
+ assert browser.profile_dir() == tmp_path / "mine"
+
+
+def test_pinned_profile_honours_tilde_and_resolves_relative_paths_against_hermes_home(tmp_path, monkeypatch):
+ """Regression for #110029: the docs say setting AGENT_BROWSER_PROFILE pins your own user-data-dir, but only
+ an absolute value was honoured — `~/pin` and `pin` silently fell back to the default and the human's dock
+ browser and the agent's browser could end up on different jars. A relative path is anchored where the rest
+ of this profile's screen state lives (its HERMES_HOME), so two profiles never share one 'pin'."""
+ home = tmp_path / "hermes-home"
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr(runtime, "get_hermes_home", lambda: home)
+ monkeypatch.setattr(Path, "home", lambda: tmp_path / "user")
+ monkeypatch.setenv("HOME", str(tmp_path / "user"))
+
+ monkeypatch.setenv("AGENT_BROWSER_PROFILE", "~/pin")
+ assert browser.profile_dir() == tmp_path / "user" / "pin"
+ monkeypatch.setenv("AGENT_BROWSER_PROFILE", "pin")
+ assert browser.profile_dir() == home / "pin"
+ assert browser.env_for_agent({})["AGENT_BROWSER_PROFILE"] == str(home / "pin"), "agent-browser gets the resolved path"
+
+
+def test_dock_browser_advertises_a_devtools_port():
+ """A human-started instance must be attachable, or the agent can never drive it afterwards."""
+ assert "--remote-debugging-port=" in browser.dock_argv("/opt/chrome", "/p/dir")[2]
+
+
+def test_dock_browser_caps_its_disk_cache():
+ """The persistent profile lives on the gateway's disk (6 GB on a hosted instance); the HTTP cache
+ must not be allowed to grow without bound there."""
+ argv = browser.dock_argv("/opt/chrome", "/p/dir")
+ cap = next(a for a in argv if a.startswith("--disk-cache-size="))
+ assert 0 < int(cap.split("=", 1)[1]) <= 512 * 1024 * 1024
+
+
+def _fake_running_instance(user_data_dir, pid: int, port: int) -> None:
+ (user_data_dir / "DevToolsActivePort").write_text(f"{port}\n/devtools/browser/abc\n", encoding="utf-8")
+ os.symlink(f"host-{pid}", user_data_dir / "SingletonLock")
+
+
+def test_running_instance_port_requires_live_pid_and_open_port(tmp_path):
+ listener = socket.socket()
+ listener.bind(("127.0.0.1", 0))
+ listener.listen(1)
+ port = listener.getsockname()[1]
+ try:
+ _fake_running_instance(tmp_path, os.getpid(), port)
+ assert browser.running_instance_cdp_port(str(tmp_path)) == port
+
+ # Both files outlive a closed Chromium: a dead pid must not be trusted.
+ os.unlink(tmp_path / "SingletonLock")
+ os.symlink("host-2147483000", tmp_path / "SingletonLock")
+ assert browser.running_instance_cdp_port(str(tmp_path)) is None
+ finally:
+ listener.close()
+ # Live pid, port no longer accepting: still not attachable.
+ os.unlink(tmp_path / "SingletonLock")
+ os.symlink(f"host-{os.getpid()}", tmp_path / "SingletonLock")
+ assert browser.running_instance_cdp_port(str(tmp_path)) is None
+ assert browser.running_instance_cdp_port(str(tmp_path / "missing")) is None
+
+
+def test_agent_attaches_to_human_started_browser(monkeypatch):
+ """With a live dock instance on the shared profile the local argv carries ``--cdp <port>``; without one
+ it stays a plain ``--session`` launch."""
+ from tools import browser_tool_session as session
+
+ monkeypatch.setattr(runtime, "published_env", lambda: {"DISPLAY": ":37"})
+ monkeypatch.setattr(session._cloud, "_get_browser_engine", lambda: "auto")
+ monkeypatch.setattr(session._cloud, "_is_headed_mode", lambda: False)
+ monkeypatch.setattr(session, "_agent_browser_argv", lambda cmd: [cmd])
+ argvs: list = []
+
+ def spawn(task_id, session_info, cmd_parts, *rest):
+ argvs.append(cmd_parts)
+ return {"success": True}
+
+ monkeypatch.setattr(session, "_spawn_and_collect", spawn)
+ monkeypatch.setattr(session._lp, "_lightpanda_fallback_reason", lambda *a: None)
+ info = {"session_name": "h_abc", "cdp_url": None, "features": {"local": True}}
+
+ monkeypatch.setattr(browser, "running_instance_cdp_port", lambda d, **kw: 41234)
- session._run_browser_command_unfenced("t", "open", ["https://x"], 10, None, "agent-browser", info)
++ session._dispatch_browser_command("t", info, "agent-browser", "open", ["https://x"], 10, None)
+ assert argvs[-1][:5] == ["agent-browser", "--session", "h_abc", "--cdp", "41234"]
+
+ monkeypatch.setattr(browser, "running_instance_cdp_port", lambda d, **kw: None)
- session._run_browser_command_unfenced("t", "open", ["https://x"], 10, None, "agent-browser", info)
++ session._dispatch_browser_command("t", info, "agent-browser", "open", ["https://x"], 10, None)
+ assert "--cdp" not in argvs[-1] and argvs[-1][:3] == ["agent-browser", "--session", "h_abc"]
+
+
+def _install_browsers(tmp_path, monkeypatch, *, playwright: bool, system: bool):
+ """A Playwright build under a private PLAYWRIGHT_BROWSERS_PATH and/or a system chromium on PATH."""
+ monkeypatch.delenv("AGENT_BROWSER_EXECUTABLE_PATH", raising=False)
+ roots = tmp_path / "pw"
+ roots.mkdir(parents=True)
+ monkeypatch.setenv("PLAYWRIGHT_BROWSERS_PATH", str(roots))
+ monkeypatch.setattr("tools.browser_tool_install._chromium_search_roots", lambda: [str(roots)])
+ pw_exe = roots / "chromium-1200" / "chrome-linux" / "chrome"
+ if playwright:
+ pw_exe.parent.mkdir(parents=True)
+ pw_exe.write_text("#!/bin/sh\n", encoding="utf-8")
+ pw_exe.chmod(0o755)
+ sys_exe = tmp_path / "bin" / "chromium"
+ if system:
+ sys_exe.parent.mkdir(parents=True)
+ sys_exe.write_text("#!/bin/sh\n", encoding="utf-8")
+ sys_exe.chmod(0o755)
+ monkeypatch.setattr("shutil.which", lambda name, *a, **k: str(sys_exe) if system and name == "chromium" else None)
+ return str(pw_exe), str(sys_exe)
+
+
+def test_unprivileged_user_under_apparmor_userns_restriction_gets_the_system_browser(tmp_path, monkeypatch):
+ """Playwright's bundled Chromium has no setuid chrome_sandbox; with
+ kernel.apparmor_restrict_unprivileged_userns=1 it dies 'FATAL: No usable sandbox!' for a non-root user,
+ so the dock icon is dead. A distro chromium (which ships the sandbox helper) must win there — and
+ the Playwright build stays the answer when it is the only one, started with exactly the flags
+ agent-browser starts it with on that host (one sandbox policy for the human's and the bot's browser)."""
+ pw_exe, sys_exe = _install_browsers(tmp_path, monkeypatch, playwright=True, system=True)
+ monkeypatch.setattr(browser.os, "geteuid", lambda: 1000)
+ monkeypatch.setattr(browser, "_userns_restricted", lambda: True)
+ assert browser.executable() == sys_exe
+
+ monkeypatch.setattr(browser, "_userns_restricted", lambda: False)
+ assert browser.executable() == pw_exe # unrestricted host: Playwright's build as before
+
+ _install_browsers(tmp_path / "only-pw", monkeypatch, playwright=True, system=False)
+ monkeypatch.setattr(browser, "_userns_restricted", lambda: True)
+ exe = browser.executable()
+ assert exe and exe.endswith("chrome-linux/chrome")
+ from tools import browser_tool_session as session
+
+ agent_env: dict = {}
+ session._apply_chromium_sandbox_args(agent_env)
+ agent_flags = set(agent_env.get("AGENT_BROWSER_ARGS", "").split(",")) - {""}
+ assert agent_flags <= set(browser.dock_argv(exe, "/p/dir"))
+ assert ("--no-sandbox" in browser.dock_argv(exe, "/p/dir")) == ("--no-sandbox" in agent_flags)
+
+
+def test_root_dock_browser_starts_with_the_same_sandbox_args_as_the_agents_browser(monkeypatch):
+ """Chromium refuses to start as root without --no-sandbox; agent-browser gets that flag from one
+ policy, and the dock icon (same binary, same profile) must get the very same flags or the human's
+ click dies while the agent's launch works."""
+ from tools import browser_tool_session as session
+
+ monkeypatch.setattr(session.os, "geteuid", lambda: 0)
+ monkeypatch.setattr(browser.os, "geteuid", lambda: 0)
+ agent_env: dict = {}
+ session._apply_chromium_sandbox_args(agent_env)
+ agent_flags = set(agent_env["AGENT_BROWSER_ARGS"].split(","))
+ assert agent_flags, "root must inject sandbox flags for agent-browser"
+ assert agent_flags <= set(browser.dock_argv("/opt/chrome", "/p/dir"))
+
+ # Same policy for the NON-root container case (the official image runs the gateway as uid 10000 in
+ # Docker): agent-browser bypasses the sandbox there, and the dock icon must too or it dies on click.
+ monkeypatch.setattr(session.os, "geteuid", lambda: 10000)
+ monkeypatch.setattr(browser.os, "geteuid", lambda: 10000)
+ monkeypatch.setattr(session._install, "_running_in_docker", lambda: True)
+ docker_env: dict = {}
+ session._apply_chromium_sandbox_args(docker_env)
+ assert set(docker_env["AGENT_BROWSER_ARGS"].split(",")) <= set(browser.dock_argv("/opt/chrome", "/p/dir"))
+ monkeypatch.setattr(session._install, "_running_in_docker", lambda: False)
+ monkeypatch.setattr(session, "apparmor_restricts_unprivileged_userns", lambda: False)
+ assert "--no-sandbox" not in browser.dock_argv("/opt/chrome", "/p/dir") # seated non-root host: sandboxed
+
+
+def test_status_reports_the_headed_browser_or_its_absence(monkeypatch):
+ """The official image ships only chromium_headless_shell: executable() is None and the dock silently
+ has no Browser icon. Status must say so instead of leaving the pane to guess. The subject is the
+ browser field, not host policy: status() gates it on is_supported_host(), which is pinned True so the
+ test means the same thing on every CI lane."""
+ monkeypatch.setattr(runtime, "is_supported_host", lambda: True)
+ monkeypatch.setattr(runtime, "_launcher_pid", lambda: None)
+ monkeypatch.setattr(runtime, "published_env", lambda: {})
+ monkeypatch.setattr(runtime, "geometry", lambda: "1440x900")
+ monkeypatch.setattr(browser, "executable", lambda: None)
+ assert runtime.status().as_dict()["browser"] is None
+ monkeypatch.setattr(browser, "executable", lambda: "/usr/bin/chromium")
+ assert runtime.status().browser == "/usr/bin/chromium"
+
+
+def test_dock_exec_line_survives_spaces_in_the_executable_and_profile_paths():
+ """The launcher used to split the shell line on the first space to find the executable, so a
+ Chromium under '/opt/Google Chrome/' or a profile under a spaced HERMES_HOME broke the dock icon.
+ Exec= follows the Desktop Entry spec: each argument double-quoted, with the reserved characters
+ backslash-escaped inside the quotes."""
+ exe = "/opt/Google Chrome/chrome"
+ profile = '/home/a b/.hermes/browser "x"/profile'
+ line = browser.dock_exec_line(exe, profile)
+ assert line.startswith('Exec="/opt/Google Chrome/chrome" ')
+ assert r'"--user-data-dir=/home/a b/.hermes/browser \\"x\\"/profile"' in line # spec: \" quoted, then \ string-escaped
+ assert "--remote-debugging-port=0" in line
+
+
+def test_headless_shell_override_is_not_a_headed_browser(tmp_path, monkeypatch):
+ """The official Docker image ships only Playwright's chrome-headless-shell and its boot hook exports it
+ as AGENT_BROWSER_EXECUTABLE_PATH. That binary cannot open a window: taken at face value the dock's
+ Browser icon would point at it and status would claim a headed browser exists. Live in the image:
+ status.browser named the headless shell while the dock had no working Browser."""
+ shell = tmp_path / "shell" / "chromium_headless_shell-1243" / "chrome-headless-shell-linux64" / "chrome-headless-shell"
+ shell.parent.mkdir(parents=True)
+ shell.write_text("#!/bin/sh\n", encoding="utf-8")
+ shell.chmod(0o755)
+ _install_browsers(tmp_path, monkeypatch, playwright=False, system=False)
+ monkeypatch.setenv("AGENT_BROWSER_EXECUTABLE_PATH", str(shell))
+ assert browser.executable() is None
+
+ _, sys_exe = _install_browsers(tmp_path / "with-sys", monkeypatch, playwright=False, system=True)
+ monkeypatch.setenv("AGENT_BROWSER_EXECUTABLE_PATH", str(shell))
+ assert browser.executable() == sys_exe # a real headed browser elsewhere still wins over the override
+
+
[email protected]("engine, headed, starts", [("chrome", True, 1), ("chrome", False, 0), ("lightpanda", True, 0)])
+def test_headed_chromium_spawn_asks_the_screen_to_start_but_the_env_builder_never_does(tmp_path, monkeypatch, engine, headed, starts):
+ """Regression for #110050 at the right boundary: a real browser command that forks a headed Chromium daemon
+ starts the profile's screen (bot_desktop.auto_start) like computer_use dispatch does; `_build_browser_env()`
+ itself stays pure — it also serves the npx cache warmer, the Chromium auto-installer and the Lightpanda
+ engine, none of which may block on Xvnc+Xfce coming up."""
+ from tools import browser_tool as bt
+ from tools import browser_tool_cloud as cloud
+ from tools import browser_tool_session as session
+
+ calls: list = []
+ monkeypatch.setattr(runtime, "ensure_started_for_tool", lambda: calls.append(1))
+ monkeypatch.setattr(runtime, "published_env", lambda: {})
+ monkeypatch.setattr(cloud, "_is_headed_mode", lambda: headed)
+ bt._build_browser_env()
+ assert calls == []
+
+ class _Done:
+ returncode = 0
+ def wait(self, timeout=None): return 0
+ def _fake_popen(argv, env, socket_dir, tag, stdin_payload=None):
+ for slot in ("stdout", "stderr"):
+ Path(socket_dir, f"_{slot}_{tag}").write_text("{}" if slot == "stdout" else "")
+ return _Done()
+ monkeypatch.setattr(session, "_popen_agent_browser", _fake_popen)
+ monkeypatch.setattr(session, "_prepare_session_socket_dir", lambda name: str(tmp_path))
+ session._spawn_and_collect("t", {"session_name": "h_x"}, ["agent-browser"], "open", engine, 5)
+ assert len(calls) == starts
+
+
+def test_janitor_keeps_the_shared_browser_alive_while_a_human_holds_the_lease(monkeypatch):
+ """#110064: the agent goes idle BECAUSE the human took over to log in; the janitor must count the human's
+ lease as activity for the shared local browser, and reap it again once the lease is handed back."""
+ from tools import browser_tool_lifecycle as lifecycle, browser_tool_session as session
+ from tools.bot_desktop import lease
+
+ monkeypatch.setattr(runtime, "published_env", lambda: {"DISPLAY": ":37"})
+ holder = {"human": True}
+ monkeypatch.setattr(lease, "human_holds", lambda *a, **k: holder["human"])
+ reaped: list = []
+ monkeypatch.setattr(lifecycle, "cleanup_browser", lambda task_id: reaped.append(task_id))
+ monkeypatch.setattr(lifecycle._bt, "BROWSER_SESSION_INACTIVITY_TIMEOUT", 1)
+ monkeypatch.setattr(lifecycle._bt, "_active_sessions", {
+ "bot": {"session_name": "h_bot", "features": {"local": True}},
+ "cloud": {"session_name": "c_1", "bb_session_id": "bb", "features": {}},
+ })
+ monkeypatch.setattr(lifecycle._bt, "_session_last_activity", {"bot": 0.0, "cloud": 0.0})
+ monkeypatch.setattr(lifecycle._bt, "_session_owner_homes", {})
+
+ lifecycle._cleanup_inactive_browser_sessions()
+ assert reaped == ["cloud"], "only the browser the human is not typing into may be reaped"
+ assert lifecycle._bt._session_last_activity["bot"] > 0, "the human's lease refreshed the bot browser's activity"
+
+ holder["human"] = False
+ lifecycle._bt._session_last_activity["bot"] = 0.0
+ lifecycle._cleanup_inactive_browser_sessions()
+ assert reaped == ["cloud", "bot"]
+ assert session.human_holds_shared_browser({"features": {"local": True}}) is False
+
+
+def test_daemon_idle_timer_defers_to_the_janitor_only_for_the_shared_headed_browser(monkeypatch):
+ """The agent-browser daemon cannot see the lease, so on the Bot Desktop its self-termination timer steps
+ back and the lease-aware janitor owns the browser's lifetime; headless browsing keeps the mirror."""
+ from tools import browser_tool_session as session
+
+ monkeypatch.setattr(session._bt, "BROWSER_SESSION_INACTIVITY_TIMEOUT", 120)
+ monkeypatch.setattr(runtime, "published_env", lambda: {"DISPLAY": ":37"})
+ monkeypatch.setattr(session._cloud, "_is_headed_mode", lambda: True)
+ assert session._daemon_idle_timeout_seconds() > 120
+ monkeypatch.setattr(session._cloud, "_is_headed_mode", lambda: False)
+ assert session._daemon_idle_timeout_seconds() == 120
+ monkeypatch.setattr(session._cloud, "_is_headed_mode", lambda: True)
+ monkeypatch.setattr(runtime, "published_env", lambda: {})
+ assert session._daemon_idle_timeout_seconds() == 120
diff --cc tools/browser_tool_session.py
index bfdce8b8ad3,2c4e3496a45..4baf9b42d34
--- a/tools/browser_tool_session.py
+++ b/tools/browser_tool_session.py
@@@ -639,80 -605,11 +653,68 @@@ def _spawn_and_collect
return _interpret_browser_command_output(command, stdout, stderr, proc.returncode)
- def _run_browser_command(
- task_id: str,
- command: str,
- args: List[str] = None,
- timeout: Optional[int] = None,
- _engine_override: Optional[str] = None,
- ) -> Dict[str, Any]:
- """Run one agent-browser CLI command against the task's session; returns its parsed JSON.
- ``timeout=None`` reads ``browser.command_timeout``; ``_engine_override`` forces an engine
- for this call only (Lightpanda fallback retries with Chrome without touching global state)."""
- if timeout is None:
- timeout = _bt._safe_command_timeout()
- args = args or []
-
- preflight = _browser_command_preflight()
- if "browser_cmd" not in preflight:
- return preflight
- browser_cmd = preflight["browser_cmd"]
-
- try:
- session_info = _get_session_info(task_id)
- except Exception as e:
- _bt.logger.warning("Failed to create browser session for task=%s: %s", task_id, e)
- return {"success": False, "error": f"Failed to create browser session: {str(e)}"}
- return run_fenced(session_info, lambda: _run_browser_command_unfenced(
- task_id, command, args, timeout, _engine_override, browser_cmd, session_info))
-
-
+def run_fenced(session_info: Dict[str, Any], fn: Callable[[], Dict[str, Any]]) -> Dict[str, Any]:
+ """Run ``fn`` under the Bot Desktop lease fence when ``session_info`` is the bot's LOCAL browser.
+
+ That browser lives on the Bot Desktop screen, in the same profile a human who took over is typing
+ into. While the human holds the lease every action AND read against it is refused (the page may show
+ their credential); the fence brackets the whole run so a takeover mid-command also voids the result.
+ Cloud / user-supplied CDP sessions are a different browser and run unfenced. This is THE fence: every
+ path that reaches the page (agent-browser subprocess, CDP supervisor fast path) goes through here.
+ """
+ if not _shares_bot_desktop_browser(session_info):
+ return fn()
+ from tools.bot_desktop import lease as _bd_lease
+ try:
+ admitted = _bd_lease.assert_agent_may_act()
+ except _bd_lease.HumanHasControl as e:
+ return {"success": False, "error": str(e), "code": "human_has_control"}
+ result = fn()
+ if _bd_lease.get().epoch != admitted.epoch:
+ return {"success": False, "code": "human_has_control",
+ "error": "A human took over the bot's screen while this browser command ran; its result was "
+ "discarded. Tell the user what you need; retry once they hand back."}
+ return result
+
+
++def run_fenced_pair(session_info: Dict[str, Any], fn: Callable[[], "tuple[str, Dict[str, Any]]"]) -> "tuple[str, Dict[str, Any]]":
++ """``run_fenced`` for the dispatch shape ``(engine, result)``; a refusal carries no engine (never ran)."""
++ engine_box: list = []
++
++ def _call() -> Dict[str, Any]:
++ engine, result = fn()
++ engine_box.append(engine)
++ return result
++
++ result = run_fenced(session_info, _call)
++ return (engine_box[0] if engine_box else "auto"), result
++
++
+def _shares_bot_desktop_browser(session_info: Dict[str, Any]) -> bool:
+ """Decided by provenance, not transport: every LOCAL session (plain ``--session``, real-profile CDP
+ attach, Lightpanda) is a browser Hermes launched with this profile's Bot Desktop DISPLAY, so it is the
+ screen a human who took over is typing into. Cloud / user-supplied CDP sessions are another browser.
+ A human lease with the screen already gone (dead Xvnc) still fences — computer_use does the same."""
+ if not (session_info.get("features") or {}).get("local"):
+ return False
+ from tools.bot_desktop import lease as _bd_lease, runtime as _bd_runtime
+ return bool(_bd_runtime.published_env().get("DISPLAY")) or _bd_lease.human_holds()
+
+
+def _bot_desktop_attach_port(session_info: Dict[str, Any]) -> Optional[int]:
+ """DevTools port of a human-started Chromium on the Bot Desktop's shared profile, else ``None``."""
+ if not _shares_bot_desktop_browser(session_info):
+ return None
+ from tools.bot_desktop import browser as _bd_browser
+ return _bd_browser.running_instance_cdp_port(str(_bd_browser.profile_dir()),
+ exclude_session=session_info["session_name"])
+
+
- def _run_browser_command_unfenced(task_id: str, command: str, args: List[str], timeout: int,
- _engine_override: Optional[str], browser_cmd, session_info: Dict[str, Any]) -> Dict[str, Any]:
+ def _dispatch_browser_command(
+ task_id: str, session_info: Dict[str, Any], browser_cmd: str, command: str, args: List[str],
+ timeout: int, _engine_override: Optional[str],
+ ) -> "tuple[str, Dict[str, Any]]":
+ """Build the agent-browser argv for ``session_info`` and run it once → ``(engine, result)``."""
# Cleanup stops the supervisor before closing the backend; keep it stopped.
if command != "close" and session_info.get("cdp_url"):
_cdp._ensure_cdp_supervisor(task_id)
@@@ -747,6 -638,48 +749,50 @@@
except Exception as e:
_bt.logger.warning("browser '%s' exception: %s", command, e, exc_info=True)
result = {"success": False, "error": str(e)}
+ return engine, result
+
+
+ def _run_browser_command(
+ task_id: str,
+ command: str,
+ args: List[str] = None,
+ timeout: Optional[int] = None,
+ _engine_override: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """Run one agent-browser CLI command against the task's session; returns its parsed JSON.
+ ``timeout=None`` reads ``browser.command_timeout``; ``_engine_override`` forces an engine
+ for this call only (Lightpanda fallback retries with Chrome without touching global state)."""
+ if timeout is None:
+ timeout = _bt._safe_command_timeout()
+ args = args or []
+
+ preflight = _browser_command_preflight()
+ if "browser_cmd" not in preflight:
+ return preflight
+ browser_cmd = preflight["browser_cmd"]
+
+ for attempt in range(2):
+ try:
+ session_info = _get_session_info(task_id)
+ except Exception as e:
+ _bt.logger.warning("Failed to create browser session for task=%s: %s", task_id, e)
+ return {"success": False, "error": f"Failed to create browser session: {str(e)}"}
- engine, result = _dispatch_browser_command(task_id, session_info, browser_cmd, command, args, timeout,
- _engine_override)
++ engine, result = run_fenced_pair(session_info, lambda: _dispatch_browser_command(
++ task_id, session_info, browser_cmd, command, args, timeout, _engine_override))
++ if result.get("code") == "human_has_control":
++ return result
+ # #115184: a protocol-level failure (exit 101 on a stale session daemon, empty/non-JSON
+ # output) poisons the cached local session record exactly like a timeout — recycle it
+ # the same way and retry once on the replacement before handing the caller the error.
+ # ``close`` is exempt: a dead daemon is already closed, and cleanup must never spawn
+ # a fresh session just to close it.
+ if attempt == 0 and command != "close" and _is_recoverable_local_backend_failure(session_info, result):
+ _bt.logger.warning("browser '%s' failed at the backend level (task=%s, rc=%s); recycling the session "
+ "and retrying once", command, task_id, result.get("returncode"))
+ _recycle_local_session(task_id, session_info, _prepare_session_socket_dir(session_info["session_name"]),
+ f"agent-browser '{command}' exited {result.get('returncode')}")
+ continue
+ break
# Lightpanda automatic Chrome fallback — runs for ALL exit paths (timeout,
# empty, non-JSON, nonzero rc, parsed).
diff --cc tui_gateway/contracts/__init__.py
index cfd3c95f3d9,58715d76c2e..06074b02b9a
--- a/tui_gateway/contracts/__init__.py
+++ b/tui_gateway/contracts/__init__.py
@@@ -5,8 -5,8 +5,9 @@@ from . import ( # noqa: F40
billing_delegation_pets,
common,
config_free_tier_control,
+ connectors,
connectors_operation,
+ display,
events,
groups_bot_relay,
liveness,
diff --cc tui_gateway/server.py
index 27669965e56,cb7db335aec..ae2d0297a6e
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@@ -3304,8 -3341,8 +3341,9 @@@ from . import ( # noqa: E40
methods_projects as _methods_projects, methods_session_foreign as _methods_session_foreign,
methods_session_control as _methods_session_control, methods_subagents as _methods_subagents,
methods_vault as _methods_vault, methods_free_tier as _methods_free_tier,
- methods_connectors as _methods_connectors, methods_display as _methods_display,
- methods_display_watch as _methods_display_watch)
+ methods_connectors as _methods_connectors, methods_connectors_account as _methods_connectors_account,
++ methods_display as _methods_display, methods_display_watch as _methods_display_watch,
+ methods_onboarding as _methods_onboarding)
for _m in (
_session_transports, _session_reaper, _session_lifecycle, _session_workdir, _compute_host_bridge, _model_switch,
@@@ -3316,6 -3353,6 +3354,6 @@@
_methods_config_set, _methods_complete, _methods_tools, _methods_profiles, _methods_images,
_methods_bot_relay, _prompt_turn, _billing_view, _methods_projects, _methods_session_foreign,
_methods_session_control, _methods_subagents, _methods_vault, _methods_free_tier, _methods_connectors,
- _methods_display, _methods_display_watch):
- _methods_connectors_account, _methods_onboarding):
++ _methods_connectors_account, _methods_display, _methods_display_watch, _methods_onboarding):
_m.register(sys.modules[__name__])
del _m