The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge remote-tracking branch 'origin/main' into ethie/pm-clean
ethernet3f4b8840f191
diff --cc Dockerfileindex 2837d5572b5,1fece52ce77..b8e24a1d87e--- a/Dockerfile+++ b/Dockerfile@@@ -64,18 -68,26 +64,33 @@@ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/herme# replaces tini with s6-overlay's /init (PID 1 = s6-svscan), which reaps# zombies non-blockingly on SIGCHLD and additionally supervises the main# hermes process, the dashboard, and per-profile gateways.+# The second package list is the shared libraries the pinned Chromium links+# against. `npx playwright install --with-deps` used to apt-install them as+# a side effect; pm stages the pinned browser instead (below), so the libs+# must be declared here. The list is the `ldd ... | grep "not found"` set of+# the pinned chrome binary in this base image, mapped to trixie package+# names (see .hermes/plans/termux-removal-commit-spec.md).RUN apt-get -o Acquire::Retries=3 update && \apt-get -o Acquire::Retries=3 install -y --no-install-recommends \- ca-certificates curl iputils-ping python3 python-is-python3 ripgrep ffmpeg gcc g++ make cmake python3-dev python3-venv libffi-dev libolm-dev libatomic1 procps git openssh-client docker-cli xz-utils && \+ ca-certificates curl iputils-ping python3 python-is-python3 ripgrep ffmpeg gcc g++ make cmake python3-dev python3-venv libffi-dev libolm-dev libatomic1 procps git openssh-client docker-cli xz-utils \+ libasound2t64 libatk-bridge2.0-0t64 libatk1.0-0t64 libatspi2.0-0t64 libcairo2 libcups2t64 libdbus-1-3 libgbm1 libglib2.0-0t64 libnspr4 libnss3 libpango-1.0-0 libx11-6 libxcb1 libxcomposite1 libxdamage1 libxext6 libxfixes3 libxkbcommon0 libxrandr2 && \rm -rf /var/lib/apt/lists/*+ # Bot Screen (opt-in): TigerVNC + the Xfce components + a headed chromium, so a+ # container that cannot run apt at run time (unprivileged user, no sudo — every+ # hosted instance) can still stream a desktop. ~550 MB. Nothing here starts at+ # boot; the layer costs no memory until a screen is started. Same package list+ # as tools/bot_desktop/runtime.py::PACKAGES["apt"].+ # docker build --build-arg HERMES_BOT_DESKTOP=1 .+ ARG HERMES_BOT_DESKTOP=0+ RUN if [ "$HERMES_BOT_DESKTOP" = "1" ]; then \+ apt-get -o Acquire::Retries=3 update && \+ DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=3 install -y --no-install-recommends \+ tigervnc-standalone-server xfce4-panel xfwm4 xfdesktop4 xfce4-settings xfce4-terminal \+ dbus-x11 x11-xserver-utils x11-utils x11-xkb-utils xauth fonts-dejavu-core chromium && \+ rm -rf /var/lib/apt/lists/*; \+ fi+# Prefer the fixed SQLite over Debian's vulnerable libsqlite3.so.0. Keep the# public library name stable so both the system interpreter and the uv-created# venv resolve the replacement without changing Python import paths.diff --cc apps/desktop/e2e/bot-screen-stale-status-reply.spec.tsindex 00000000000,0f9730efc0b..2e77a036817mode 000000,100644..100644--- a/apps/desktop/e2e/bot-screen-stale-status-reply.spec.ts+++ b/apps/desktop/e2e/bot-screen-stale-status-reply.spec.ts@@@ -1,0 -1,296 +1,299 @@@+ import fs from 'node:fs'+ import path from 'node:path'+++import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'+ import { startMockServer } from '../../../tests-js/scripts/mock-server'++ import {+ buildAppEnv,+ createSandbox,+ launchDesktop,+ type MockBackendFixture,- waitForAppReady,- writeEnvFile,- writeMockProviderConfig++ waitForAppReady+ } from './fixtures'+ import { RealSessionBuilder } from './real-session-builder'+ import { expect, test } from './test'++ // Bot Screen portal vs. a slow `display.status` reply, in the real Electron app.+ //+ // The Screen hero (the portal above a bot's routines) fetches `display.status`+ // once on mount; opening the Screen pane fetches it again. The renderer keeps a+ // per-bot generation so a reply that a NEWER request overtook is dropped. Before+ // the fix the portal's reply carried no request token, so `setScreenStatus`+ // treated it as authoritative: it landed as truth AND bumped the generation,+ // which dropped the pane's newer `running: false` — the hero kept saying+ // "Live · bot in control" (running/pid/display of a screen that had stopped)+ // and the pane attached to a dead display.+ //+ // The gateway's answer to `display.status` is the only thing scripted here:+ // `WebSocket.prototype.send` holds the two requests and the test answers them+ // through the real JSON-RPC client in the order the bug needs (portal's stale+ // `running: true` first, pane's fresh `running: false` second). Everything else+ // — roster, routines pane, hero, pane, store, listeners — is the shipped renderer.+ //+ // The orphan-row branch (a source-scoped row whose connection was deleted) is+ // not reachable in this single-local-source rig: `window.hermesDesktop` is a+ // non-writable contextBridge object, so the union roster cannot be seeded with+ // a connection-less agent. That branch stays covered by+ // `src/plugins/hermes-bots/screen-connection.test.ts`; the second test here+ // drives the same shipped `display.lease` / `display.status` listeners with+ // pushed events through the real client and asserts they keep updating without+ // a page error.++ type Page = MockBackendFixture['page']++ interface ScreenProbe {+ held: Array<{ id: string | number }>+ log: string[]+ }++ let fixture: MockBackendFixture | null = null+ const pageErrors: string[] = []++ // BOT_SCREEN_SCREENSHOT_DIR=<dir> saves full-window captures at the key states.+ async function capture(page: Page, name: string): Promise<void> {+ const dir = process.env.BOT_SCREEN_SCREENSHOT_DIR++ if (!dir) {+ return+ }++ fs.mkdirSync(dir, { recursive: true })+ await page.screenshot({ path: path.join(dir, `${name}.png`) })+ }++ async function seedBot(hermesHome: string, mockUrl: string, name: string): Promise<void> {+ const dir = path.join(hermesHome, 'profiles', name)+ fs.mkdirSync(dir, { recursive: true })+ writeMockProviderConfig(dir, mockUrl)+ writeEnvFile(dir)++ const builder = await RealSessionBuilder.start(dir)++ try {+ await builder.createSession({ title: 'Bot Chat', turns: [`Hello ${name}`] })+ } finally {+ await builder.close()+ }+ }++ const PROFILE_KEY = '/e2e/alpha/.hermes'++ function snapshot(running: boolean) {+ return {+ profile: 'alpha',+ profile_key: PROFILE_KEY,+ supported: true,+ installed: true,+ missing: [],+ running,+ pid: running ? 4242 : null,+ display: running ? ':7' : null,+ socket: null,+ geometry: '1280x800',+ install_command: null,+ browser: null,+ lease: { holder: 'agent', viewer_id: null, viewer_hash: null, since: 1, epoch: 1, reason: '' }+ }+ }++ /** Hold every outgoing `display.status` request; answer / push events through the real client. */+ async function installScreenProbe(page: Page): Promise<void> {+ await page.evaluate(() => {+ if ((window as unknown as { __screenProbe?: unknown }).__screenProbe) {+ return+ }++ const held: Array<{ id: unknown; socket: WebSocket }> = []+ const log: string[] = []+ let lastSocket: WebSocket | null = null+ const send = WebSocket.prototype.send++ WebSocket.prototype.send = function (this: WebSocket, text: Parameters<WebSocket['send']>[0]) {+ lastSocket = this++ try {+ const frame = JSON.parse(String(text)) as { id?: unknown; method?: string }++ if (frame?.method === 'display.status') {+ held.push({ id: frame.id, socket: this })+ log.push(`held display.status #${String(frame.id)}`)++ return+ }+ } catch {+ // binary / non-JSON frames pass through untouched+ }++ return send.call(this, text)+ }++ const deliver = (socket: WebSocket, frame: Record<string, unknown>) =>+ socket.dispatchEvent(new MessageEvent('message', { data: JSON.stringify({ jsonrpc: '2.0', ...frame }) }))++ ;(window as unknown as { __screenProbe: unknown }).__screenProbe = {+ held,+ log,+ answer(index: number, result: unknown) {+ const request = held[index]+ log.push(`answered #${String(request.id)} running=${String((result as { running?: boolean }).running)}`)+ deliver(request.socket, { id: request.id, result })+ },+ event(type: string, payload: unknown) {+ const socket = held[0]?.socket ?? lastSocket++ if (!socket) {+ throw new Error('no gateway socket has sent a frame yet')+ }++ log.push(`event ${type}`)+ deliver(socket, { method: 'event', params: { type, payload, session_id: '' } })+ }+ }+ })+ }++ const probe = (page: Page) => page.evaluate(() => {+ const state = (window as unknown as { __screenProbe: ScreenProbe }).__screenProbe++ return { held: state.held.length, log: [...state.log] }+ })++ const answer = (page: Page, index: number, result: unknown) =>+ page.evaluate(([i, r]) => (window as unknown as { __screenProbe: { answer: (i: number, r: unknown) => void } }).__screenProbe.answer(i, r), [index, result] as const)++ const pushEvent = (page: Page, type: string, payload: unknown) =>+ page.evaluate(([t, p]) => (window as unknown as { __screenProbe: { event: (t: string, p: unknown) => void } }).__screenProbe.event(t, p), [type, payload] as const)++ const hero = (page: Page) => page.locator('button[aria-label^="Screen:"]').first()+++async function revealScreenHero(page: Page): Promise<void> {++ const tab = page++ .getByRole('button', { name: 'Bots', exact: true })++ .or(page.getByRole('tab', { name: 'Bots', exact: true }))++ .first()++++ await tab.click()++ await expect(page.getByRole('button', { name: 'New bot or group chat' })).toBeVisible()++++ const row = page.locator('[data-slot="bots-roster"] [data-roster-key="local::alpha"]')++ await expect(row).toBeVisible({ timeout: 30_000 })++++ for (let attempt = 1; ; attempt += 1) {++ await row.click()++++ try {++ await expect(page.getByText('Hello alpha', { exact: true }).filter({ visible: true }).first()).toBeVisible({ timeout: 45_000 })++++ break++ } catch (error) {++ if (attempt >= 3) {++ throw error++ }++ }++ }++++ await page++ .getByText(/Waking up/i)++ .first()++ .waitFor({ state: 'hidden', timeout: 90_000 })++ .catch(() => undefined)++++ if ((await hero(page).count()) === 0) {++ await page.getByRole('tab', { name: 'Scheduled jobs' }).first().click()++ }++}+++ test.beforeAll(async () => {+ const mock = await startMockServer()+ const sandbox = createSandbox('bots-screen-stale')+ writeMockProviderConfig(sandbox.hermesHome, mock.url)+ writeEnvFile(sandbox.hermesHome)+ await seedBot(sandbox.hermesHome, mock.url, 'alpha')++ const { app, page } = await launchDesktop(buildAppEnv(sandbox))+ page.on('pageerror', error => pageErrors.push(String(error)))++ fixture = {+ app,+ page,+ mock,+ mockUrl: mock.url,+ sandbox,+ cleanup: async () => {+ await app.close().catch(() => undefined)+ await mock.close()+ sandbox.cleanup()+ }+ }+ await waitForAppReady(fixture, 120_000)+ })++ test.afterAll(async () => {+ await fixture?.cleanup()+ fixture = null+ })++ test('a stale portal display.status reply does not roll back the newer stopped state', async () => {+ test.setTimeout(300_000)+ const page = fixture!.page++ await installScreenProbe(page)-- const tab = page- .getByRole('button', { name: 'Bots', exact: true })- .or(page.getByRole('tab', { name: 'Bots', exact: true }))- .first()-- await tab.click()- await expect(page.getByRole('button', { name: 'New bot or group chat' })).toBeVisible()-- const row = page.locator('[data-slot="bots-roster"] [data-roster-key="local::alpha"]')- await expect(row).toBeVisible({ timeout: 30_000 })-- for (let attempt = 1; ; attempt += 1) {- await row.click()-- try {- await expect(page.getByText('Hello alpha', { exact: true }).filter({ visible: true }).first()).toBeVisible({ timeout: 45_000 })-- break- } catch (error) {- if (attempt >= 3) {- throw error- }- }- }-- await page- .getByText(/Waking up/i)- .first()- .waitFor({ state: 'hidden', timeout: 90_000 })- .catch(() => undefined)-+ // Reveal the routines pane: the Screen hero mounts and fires the portal's one-shot fetch.- if ((await hero(page).count()) === 0) {- await page.getByRole('tab', { name: 'Scheduled jobs' }).first().click()- }++ await revealScreenHero(page)++ await expect(hero(page)).toHaveAttribute('aria-label', 'Screen: Checking the screen…', { timeout: 15_000 })+ await expect.poll(async () => (await probe(page)).held, { timeout: 15_000 }).toBe(1)+ await capture(page, '1-hero-fetch-in-flight')++ // Open the pane: its own (newer) display.status request goes out while the portal's is still open.+ await hero(page).click()+ await expect.poll(async () => (await probe(page)).held, { timeout: 15_000 }).toBe(2)++ // The portal's older reply lands first and describes a screen that has since been+ // stopped; the pane's newer reply says so. Only the newer one may win.+ await answer(page, 0, snapshot(true))+ await answer(page, 1, snapshot(false))+ await page.waitForTimeout(1000)+ await capture(page, '2-after-stale-reply')++ await expect(hero(page)).toHaveAttribute('aria-label', 'Screen: Screen is off', { timeout: 10_000 })+ await expect(page.getByText('Screen is off', { exact: true }).filter({ visible: true }).first()).toBeVisible()+ await expect(page.getByRole('button', { name: 'Start screen' })).toBeVisible()++ // Belt and braces: it stays stopped — nothing later "corrects" back to live.+ await page.waitForTimeout(1500)+ await expect(hero(page)).toHaveAttribute('aria-label', 'Screen: Screen is off')+ expect(pageErrors).toEqual([])+ })++ test('pushed display.status / display.lease events keep updating the shipped listeners without a page error', async () => {+ test.setTimeout(120_000)+ const page = fixture!.page++ await installScreenProbe(page)++ await revealScreenHero(page)+ await expect(hero(page)).toBeVisible({ timeout: 15_000 })++ // A start made outside this window is pushed as a token-less status: authoritative.+ await pushEvent(page, 'display.status', snapshot(true))+ await expect(hero(page)).toHaveAttribute('aria-label', 'Screen: Live · bot in control', { timeout: 10_000 })++ // An event for another screen (different profile_key) is ignored by every listener.+ await pushEvent(page, 'display.lease', {+ profile_key: '/e2e/other/.hermes',+ lease: { holder: 'human', viewer_id: null, viewer_hash: 'someone-else', since: 2, epoch: 2, reason: '' }+ })+ await page.waitForTimeout(500)+ await expect(hero(page)).toHaveAttribute('aria-label', 'Screen: Live · bot in control')++ // A takeover on this screen by another viewer repaints the hero and the pane.+ await pushEvent(page, 'display.lease', {+ profile_key: PROFILE_KEY,+ lease: { holder: 'human', viewer_id: null, viewer_hash: 'someone-else', since: 2, epoch: 2, reason: '' }+ })+ await expect(hero(page)).toHaveAttribute('aria-label', 'Screen: Live · another viewer in control', { timeout: 10_000 })+ await capture(page, '3-lease-event-applied')++ expect(pageErrors).toEqual([])+ })diff --cc pyproject.tomlindex 0624b4959a0,62920eaf49c..4cd87db1f9e--- a/pyproject.toml+++ b/pyproject.toml@@@ -1,18 -1,18 +1,16 @@@--[project]name = "hermes-agent"-version = "0.21.4"+version = "0.0.0"description = "The self-improving AI agent — creates skills from experience, improves them during use, and runs anywhere"readme = "README.md"-# Upper bound is load-bearing, not cosmetic. uv resolves the project's-# Python from `requires-python`, and an inherited `UV_PYTHON` env var (or a-# fresh distro whose newest interpreter uv auto-picks) will otherwise select-# 3.14, where Rust-backed transitives (e.g. pydantic-core) have no cp314-# wheel yet and fall back to a maturin source build that fails. Capping at-# <3.14 makes uv refuse 3.14 with a clear error instead of attempting that-# build. Raise the ceiling once our Rust transitives ship cp314 wheels.-requires-python = ">=3.11,<3.14"+# 3.14 is the newest python we know we have wheels for.+# we *only* support 3.14, BUT we need to allow old hermes installs on <3.14+# to get thru their update step on old python.+# Shortly after they do, we update to our latest python.+# See tests/compat/README.md for the updater contract this keeps.+requires-python = ">=3.11,<3.15"authors = [{ name = "Nous Research" }]license = "MIT"license-files = ["LICENSE"]@@@ -810,10 -618,9 +808,13 @@@ gateway = ["assets/**/*"# sealed wheels with the plugin Python modules; without this declaration the# wheel contains adapters but discovery finds zero bundled plugins.plugins = ["**/plugin.yaml", "**/plugin.yml"]+# pm/lock.json is the runtime pin table (uv/python/tool versions + sha256s).+# Without it a sealed wheel installs the pm package but has no pins to+# realize — the pm store would be empty.+pm = ["lock.json", "artifact-mirror.json", "pyproject.toml", "uv.lock"]+ # Bot Desktop starts Xvnc + Xfce through a shell launcher and seeds the wallpaper; both are read+ # via Path(__file__).parent in tools/bot_desktop/runtime.py and vanish from sealed wheels otherwise.+ tools = ["bot_desktop/launcher.sh", "bot_desktop/wallpaper.png"][tool.pytest.ini_options]testpaths = ["tests"]diff --cc scripts/check-windows-footguns.pyindex b28b385915d,d5de92b410c..adf12d4d562--- a/scripts/check-windows-footguns.py+++ b/scripts/check-windows-footguns.py@@@ -438,54 -431,27 +438,75 @@@ FOOTGUNS: list[Footgun] =and _call_closes_on_line(line, m.end())),),+ Footgun(+ name="read with encoding='utf-8' (BOM-intolerant — use 'utf-8-sig')",+ # Fires when a READ-shaped call passes plain utf-8. Windows tooling+ # (PowerShell Set-Content/Out-File, some editors) BOM-prefixes files+ # it touches; a plain-utf-8 read then hands '\ufeff{...' to+ # json.load, which dies with "Expecting value". utf-8-sig reads+ # BOM'd and BOM-less files identically, so it is strictly safer on+ # the read side. Live case: PR #3 — Set-Content BOM'd+ # install-stamp.json and read_build_info demoted the tree to+ # `unknown`. The quote pattern stops at the closing quote, so+ # 'utf-8-sig' itself never matches.+ pattern=re.compile(+ r"""encoding\s*=\s*['"]utf[-_]?8['"]""", re.IGNORECASE+ ),+ message=(+ "Reading with encoding='utf-8' breaks on BOM-prefixed files — "+ "Windows tooling (PowerShell Set-Content/Out-File, some "+ "editors) BOMs files it touches, and json.load on the result "+ "fails with 'Expecting value'. encoding='utf-8-sig' reads "+ "BOM'd and BOM-less files alike. Policy: reads utf-8-sig, "+ "writes utf-8."+ ),+ fix=(+ "path.read_text(encoding='utf-8-sig') / "+ "open(path, 'r', encoding='utf-8-sig')"+ ),+ post_filter=lambda m, line: _is_read_shaped(line),+ ),+ Footgun(+ name="write with encoding='utf-8-sig' (emits a BOM)",+ # The inverse direction: utf-8-sig on a WRITE emits the BOM — the+ # exact bytes the read-side rule exists to tolerate. Never produce+ # them ourselves.+ pattern=re.compile(+ r"""encoding\s*=\s*['"]utf[-_]?8[-_]sig['"]""", re.IGNORECASE+ ),+ message=(+ "Writing with encoding='utf-8-sig' EMITS a UTF-8 BOM — the "+ "exact bytes that break plain-utf-8 readers and non-Python "+ "tooling. Policy: reads utf-8-sig, writes utf-8 (never emit "+ "a BOM)."+ ),+ fix=(+ "path.write_text(data, encoding='utf-8') / "+ "open(path, 'w', encoding='utf-8')"+ ),+ post_filter=lambda m, line: _is_write_shaped(line),+ ),+ Footgun(+ name="module-level import of a POSIX-only stdlib module",+ # Only unindented imports: a top-level `import fcntl` fails at import time on Windows and takes+ # every importer down with it (tools.bot_desktop.lease took computer_use down on native+ # Windows). Indented imports inside a function or a try/except ImportError are the fix shape.+ pattern=re.compile(+ r"^(?:import\s+(?:fcntl|pwd|grp|termios|resource|pty|tty)\b"+ r"|from\s+(?:fcntl|pwd|grp|termios|resource|pty|tty)\s+import\b)"+ ),+ message=(+ "fcntl/pwd/grp/termios/resource/pty/tty do not exist on Windows; a module-level import "+ "raises ModuleNotFoundError and breaks every module that imports this one."+ ),+ fix=(+ "Import lazily inside the function that needs it, or\n"+ "try:\n"+ " import fcntl\n"+ "except ImportError:\n"+ " fcntl = None # and take the Windows path when None"+ ),+ ),]diff --cc tests/fixtures/resolution_allowlist.jsonindex 8d0a7c14bff,040864f3cee..72ccfced9c9--- a/tests/fixtures/resolution_allowlist.json+++ b/tests/fixtures/resolution_allowlist.json@@@ -648,5 -688,40 +648,30 @@@"path": "tui_gateway/methods_prompt.py","symbol": "_","kind": "bare_which"+ },+ {+ "path": "agent/anthropic_adapter.py",+ "symbol": "<module>",+ "kind": "known_path_table"+ },- {- "path": "hermes_cli/_early_recovery.py",- "symbol": "_find_uv_binary",- "kind": "known_path_table"- },- {- "path": "tools/computer_use/cua_backend_driver.py",- "symbol": "_candidate_cua_driver_commands",- "kind": "known_path_table"- },+ {+ "path": "tools/bot_desktop/browser.py",+ "symbol": "_system_executable",+ "kind": "bare_which"+ },+ {+ "path": "tools/bot_desktop/install.py",+ "symbol": "_run",+ "kind": "bare_which"+ },+ {+ "path": "tools/bot_desktop/runtime.py",+ "symbol": "missing_binaries",+ "kind": "bare_which"+ },+ {+ "path": "tools/bot_desktop/runtime.py",+ "symbol": "package_manager",+ "kind": "bare_which"}]diff --cc tests/hermes_cli/test_bot_desktop_screen_stop.pyindex 00000000000,81482c81829..f88ccd841aamode 000000,100644..100644--- a/tests/hermes_cli/test_bot_desktop_screen_stop.py+++ b/tests/hermes_cli/test_bot_desktop_screen_stop.py@@@ -1,0 -1,36 +1,36 @@@+ """The documented CLI stop --force is also recovery for a disconnected viewer's lease."""++ import argparse++ from hermes_cli.subcommands.computer_use_screen import build_screen_parser+ import pytest++[email protected]_only[email protected]("linux")+ def test_screen_stop_hands_back_even_when_the_desktop_has_already_exited():+ from tools.bot_desktop import lease++ parser = argparse.ArgumentParser()+ build_screen_parser(parser.add_subparsers(), lambda sub, help_text: sub.add_argument('--json', action='store_true'))+ lease.acquire('disconnected-viewer')+ args = parser.parse_args(['screen', 'stop', '--force'])+ assert args.screen_func(args) == 0+ assert lease.get().holder == lease.AGENT++[email protected]_only[email protected]("linux")+ def test_screen_stop_refuses_while_a_human_holds_unless_forced(monkeypatch):+ """Same door as display.stop: a runbook or stray `screen stop` must not yank a live takeover."""+ from tools.bot_desktop import lease, runtime++ stopped: list = []+ monkeypatch.setattr(runtime, "stop", lambda: stopped.append(1) or True)+ parser = argparse.ArgumentParser()+ build_screen_parser(parser.add_subparsers(), lambda sub, help_text: sub.add_argument('--json', action='store_true'))+ lease.acquire('human-at-keyboard')+ args = parser.parse_args(['screen', 'stop'])+ assert args.screen_func(args) == 1+ assert lease.get().holder == lease.HUMAN and not stopped+ args = parser.parse_args(['screen', 'stop', '--force'])+ assert args.screen_func(args) == 0+ assert lease.get().holder == lease.AGENT and stoppeddiff --cc tests/hermes_cli/test_profiles.pyindex 152042ad916,3808c6f11eb..1e993ba6b8a--- a/tests/hermes_cli/test_profiles.py+++ b/tests/hermes_cli/test_profiles.py@@@ -14,8 -15,8 +15,8 @@@ import typefrom pathlib import Pathfrom unittest.mock import patch, MagicMock++import hermes_yaml as yamlimport pytest--import yamlfrom hermes_cli import profilesfrom hermes_cli.profiles import (@@@ -129,7 -130,7 +130,7 @@@ class TestCreateProfileprofile_dir = create_profile("coder", no_alias=True)env_path = profile_dir / ".env"assert env_path.exists()-- content = env_path.read_text(encoding="utf-8")++ content = env_path.read_text(encoding="utf-8-sig")# Placeholder only — no credentials leak in from anywhere.assert all(line.startswith("#") or not line.strip()@@@ -148,12 -149,12 +149,12 @@@"""default_home = profile_env / ".hermes"(default_home / "config.yaml").write_text(-- "model:\n provider: nous\n default: some/model\n"++ "model:\n provider: nous\n default: some/model\n", encoding="utf-8")profile_dir = create_profile("coder", no_alias=True)-- cfg = yaml.safe_load((profile_dir / "config.yaml").read_text())++ cfg = yaml.safe_load((profile_dir / "config.yaml").read_text(encoding="utf-8-sig"))assert cfg["model"]["provider"] == "nous"assert cfg["model"]["default"] == "some/model"@@@ -168,12 -169,12 +169,12 @@@(default_home / "config.yaml").write_text("model:\n provider: my-gateway\n default: my-finetune\n""providers:\n my-gateway:\n api: https://llm.internal.example.com/v1\n key_env: GW_KEY\n"-- " unrelated:\n api: https://other.example.com/v1\n"++ " unrelated:\n api: https://other.example.com/v1\n", encoding="utf-8")profile_dir = create_profile("coder", no_alias=True)-- cfg = yaml.safe_load((profile_dir / "config.yaml").read_text())++ cfg = yaml.safe_load((profile_dir / "config.yaml").read_text(encoding="utf-8-sig"))assert cfg["model"] == {"provider": "my-gateway", "default": "my-finetune"}assert cfg["providers"] == {"my-gateway": {"api": "https://llm.internal.example.com/v1", "key_env": "GW_KEY"}}@@@ -185,15 -186,15 +186,15 @@@"""default_home = profile_env / ".hermes"(default_home / "config.yaml").write_text(-- "model:\n provider: nous\n default: some/model\n"++ "model:\n provider: nous\n default: some/model\n", encoding="utf-8")profile_dir = create_profile("coder", no_alias=True)(default_home / "config.yaml").write_text(-- "model:\n provider: other\n default: changed/model\n"++ "model:\n provider: other\n default: changed/model\n", encoding="utf-8")-- cfg = yaml.safe_load((profile_dir / "config.yaml").read_text())++ cfg = yaml.safe_load((profile_dir / "config.yaml").read_text(encoding="utf-8-sig"))assert cfg["model"]["provider"] == "nous"assert cfg["model"]["default"] == "some/model"@@@ -204,17 -205,17 +205,17 @@@tmp_path = profile_envdefault_home = tmp_path / ".hermes"# Create source config files in default profile-- (default_home / "config.yaml").write_text("model: test")-- (default_home / ".env").write_text("KEY=val")-- (default_home / "SOUL.md").write_text("Be helpful.")++ (default_home / "config.yaml").write_text("model: test", encoding="utf-8")++ (default_home / ".env").write_text("KEY=val", encoding="utf-8")++ (default_home / "SOUL.md").write_text("Be helpful.", encoding="utf-8")profile_dir = create_profile("coder", clone_config=True, no_alias=True)-- cloned_config = yaml.safe_load((profile_dir / "config.yaml").read_text())++ cloned_config = yaml.safe_load((profile_dir / "config.yaml").read_text(encoding="utf-8-sig"))assert cloned_config["_config_version"] == DEFAULT_CONFIG["_config_version"]assert cloned_config["model"] == "test"-- assert (profile_dir / ".env").read_text().strip() == "KEY=val"-- assert (profile_dir / "SOUL.md").read_text() == "Be helpful."++ assert (profile_dir / ".env").read_text(encoding="utf-8-sig").strip() == "KEY=val"++ assert (profile_dir / "SOUL.md").read_text(encoding="utf-8-sig") == "Be helpful."def test_clone_sync_imports_carries_manifest_but_never_links_profiles(self, profile_env):"""--sync-imports copies import-sync.json (a pointer at EXTERNAL agent trees) and nothing@@@ -222,11 -223,11 +223,11 @@@from hermes_cli.agent_import_sync import SYNC_MANIFEST_NAME, load_sync_manifestdefault_home = profile_env / ".hermes"-- (default_home / "config.yaml").write_text("model: test")++ (default_home / "config.yaml").write_text("model: test", encoding="utf-8")manifest = {"version": 1, "agents": {"claude-code": {"source": str(profile_env / ".claude"), "digest": "d", "overwrite": False,"last_import": 1, "imported_skills": ["s1"]}}}-- (default_home / SYNC_MANIFEST_NAME).write_text(json.dumps(manifest))++ (default_home / SYNC_MANIFEST_NAME).write_text(json.dumps(manifest), encoding="utf-8")plain = create_profile("plain", clone_config=True, no_alias=True)assert not (plain / SYNC_MANIFEST_NAME).exists()@@@ -234,8 -235,8 +235,8 @@@synced = create_profile("synced", clone_config=True, sync_imports=True, no_alias=True)assert load_sync_manifest(synced)["agents"] == manifest["agents"]# Editing the source afterwards does not reach the clone: still an independent island.-- (default_home / "config.yaml").write_text("model: changed")-- assert yaml.safe_load((synced / "config.yaml").read_text())["model"] == "test"++ (default_home / "config.yaml").write_text("model: changed", encoding="utf-8")++ assert yaml.safe_load((synced / "config.yaml").read_text(encoding="utf-8-sig"))["model"] == "test"@staticmethoddef _home_with_linked_skill(profile_env):@@@ -246,7 -247,7 +247,7 @@@(external / "foo" / "SKILL.md").write_text("# external foo\n", encoding="utf-8")(default_home / "skills" / "local").mkdir(parents=True)(default_home / "skills" / "local" / "SKILL.md").write_text("# local\n", encoding="utf-8")-- (default_home / "config.yaml").write_text(f"model: test\nskills:\n external_dirs:\n - {external}\n")++ (default_home / "config.yaml").write_text(f"model: test\nskills:\n external_dirs:\n - {external}\n", encoding="utf-8")return default_home, external@pytest.mark.parametrize("clone_kwargs", [{"clone_config": True}, {"clone_all": True}])@@@ -257,7 -258,7 +258,7 @@@default_home, external = self._home_with_linked_skill(profile_env)# copytree sees plain directories (what a junction looks like to os.stat on Windows).(default_home / "skills" / "foo").mkdir()-- (default_home / "skills" / "foo" / "SKILL.md").write_text("# a physical copy would come from here\n")++ (default_home / "skills" / "foo" / "SKILL.md").write_text("# a physical copy would come from here\n", encoding="utf-8")(default_home / "skills" / "gone").mkdir()targets = {str(default_home / "skills" / "foo"): str(external / "foo"),str(default_home / "skills" / "gone"): str(profile_env / "nowhere")}@@@ -272,13 -273,13 +273,13 @@@clone = create_profile("clone", no_alias=True, **clone_kwargs)foo = clone / "skills" / "foo"assert foo.is_symlink() and foo.resolve() == (external / "foo").resolve()-- assert (foo / "SKILL.md").read_text(encoding="utf-8") == "# external foo\n"++ assert (foo / "SKILL.md").read_text(encoding="utf-8-sig") == "# external foo\n"assert (clone / "skills" / "local" / "SKILL.md").is_file()assert not (clone / "skills" / "gone").exists()from tools.skills_tool import _collect_skill_candidatesassert len(_collect_skill_candidates("foo", None, [clone / "skills", external])) == 1-- @pytest.mark.windows_only++ @pytest.mark.platforms("windows")def test_clone_keeps_real_ntfs_junction(self, profile_env):import _winapidefault_home, external = self._home_with_linked_skill(profile_env)@@@ -299,26 -300,74 +300,74 @@@# Cron jobs are scheduled work bound to the source profile + origin channel; a clone# that inherits jobs.json fires every job twice (two gateways, same job ids).default_home = profile_env / ".hermes"-- (default_home / "config.yaml").write_text("model: test")++ (default_home / "config.yaml").write_text("model: test", encoding="utf-8")(default_home / "cron").mkdir()-- (default_home / "cron" / "jobs.json").write_text(json.dumps({"jobs": [{"id": "abc123def456"}]}))++ (default_home / "cron" / "jobs.json").write_text(json.dumps({"jobs": [{"id": "abc123def456"}]}), encoding="utf-8")(default_home / "cron" / "output").mkdir()profile_dir = create_profile("coder", clone_all=True, no_alias=True)assert (profile_dir / "cron").is_dir()assert not any((profile_dir / "cron").iterdir())-- assert yaml.safe_load((profile_dir / "config.yaml").read_text())["model"] == "test"++ assert yaml.safe_load((profile_dir / "config.yaml").read_text(encoding="utf-8-sig"))["model"] == "test"++ def test_clone_all_does_not_inherit_the_source_screen_or_browser_process_artifacts(self, profile_env):+ """A clone keeps browser data, never the source's screen or Chromium runtime files."""+ default_home = profile_env / ".hermes"- (default_home / "config.yaml").write_text("model: test")++ (default_home / "config.yaml").write_text("model: test", encoding="utf-8")+ bd = default_home / "bot-desktop"+ browser_profile = bd / "browser-profile"+ (browser_profile / "Default").mkdir(parents=True)- (browser_profile / "Default" / "Cookies").write_text("jar")- (bd / "launcher.pid").write_text("4242 1.5")- (bd / "env").write_text("DISPLAY=:21\nXAUTHORITY=/x\n")- (bd / "lease.json").write_text(json.dumps({"holder": "human", "viewer_id": "v", "epoch": 3}))++ (browser_profile / "Default" / "Cookies").write_text("jar", encoding="utf-8")++ (bd / "launcher.pid").write_text("4242 1.5", encoding="utf-8")++ (bd / "env").write_text("DISPLAY=:21\nXAUTHORITY=/x\n", encoding="utf-8")++ (bd / "lease.json").write_text(json.dumps({"holder": "human", "viewer_id": "v", "epoch": 3}), encoding="utf-8")+ process_markers = ("DevToolsActivePort", "SingletonLock", "SingletonCookie", "SingletonSocket")+ for process_marker in process_markers:- (browser_profile / process_marker).write_text("source-process")++ (browser_profile / process_marker).write_text("source-process", encoding="utf-8")++ profile_dir = create_profile("coder", clone_all=True, no_alias=True)+ cloned_browser = profile_dir / "bot-desktop" / "browser-profile"++ for runtime_file in ("launcher.pid", "env", "lease.json"):+ assert not (profile_dir / "bot-desktop" / runtime_file).exists(), runtime_file+ for process_marker in process_markers:+ assert not (cloned_browser / process_marker).exists(), process_marker- assert (cloned_browser / "Default" / "Cookies").read_text() == "jar"++ assert (cloned_browser / "Default" / "Cookies").read_text(encoding="utf-8-sig") == "jar"+- @pytest.mark.linux_only++ @pytest.mark.platforms("linux")+ def test_clone_all_does_not_attach_to_the_source_profiles_live_browser(self, profile_env):+ """Copied Chromium markers must not route the clone through the source profile's CDP port."""+ from tools.bot_desktop.browser import running_instance_cdp_port++ default_home = profile_env / ".hermes"- (default_home / "config.yaml").write_text("model: test")++ (default_home / "config.yaml").write_text("model: test", encoding="utf-8")+ browser_profile = default_home / "bot-desktop" / "browser-profile"+ browser_profile.mkdir(parents=True)++ with socket.socket() as listener:+ listener.bind(("127.0.0.1", 0))+ listener.listen()+ port = listener.getsockname()[1]- (browser_profile / "DevToolsActivePort").write_text(f"{port}\n/devtools/browser/source\n")++ (browser_profile / "DevToolsActivePort").write_text(f"{port}\n/devtools/browser/source\n", encoding="utf-8")+ (browser_profile / "SingletonLock").symlink_to(f"host-{os.getpid()}")+ assert running_instance_cdp_port(str(browser_profile)) == port++ profile_dir = create_profile("coder", clone_all=True, no_alias=True)+ cloned_browser = profile_dir / "bot-desktop" / "browser-profile"++ assert running_instance_cdp_port(str(cloned_browser)) is None+ assert running_instance_cdp_port(str(browser_profile)) == port@pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="special files need a POSIX filesystem")def test_clone_all_skips_special_files(self, profile_env):# A live source profile holds special files copytree cannot copy (e.g. a suffixless# agent-browser control socket); one of them must not abort the whole clone.default_home = profile_env / ".hermes"-- (default_home / "config.yaml").write_text("model: test")++ (default_home / "config.yaml").write_text("model: test", encoding="utf-8")browser_dir = default_home / "home" / ".agent-browser"browser_dir.mkdir(parents=True)-- (browser_dir / "state.json").write_text("{}")++ (browser_dir / "state.json").write_text("{}", encoding="utf-8")os.mkfifo(browser_dir / "control")profile_dir = create_profile("coder", clone_all=True, no_alias=True)@@@ -343,7 -392,7 +392,7 @@@ class TestNoSkillsOptOut# Marker file is presentmarker = profile_dir / NO_BUNDLED_SKILLS_MARKERassert marker.is_file(), "expected .no-bundled-skills marker in profile root"-- assert "--no-skills" in marker.read_text()++ assert "--no-skills" in marker.read_text(encoding="utf-8-sig")# skills/ dir exists (profile bootstrapping still creates the dir) but# contains nothing yet because create_profile itself doesn't seed.@@@ -367,7 -416,7 +416,7 @@@ class TestBackfillProfileEnvsdef test_copies_default_env_into_envless_profiles(self, profile_env):import stattmp_path = profile_env-- (tmp_path / ".hermes" / ".env").write_text("OPENROUTER_API_KEY=root-key\n")++ (tmp_path / ".hermes" / ".env").write_text("OPENROUTER_API_KEY=root-key\n", encoding="utf-8")p1 = create_profile("old1", no_alias=True)p2 = create_profile("old2", no_alias=True)# Simulate pre-#44792 profiles: no .env@@@ -378,7 -427,7 +427,7 @@@assert sorted(backfilled) == ["old1", "old2"]for p in (p1, p2):-- assert (p / ".env").read_text() == "OPENROUTER_API_KEY=root-key\n"++ assert (p / ".env").read_text(encoding="utf-8-sig") == "OPENROUTER_API_KEY=root-key\n"assert stat.S_IMODE((p / ".env").stat().st_mode) == 0o600@@@ -389,7 -438,7 +438,7 @@@backfilled = backfill_profile_envs(quiet=True)assert backfilled == ["noroot"]-- content = (p / ".env").read_text(encoding="utf-8")++ content = (p / ".env").read_text(encoding="utf-8-sig")assert all(line.startswith("#") or not line.strip()for line in content.splitlines()@@@ -882,12 -931,12 +931,12 @@@ class TestAliasCollision-- @pytest.mark.windows_only++ @pytest.mark.platforms("windows")def test_windows_checks_bat_extension(self, profile_env):wrapper_dir = profile_env / ".local" / "bin"wrapper_dir.mkdir(parents=True, exist_ok=True)bat_path = wrapper_dir / "mybot.bat"-- bat_path.write_text("@echo off\r\nhermes -p mybot %*\r\n")++ bat_path.write_text("@echo off\r\nhermes -p mybot %*\r\n", encoding="utf-8")with patch("subprocess.run") as mock_run:mock_run.return_value = MagicMock(returncode=0, stdout=str(bat_path),@@@ -917,12 -966,12 +966,12 @@@ class TestWrapperScriptwrapper = create_wrapper_script("mybot")assert wrapper is not Noneassert wrapper.name == "mybot"-- content = wrapper.read_text()++ content = wrapper.read_text(encoding="utf-8-sig")assert content.startswith("#!/bin/sh")assert "exec /opt/hermes/bin/hermes -p mybot" in content-- @pytest.mark.windows_only++ @pytest.mark.platforms("windows")def test_remove_finds_bat_on_windows(self, profile_env):from hermes_cli.profiles import create_wrapper_scriptwrapper = create_wrapper_script("mybot")@@@ -953,7 -1002,7 +1002,7 @@@ class TestWrapperScriptSecuritywith pytest.raises(ValueError, match="Invalid alias name"):create_wrapper_script("../../.bashrc", target="coder")# The traversal target was not touched.-- assert sentinel.read_text(encoding="utf-8") == "keep"++ assert sentinel.read_text(encoding="utf-8-sig") == "keep"def test_create_wrapper_rejects_absolute_path(self, profile_env, tmp_path):target = tmp_path / "abs-wrapper"@@@ -981,7 -1030,7 +1030,7 @@@ class TestFindAliasForProfilefrom hermes_cli.profiles import _get_wrapper_dir, find_alias_for_profilewrapper_dir = _get_wrapper_dir()wrapper_dir.mkdir(parents=True, exist_ok=True)-- (wrapper_dir / "pip").write_text("#!/bin/sh\nexec python -m pip \"$@\"\n")++ (wrapper_dir / "pip").write_text("#!/bin/sh\nexec python -m pip \"$@\"\n", encoding="utf-8")assert find_alias_for_profile("steve") is None@@@ -1037,12 -1086,12 +1086,12 @@@ class TestRenameProfile"enabled": True,}}-- }))++ }), encoding="utf-8")with patch("hermes_cli.profiles.check_alias_collision", return_value="skip"):rename_profile("ssi_health", "heimdall")-- cfg = json.loads(honcho_path.read_text())++ cfg = json.loads(honcho_path.read_text(encoding="utf-8-sig"))assert "hermes.ssi_health" not in cfg["hosts"]assert cfg["hosts"]["hermes_heimdall"]["aiPeer"] == "ssi_health"assert cfg["hosts"]["hermes_heimdall"]["peerName"] == "user-peer"@@@ -1252,12 -1301,12 +1301,12 @@@ class TestExportImport# OPERATOR's real install whenever basetest sits inside it, so this test used to# overwrite the live config.yaml / .env / MEMORY.md with its fixtures.default_dir = profile_env / ".hermes"-- (default_dir / "config.yaml").write_text("model: test")-- (default_dir / ".env").write_text("KEY=val")-- (default_dir / "SOUL.md").write_text("Be nice.")++ (default_dir / "config.yaml").write_text("model: test", encoding="utf-8")++ (default_dir / ".env").write_text("KEY=val", encoding="utf-8")++ (default_dir / "SOUL.md").write_text("Be nice.", encoding="utf-8")mem_dir = default_dir / "memories"mem_dir.mkdir(exist_ok=True)-- (mem_dir / "MEMORY.md").write_text("remember this")++ (mem_dir / "MEMORY.md").write_text("remember this", encoding="utf-8")output = tmp_path / "export" / "default.tar.gz"output.parent.mkdir(parents=True, exist_ok=True)@@@ -1282,7 -1331,7 +1331,7 @@@"""# Same reason as above: never resolve the operator's real default home from a test.default_dir = profile_env / ".hermes"-- (default_dir / "config.yaml").write_text("ok")++ (default_dir / "config.yaml").write_text("ok", encoding="utf-8")# Place broken symlink *inside* the allowed ``skills/`` tree so the# root-level allow-list passes the directory through; the# symlinks=True flag must then preserve the link instead of@@@ -1291,7 -1340,7 +1340,7 @@@broken_dir.mkdir(parents=True)(broken_dir / "broken_link").symlink_to("/nonexistent/path")# Valid symlink for comparison-- (broken_dir / "valid_target.txt").write_text("real data")++ (broken_dir / "valid_target.txt").write_text("real data", encoding="utf-8")(broken_dir / "valid_link").symlink_to(broken_dir / "valid_target.txt")@@@ -1378,9 -1427,9 +1427,8 @@@ class TestWriteProfileMetaDurabilitydef _interrupted_write(profile_dir):"""Run a ``write_profile_meta`` whose serialization fails mid-call.-- The pre-fix code called ``yaml.safe_dump``; ``utils.atomic_yaml_write``-- calls ``yaml.dump``. Breaking both keeps this serializer-agnostic, so-- it measures durability rather than the choice of entry point. A++ ``utils.atomic_yaml_write`` serializes through ``hermes_yaml.safe_dump``.++ Breaking that seam measures durability rather than the choice of writer. Ascoped ``MonkeyPatch.context`` is used instead of the fixture so thepatch is reverted immediately, without touching the session-wide envisolation that shares the function-scoped ``monkeypatch`` instance.@@@ -1390,20 -1439,20 +1438,19 @@@with pytest.MonkeyPatch.context() as mp:mp.setattr(yaml, "safe_dump", _boom)-- mp.setattr(yaml, "dump", _boom)with pytest.raises(RuntimeError):profiles.write_profile_meta(profile_dir, description_auto=True)def test_failed_write_leaves_existing_file_intact(self, tmp_path):profile_dir = self._seed(tmp_path)path = profile_dir / "profile.yaml"-- before = path.read_text(encoding="utf-8")++ before = path.read_text(encoding="utf-8-sig")assert "Curated by hand" in beforeself._interrupted_write(profile_dir)# A truncating open() destroys the file before the dump ever runs.-- assert path.read_text(encoding="utf-8") == before++ assert path.read_text(encoding="utf-8-sig") == beforedef test_failed_write_does_not_silently_drop_unspecified_fields(self, tmp_path):profile_dir = self._seed(tmp_path)@@@ -1427,7 -1476,7 +1474,7 @@@profile_dir.mkdir()profiles.write_profile_meta(profile_dir, description="Code wizard 🧙 ✨")-- raw = (profile_dir / "profile.yaml").read_text(encoding="utf-8")++ raw = (profile_dir / "profile.yaml").read_text(encoding="utf-8-sig")assert "\\U" not in rawassert "🧙" in rawassert profiles.read_profile_meta(profile_dir)["description"] == "Code wizard 🧙 ✨"@@@ -1451,7 -1500,7 +1498,7 @@@profiles.write_profile_meta(profile_dir, description="updated")assert (profile_dir / "profile.yaml").is_symlink()-- assert "updated" in real.read_text(encoding="utf-8")++ assert "updated" in real.read_text(encoding="utf-8-sig")assert [p.name for p in profile_dir.iterdir() if p.name.endswith(".tmp")] == []@@@ -1525,16 -1574,16 +1572,16 @@@ class TestEdgeCasestmp_path = profile_env# Create source profile with configsource_dir = create_profile("source", no_alias=True)-- (source_dir / "config.yaml").write_text("model: cloned")-- (source_dir / ".env").write_text("SECRET=yes")++ (source_dir / "config.yaml").write_text("model: cloned", encoding="utf-8")++ (source_dir / ".env").write_text("SECRET=yes", encoding="utf-8")target_dir = create_profile("target", clone_from="source", clone_config=True, no_alias=True,)-- cloned_config = yaml.safe_load((target_dir / "config.yaml").read_text())++ cloned_config = yaml.safe_load((target_dir / "config.yaml").read_text(encoding="utf-8-sig"))assert cloned_config["_config_version"] == DEFAULT_CONFIG["_config_version"]assert cloned_config["model"] == "cloned"-- assert (target_dir / ".env").read_text().strip() == "SECRET=yes"++ assert (target_dir / ".env").read_text(encoding="utf-8-sig").strip() == "SECRET=yes"@@@ -1569,7 -1618,7 +1616,7 @@@ class TestProfilesToServehost multiplexer, but callers that enumerate INSTALLED profiles still see it."""create_profile("solo", no_alias=True)create_profile("member", no_alias=True)-- (get_profile_dir("solo") / "config.yaml").write_text("gateway:\n standalone: true\n")++ (get_profile_dir("solo") / "config.yaml").write_text("gateway:\n standalone: true\n", encoding="utf-8")serve = dict(profiles_to_serve(multiplex=True))assert set(serve) == {"default", "member"}served_all = dict(profiles_to_serve(multiplex=True, include_standalone=True))@@@ -1580,7 -1629,7 +1627,7 @@@standalone) with exactly one warning per process."""profiles._STANDALONE_WARNED = Falsedefault_home = _get_default_hermes_home()-- (default_home / "config.yaml").write_text("gateway:\n standalone: true\n")++ (default_home / "config.yaml").write_text("gateway:\n standalone: true\n", encoding="utf-8")caplog.clear()with caplog.at_level("WARNING", logger="hermes_cli.profiles"):serve = dict(profiles_to_serve(multiplex=True))@@@ -1594,7 -1643,7 +1641,7 @@@def test_standalone_malformed_config_does_not_break_roster(self, profile_env, caplog, content):create_profile("solo", no_alias=True)home = get_profile_dir("solo")-- (home / "config.yaml").write_text(content)++ (home / "config.yaml").write_text(content, encoding="utf-8")for _ in range(2):assert profiles.profile_is_standalone(home) is Falseassert "solo" in dict(profiles_to_serve(True))@@@ -1608,7 -1657,7 +1655,7 @@@create_profile("solo", no_alias=True)home = get_profile_dir("solo")cfg = home / "config.yaml"-- cfg.write_text("gateway:\n standalone: true\n")++ cfg.write_text("gateway:\n standalone: true\n", encoding="utf-8")real_stat = Path.statdef denied(path, *args, **kwargs):@@@ -1637,13 -1686,13 +1684,13 @@@create_profile("alpha", no_alias=True)create_profile("beta", no_alias=True)alpha, beta = get_profile_dir("alpha"), get_profile_dir("beta")-- (alpha / "config.yaml").write_text("gateway:\n standalone: true\n")++ (alpha / "config.yaml").write_text("gateway:\n standalone: true\n", encoding="utf-8")assert profiles.profile_is_standalone(alpha) is Trueassert profiles.profile_is_standalone(beta) is Falseassert profiles.profile_is_standalone(alpha) is True # memo hit, still Truecfg = alpha / "config.yaml"replacement = alpha / "replacement.yaml"-- replacement.write_text("gateway:\n standalone: false\n")++ replacement.write_text("gateway:\n standalone: false\n", encoding="utf-8")replacement.replace(cfg)assert profiles.profile_is_standalone(alpha) is Falseassert profiles.profile_is_standalone(beta) is False@@@ -1672,7 -1721,7 +1719,7 @@@ class TestResolveProfileEnvSpellingcustom = tmp_path / "custom-hermes"for profile_dir in (root / "profiles" / "beta", root / "profiles" / "coder", custom / "profiles" / "beta"):profile_dir.mkdir(parents=True)-- (profile_dir / "config.yaml").write_text("{}\n") # identity marker: a bare dir does not resolve++ (profile_dir / "config.yaml").write_text("{}\n", encoding="utf-8") # identity marker: a bare dir does not resolvecases = [(root, "coder", root / "profiles" / "coder"),(root / "profiles" / "alpha", "beta", root / "profiles" / "beta"),@@@ -1695,6 -1744,74 +1742,74 @@@assert Path(resolve_profile_env("default")) == _get_default_hermes_home()+++ def _live_bot_desktop_launcher(profile_dir: Path):+ """A synthetic Bot Desktop launcher for ``profile_dir``: its own session (like launcher.sh) with the+ identity file + env runtime.status() reads, so the profile op sees a running screen."""+ import subprocess+ from tools.bot_desktop import runtime++ proc = subprocess.Popen(["sleep", "60"], start_new_session=True)+ sd = profile_dir / "bot-desktop"+ sd.mkdir()+ (sd / "launcher.pid").write_text(f"{proc.pid} {runtime._create_time(proc.pid)}", encoding="utf-8")+ (sd / "env").write_text("DISPLAY=:42\n", encoding="utf-8")+ return proc++[email protected]_only[email protected]("linux")+ @pytest.mark.parametrize("op", ["delete", "rename"])+ def test_profile_delete_and_rename_stop_the_profiles_bot_desktop(profile_env, op):+ """Deleting or renaming a profile stops its gateway, and must stop its Bot Desktop launcher too: the+ Xvnc/Xfce session otherwise keeps running against a directory that no longer exists (or now belongs to+ another name), holding its display number and an rfb.sock nobody can reach through status()."""+ import time+ from tools.bot_desktop import runtime++ profile_dir = create_profile("coder", no_alias=True)+ proc = _live_bot_desktop_launcher(profile_dir)+ # A human held the screen when the op ran. lease.json moves with a rename; left human-held it would+ # fence the agent out of the renamed profile's next screen for a viewer that no longer exists.+ (profile_dir / "bot-desktop" / "lease.json").write_text(+ json.dumps({"holder": "human", "viewer_id": "gone", "since": 1.0, "epoch": 3, "reason": ""}), encoding="utf-8")+ try:+ with patch("hermes_cli.profiles._cleanup_gateway_service"), \+ patch("hermes_cli.profiles.check_alias_collision", return_value="skip"):+ if op == "delete":+ delete_profile("coder", yes=True)+ else:+ rename_profile("coder", "hacker")+ # The runtime reaps what it kills (a later gateway holds no Popen for the launcher), so our own+ # Popen may see the status already collected; liveness, not the exit code, is the contract.+ deadline = time.monotonic() + 10+ while time.monotonic() < deadline and runtime._pid_alive(proc.pid):+ time.sleep(0.05)+ assert not runtime._pid_alive(proc.pid), "the launcher was not stopped by the profile op"+ if op == "rename":- moved = json.loads((profile_dir.parent / "hacker" / "bot-desktop" / "lease.json").read_text(encoding="utf-8"))++ moved = json.loads((profile_dir.parent / "hacker" / "bot-desktop" / "lease.json").read_text(encoding="utf-8-sig"))+ assert moved["holder"] == "agent", "stale human lease survived the teardown"+ finally:+ proc.kill()+++ @pytest.mark.parametrize("name", ["coder", "default"])+ def test_export_leaves_the_bot_desktop_browser_profile_out(profile_env, tmp_path, name):+ """bot-desktop/ holds the screen's persistent Chromium profile (Cookies, Login Data: the bot's live web+ sessions) plus sockets and X state. None of it belongs in an export archive meant to move a persona."""+ profile_dir = create_profile(name, no_alias=True) if name != "default" else get_profile_dir("default")- (profile_dir / "config.yaml").write_text("model: test")++ (profile_dir / "config.yaml").write_text("model: test", encoding="utf-8")+ cookies = profile_dir / "bot-desktop" / "browser-profile" / "Default" / "Cookies"+ cookies.parent.mkdir(parents=True)+ cookies.write_bytes(b"SQLite format 3\x00")+ output = tmp_path / "export" / f"{name}.tar.gz"+ output.parent.mkdir(parents=True, exist_ok=True)+ export_profile(name, str(output))+ with tarfile.open(str(output), "r:gz") as tf:+ names = tf.getnames()+ assert f"{name}/config.yaml" in names+ assert not [n for n in names if "bot-desktop" in n], names+# ===================================================================# TestCloneAllExcludesRuntimeTrees# ===================================================================@@@ -1712,12 -1829,12 +1827,12 @@@ class TestCloneAllExcludesRuntimeTreesdef _seed(self, home):(home / "models").mkdir(); (home / "models" / "big.gguf").write_bytes(b"\0" * 64)(home / "runtimes" / "llamacpp" / "bin").mkdir(parents=True)-- (home / "runtimes" / "llamacpp" / "bin" / "llama-server").write_text("bin")++ (home / "runtimes" / "llamacpp" / "bin" / "llama-server").write_text("bin", encoding="utf-8")(home / "node" / "bin").mkdir(parents=True)-- (home / "node" / "bin" / "node").write_text("bin")++ (home / "node" / "bin" / "node").write_text("bin", encoding="utf-8")(home / "skills" / "greet").mkdir(parents=True)-- (home / "skills" / "greet" / "SKILL.md").write_text("# greet\n")-- (home / "config.yaml").write_text("model: test\n")++ (home / "skills" / "greet" / "SKILL.md").write_text("# greet\n", encoding="utf-8")++ (home / "config.yaml").write_text("model: test\n", encoding="utf-8")def test_ignore_drops_runtime_trees_only_at_the_default_root(self, profile_env):default_home = profile_env / ".hermes"diff --cc tests/tools/test_bot_desktop_browser.pyindex 00000000000,61e57244bff..915adc8130dmode 000000,100644..100644--- a/tests/tools/test_bot_desktop_browser.py+++ b/tests/tools/test_bot_desktop_browser.py@@@ -1,0 -1,317 +1,320 @@@+ """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._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._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)++ monkeypatch.setattr(++ "hermes_cli.browser_runtime.chromium_executable",++ lambda: str(pw_exe) if playwright else None,++ )+ 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+++ @pytest.mark.parametrize("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 "")++ Path(socket_dir, f"_{slot}_{tag}").write_text("{}" if slot == "stdout" else "", encoding="utf-8")+ 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() == 120diff --cc tests/tools/test_bot_desktop_idle.pyindex 00000000000,ba3f19641d6..f8d4b757529mode 000000,100644..100644--- a/tests/tools/test_bot_desktop_idle.py+++ b/tests/tools/test_bot_desktop_idle.py@@@ -1,0 -1,52 +1,52 @@@+ """Bot Desktop idle auto-stop: a screen nobody used past ``bot_desktop.idle_stop_minutes`` is stopped,+ one a human holds or that saw recent use is not."""++ from __future__ import annotations++ import os+ import time++ from tools.bot_desktop import lease, runtime+++ def _running(monkeypatch, tmp_path):+ sd = tmp_path / "bd"+ sd.mkdir()- (sd / "env").write_text("DISPLAY=:20\n")++ (sd / "env").write_text("DISPLAY=:20\n", encoding="utf-8")+ monkeypatch.setattr(runtime, "state_dir", lambda: sd)+ monkeypatch.setattr(runtime, "_launcher_pid", lambda: 4242)+ monkeypatch.setattr(runtime, "idle_stop_seconds", lambda: 600.0)+ stops = []+ monkeypatch.setattr(runtime, "stop", lambda: stops.append(True) or True)+ return sd, stops+++ def _age(path, seconds):+ old = time.time() - seconds+ os.utime(path, (old, old))+++ def test_idle_screen_is_stopped_but_a_used_or_held_one_is_not(tmp_path, monkeypatch):+ sd, stops = _running(monkeypatch, tmp_path)+ monkeypatch.setattr(lease, "get", lambda profile_key=None: lease.Lease(holder=lease.AGENT))++ _age(sd / "env", 5) # just started, never stamped: ages from publish+ assert runtime.stop_if_idle() is False and stops == []++ _age(sd / "env", 3600)+ runtime.touch_activity() # a computer_use action / browser spawn a moment ago+ assert runtime.stop_if_idle() is False and stops == []++ _age(sd / "activity", 3600)+ monkeypatch.setattr(lease, "get", lambda profile_key=None: lease.Lease(holder=lease.HUMAN, viewer_id="v1"))+ assert runtime.stop_if_idle() is False and stops == [], "a human mid-login is never timed out"++ monkeypatch.setattr(lease, "get", lambda profile_key=None: lease.Lease(holder=lease.AGENT))+ assert runtime.stop_if_idle() is True and stops == [True]+++ def test_idle_stop_disabled_by_zero(tmp_path, monkeypatch):+ sd, stops = _running(monkeypatch, tmp_path)+ monkeypatch.setattr(runtime, "idle_stop_seconds", lambda: 0.0)+ _age(sd / "env", 10 ** 6)+ assert runtime.stop_if_idle() is False and stops == []diff --cc tests/tools/test_bot_desktop_install.pyindex 00000000000,4d3b84ee873..c370b512842mode 000000,100644..100644--- a/tests/tools/test_bot_desktop_install.py+++ b/tests/tools/test_bot_desktop_install.py@@@ -1,0 -1,266 +1,263 @@@+ """Bot Desktop package install: sudo hand-off and single-flight invariants."""++ from __future__ import annotations++ import os+ import threading++ import pytest++ from tools.bot_desktop import install, runtime++ _REAL_INSTALL_COMMAND = runtime.install_command # captured before the fixture pins a sudo line+++ @pytest.fixture(autouse=True)+ def _isolated_host(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setattr(install, "_sudo_nopasswd", lambda: False)+ monkeypatch.setattr(runtime, "is_supported_host", lambda: True)+ monkeypatch.setattr(runtime, "install_command", lambda: "sudo apt-get install -y tigervnc-standalone-server")+ yield+ install._running.clear()+++ def test_empty_password_cancels_without_spawning(monkeypatch):+ monkeypatch.setattr(install.subprocess, "Popen", lambda *a, **k: pytest.fail("package manager spawned"))+ lines: list[str] = []+ code = install.install_packages(ask_password=lambda: "", on_line=lines.append)+ assert code == -1+ assert any("cancelled" in line for line in lines)+++ def test_second_install_for_same_profile_is_refused(monkeypatch):+ gate = threading.Event()+ entered = threading.Event()++ def slow_run(cmd, *, ask_password, on_line, timeout_seconds):+ entered.set()+ gate.wait(5)+ return 0++ monkeypatch.setattr(install, "_run", slow_run)+ worker = threading.Thread(target=install.install_packages, kwargs={"ask_password": lambda: "pw", "on_line": lambda _l: None})+ worker.start()+ assert entered.wait(5)+ with pytest.raises(install.InstallBusy):+ install.install_packages(ask_password=lambda: "pw", on_line=lambda _l: None)+ gate.set()+ worker.join(5)+ install.assert_not_running() # slot released once the run finishes+++ def test_claim_is_atomic_and_refuses_a_second_claim():+ """The gateway claims BEFORE spawning its worker; a second Install click must fail at claim time, not+ pass a read-only check and race the worker for the slot."""+ key = install.claim()+ with pytest.raises(install.InstallBusy):+ install.claim()+ with pytest.raises(install.InstallBusy):+ install.install_packages(ask_password=lambda: "pw", on_line=lambda _l: None)+ install.release(key)+ install.claim() # free again+ install.release(key)++[email protected]_only[email protected]("linux")+ def test_timeout_kills_the_package_managers_whole_process_group(monkeypatch):+ """sudo forks the package manager into the same (new) session; killing sudo alone leaves apt/dnf+ holding the dpkg lock as root. The timeout must take the group."""+ import subprocess+ import time++ monkeypatch.setattr(install, "_sudo_nopasswd", lambda: True)+ # stand-in for `sudo apt-get ...`: a parent that spawns a child and waits, both in the new session+ fake = ["sudo"]+ real_popen = subprocess.Popen++ def popen(argv, **kw):+ if argv[:1] != fake:+ return real_popen(argv, **kw)+ return real_popen(["bash", "-c", "sleep 30 >/dev/null 2>&1 & echo child $!; wait"], **kw)++ monkeypatch.setattr(install.subprocess, "Popen", popen)+ lines: list[str] = []+ code = install._run("sudo apt-get install -y x", ask_password=lambda: "", on_line=lines.append, timeout_seconds=0.5)+ assert code != 0+ child = next(int(line.split()[1]) for line in lines if line.startswith("child "))+ from pathlib import Path++ def gone() -> bool: # /proc-based: a reparented orphan sits outside our subtree, where os.kill(pid, 0) is guarded+ try:- return "Z" in (Path(f"/proc/{child}/stat").read_text(encoding="utf-8").rsplit(")", 1)[1].split() or ["Z"])[0]++ return "Z" in (Path(f"/proc/{child}/stat").read_text(encoding="utf-8-sig").rsplit(")", 1)[1].split() or ["Z"])[0]+ except OSError:+ return True++ for _ in range(50): # the child must die with the group, not linger reparented to init+ if gone():+ break+ time.sleep(0.1)+ else:+ subprocess.run(["kill", "-9", str(child)], check=False)+ pytest.fail("grandchild survived the install timeout")+++ def test_passwordless_sudo_runs_the_install_without_asking_for_a_password(monkeypatch):+ """A host with NOPASSWD sudo must not pop the masked password card — the card blocks the install+ for up to five minutes on an answer nobody needs to give — and the package command still runs+ and streams its output."""+ monkeypatch.setattr(install, "_sudo_nopasswd", lambda: True)+ spawned: list[list[str]] = []++ class _Proc:+ """Stands in for the sudo child: the drain reads the pipe by fd, so stdout is a real pipe with+ the output already written and the write end closed (EOF)."""+ pid = 4242+ returncode = 0+ stdin = __import__("io").StringIO()++ def __init__(self, argv, **kw):+ spawned.append(argv)+ r, w = os.pipe()+ os.write(w, b"Reading package lists...\nDone\n")+ os.close(w)+ self.stdout = os.fdopen(r, "rb")++ def wait(self, timeout=None):+ return 0++ def poll(self):+ return 0++ monkeypatch.setattr(install.subprocess, "Popen", _Proc)+ monkeypatch.setattr(install.os, "killpg", lambda *a: None)+ lines: list[str] = []+ code = install.install_packages(ask_password=lambda: pytest.fail("sudo password asked despite NOPASSWD"),+ on_line=lines.append)+ assert code == 0+ assert spawned and spawned[0][:1] == ["sudo"] and "-S" not in spawned[0]+ assert "Done" in lines++[email protected]_only[email protected]("linux")+ def test_timeout_returns_and_frees_the_slot_even_when_a_descendant_survives(monkeypatch):+ """From an unprivileged Hermes, killpg reaches the sudo leader but not a root-owned apt child; that+ child keeps the pipe's write end open, so draining stdout never sees EOF and the profile slot stays+ taken forever. The timeout must end the drain and release the slot regardless of what survived.+ Stand-in for the unkillable root child: a grandchild in its own session holding our stdout."""+ import subprocess+ import time++ monkeypatch.setattr(install, "_sudo_nopasswd", lambda: True)+ monkeypatch.setattr(install, "_TERM_GRACE_SECONDS", 0.2, raising=False)+ real_popen = subprocess.Popen++ def popen(argv, **kw):+ if argv[:1] != ["sudo"]:+ return real_popen(argv, **kw)+ return real_popen(["sh", "-c", "setsid sleep 30 & echo child $!; wait"], **kw)++ monkeypatch.setattr(install.subprocess, "Popen", popen)+ lines: list[str] = []+ started = time.monotonic()+ worker = threading.Thread(target=lambda: lines.append(+ f"code {install.install_packages(ask_password=lambda: '', on_line=lines.append, timeout_seconds=0.5)}"))+ worker.start()+ worker.join(3.0)+ survivor = next((int(line.split()[1]) for line in lines if line.startswith("child ")), None)+ if survivor:+ subprocess.run(["kill", "-9", str(survivor)], check=False)+ assert not worker.is_alive(), f"install_packages hung {time.monotonic() - started:.1f}s on a surviving descendant"+ assert any(line.startswith("code ") and line != "code 0" for line in lines), lines+ assert any("timed out" in line for line in lines), lines+ install.release(install.claim()) # slot is free again+++ def test_root_installs_without_sudo_and_without_asking(monkeypatch):+ """The official Docker image runs Hermes as uid 0 with no sudo binary: the package manager must be+ run directly, and the password card must never be raised for a user who already is root."""+ import subprocess++ monkeypatch.setattr(install.os, "geteuid", lambda: 0)+ monkeypatch.setattr("shutil.which", lambda name, *a, **k: None)+ monkeypatch.setattr(runtime, "package_manager", lambda: "apt")+ monkeypatch.setattr(runtime, "install_command", _REAL_INSTALL_COMMAND)+ spawned: list[list[str]] = []+ real_popen = subprocess.Popen++ def popen(argv, **kw):+ spawned.append(list(argv))+ return real_popen(["true"], **kw)++ monkeypatch.setattr(install.subprocess, "Popen", popen)+ code = install.install_packages(ask_password=lambda: pytest.fail("root was asked for a sudo password"),+ on_line=lambda _l: None)+ assert code == 0+ assert spawned and spawned[0][0] == "apt-get", spawned+++ def test_no_sudo_binary_returns_the_host_command_instead_of_a_password_card(monkeypatch):+ """Unprivileged with no sudo on the host (minimal containers): a password card would be a dead end,+ the user needs the exact command to run on the host instead."""+ monkeypatch.setattr(install.os, "geteuid", lambda: 1000)+ monkeypatch.setattr("shutil.which", lambda name, *a, **k: None)+ monkeypatch.setattr(install.subprocess, "Popen", lambda *a, **k: pytest.fail("package manager spawned"))+ lines: list[str] = []+ code = install.install_packages(ask_password=lambda: pytest.fail("password card raised without sudo"),+ on_line=lines.append)+ assert code == install.NO_SUDO+ assert any("apt-get install" in line for line in lines), lines+++ def test_timeout_finishes_the_group_when_only_the_leader_dies_on_term(monkeypatch):+ """TERM ends the leader shell at once, but a descendant in the same group that ignores TERM used to be+ left alive holding the dpkg lock: the kill helper returned as soon as the leader was reaped. Cleanup is+ done only when the whole process group is gone."""+ import subprocess+ import time++ monkeypatch.setattr(install, "_sudo_nopasswd", lambda: True)+ monkeypatch.setattr(install, "_TERM_GRACE_SECONDS", 0.3, raising=False)+ real_popen = subprocess.Popen++ def popen(argv, **kw):+ if argv[:1] != ["sudo"]:+ return real_popen(argv, **kw)+ return real_popen(["sh", "-c", "sh -c 'trap \"\" TERM; echo child $$; sleep 30' & wait"], **kw)++ monkeypatch.setattr(install.subprocess, "Popen", popen)+ lines: list[str] = []+ install.install_packages(ask_password=lambda: "", on_line=lines.append, timeout_seconds=0.5)+ child = next(int(line.split()[1]) for line in lines if line.startswith("child "))+ deadline = time.monotonic() + 2.0+ while time.monotonic() < deadline and _alive(child):+ time.sleep(0.05)+ try:+ assert not _alive(child), "the TERM-ignoring descendant survived the timeout cleanup"+ finally:+ subprocess.run(["kill", "-9", str(child)], check=False)+++ def _alive(pid: int) -> bool:- import os- try:- os.kill(pid, 0)- except ProcessLookupError:- return False- return True++ import psutil++++ return psutil.pid_exists(pid)+++ def test_install_slot_is_held_across_processes(tmp_path):+ """The gateway (Install card) and the CLI (`screen install`) are separate processes on one host: the+ single-flight must be a file lock in the profile's state dir, not only the in-process set."""+ import subprocess+ import sys++ key = install.claim()+ try:+ probe = subprocess.run([sys.executable, "-c",- "import fcntl,sys\nfh=open(sys.argv[1],'a+')\n"++ "import fcntl,sys\nfh=open(sys.argv[1],'a+',encoding='utf-8')\n"+ "try:\n fcntl.flock(fh.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB); print('free')\n"+ "except OSError:\n print('held')", str(runtime.state_dir() / "install.lock")],+ capture_output=True, text=True)+ assert probe.stdout.strip() == "held", probe+ finally:+ install.release(key)+ install.release(install.claim()) # freed: claimable againdiff --cc tests/tools/test_bot_desktop_launcher_seed.pyindex 00000000000,eab0685b3c9..9241b34e2bemode 000000,100644..100644--- a/tests/tools/test_bot_desktop_launcher_seed.py+++ b/tests/tools/test_bot_desktop_launcher_seed.py@@@ -1,0 -1,98 +1,102 @@@+ """Bot Desktop launcher seeds: the dock only points at programs that exist, the look is applied."""++ from __future__ import annotations++ import os+ import shutil+ import subprocess+ import xml.etree.ElementTree as ET+ from pathlib import Path++ import pytest++ LAUNCHER = Path(__file__).resolve().parents[2] / "tools" / "bot_desktop" / "launcher.sh"-pytestmark = pytest.mark.linux_only++pytestmark = pytest.mark.platforms("linux")+++ def _seed(tmp_path: Path, fake_bins: list[str], browser_exec: str = "", profile_dir: str = "") -> Path:+ bindir = tmp_path / "bin"+ bindir.mkdir(exist_ok=True)+ for name in fake_bins:+ exe = bindir / name+ exe.write_text("#!/bin/sh\n", encoding="utf-8")+ exe.chmod(0o755)++ # The launcher only needs xauth to accept the generated cookie; the test host need not ship X11 tools.++ xauth = bindir / "xauth"++ xauth.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")++ xauth.chmod(0o755)+ # The script's own tooling (mkdir, sed, cat, awk...) symlinked in, so PATH need not contain the+ # host's /usr/bin where a real chrome/thunar would leak into the dock under test.- for tool in ("mkdir", "sed", "cat", "printf", "dirname", "bash", "sh", "rm", "ln", "touch", "chmod", "xauth", "od", "tr", "awk"):++ for tool in ("mkdir", "sed", "cat", "printf", "dirname", "bash", "sh", "rm", "ln", "touch", "chmod", "xauth", "od", "tr", "awk", "grep"):+ real = shutil.which(tool)+ if real and not (bindir / tool).exists():+ (bindir / tool).symlink_to(real)+ cfg = tmp_path / "xdg"+ env = {+ "PATH": str(bindir),+ "HOME": str(tmp_path),+ "HERMES_BD_PROFILE": "t", "HERMES_BD_DISPLAY_NUM": "99",+ "HERMES_BD_SOCKET": str(tmp_path / "rfb.sock"), "HERMES_BD_XAUTH": str(tmp_path / "Xauthority"),+ "HERMES_BD_ENV_FILE": str(tmp_path / "env"), "HERMES_BD_CONFIG_HOME": str(cfg),+ "HERMES_BD_SEED_ONLY": "1",+ **({"HERMES_BD_BROWSER_EXEC": browser_exec, "HERMES_BD_BROWSER_EXEC_LINE": f"Exec={browser_exec} --user-data-dir={profile_dir or f'{tmp_path}/bp'}"} if browser_exec else {}),+ }+ subprocess.run(["bash", str(LAUNCHER)], env=env, check=True, stdin=subprocess.DEVNULL, capture_output=True, timeout=30)+ return cfg+++ def test_dock_lists_only_programs_present_on_path(tmp_path):+ chrome = tmp_path / "bin" / "chrome" # the browser is the one runtime.py resolved, never a PATH scan+ cfg = _seed(tmp_path, ["xfce4-terminal", "chrome", "firefox"], browser_exec=str(chrome))+ panel = ET.parse(cfg / "xfce4/xfconf/xfce-perchannel-xml/xfce4-panel.xml") # well-formed or this raises+ launcher_ids = [str(p.get("name")) for p in panel.iter("property") if p.get("value") == "launcher"]+ execs = sorted(+ line.split("=", 1)[1]+ for pid in launcher_ids- for line in (cfg / "xfce4/panel" / pid.replace("plugin-", "launcher-") / "hermes.desktop").read_text(encoding="utf-8").splitlines()++ for line in (cfg / "xfce4/panel" / pid.replace("plugin-", "launcher-") / "hermes.desktop").read_text(encoding="utf-8-sig").splitlines()+ if line.startswith("Exec=")+ )+ assert execs == [f"{chrome} --user-data-dir={tmp_path}/bp", "xfce4-terminal"]+++ def test_browser_launcher_follows_the_profile_without_reseeding_the_panel(tmp_path):+ """The panel layout is seeded once (the human may have rearranged it), but the Browser entry's Exec=+ binds the bot's user-data-dir by absolute path: after `hermes profile rename` the dock must open the+ renamed profile's cookie jar, the same one agent-browser now drives, while the layout stays untouched."""+ chrome = tmp_path / "bin" / "chrome"+ cfg = _seed(tmp_path, ["xfce4-terminal", "chrome"], browser_exec=str(chrome), profile_dir="/old name/bp")+ panel_xml = cfg / "xfce4/xfconf/xfce-perchannel-xml/xfce4-panel.xml"- layout_before = panel_xml.read_text(encoding="utf-8")++ layout_before = panel_xml.read_text(encoding="utf-8-sig")+ shutil.rmtree(tmp_path / "bin")+ _seed(tmp_path, ["xfce4-terminal", "chrome"], browser_exec=str(chrome), profile_dir="/new name/bp")+ execs = [+ line for d in (cfg / "xfce4/panel").glob("launcher-*/hermes.desktop")- for line in d.read_text(encoding="utf-8").splitlines() if line.startswith("Exec=") and "user-data-dir" in line++ for line in d.read_text(encoding="utf-8-sig").splitlines() if line.startswith("Exec=") and "user-data-dir" in line+ ]+ assert execs == [f"Exec={chrome} --user-data-dir=/new name/bp"]- assert panel_xml.read_text(encoding="utf-8") == layout_before++ assert panel_xml.read_text(encoding="utf-8-sig") == layout_before+++ def test_browser_launcher_seeded_before_the_marker_still_follows_a_rename(tmp_path):+ """Profiles seeded by an earlier launcher have the Browser entry but no `.hermes-browser-launcher`;+ a rename must still reach their Exec= (the marker is recovered from our own entry), not leave them+ opening the old profile's empty cookie jar forever."""+ chrome = tmp_path / "bin" / "chrome"+ cfg = _seed(tmp_path, ["xfce4-terminal", "chrome"], browser_exec=str(chrome), profile_dir="/old name/bp")+ (cfg / "xfce4/panel/.hermes-browser-launcher").unlink()+ shutil.rmtree(tmp_path / "bin")+ _seed(tmp_path, ["xfce4-terminal", "chrome"], browser_exec=str(chrome), profile_dir="/new name/bp")+ execs = [+ line for d in (cfg / "xfce4/panel").glob("launcher-*/hermes.desktop")- for line in d.read_text(encoding="utf-8").splitlines() if line.startswith("Exec=") and "user-data-dir" in line++ for line in d.read_text(encoding="utf-8-sig").splitlines() if line.startswith("Exec=") and "user-data-dir" in line+ ]+ assert execs == [f"Exec={chrome} --user-data-dir=/new name/bp"]+++ def test_look_is_seeded_with_wallpaper_and_theme(tmp_path):+ cfg = _seed(tmp_path, ["xfce4-terminal"])- desktop = (cfg / "xfce4/xfconf/xfce-perchannel-xml/xfce4-desktop.xml").read_text(encoding="utf-8")- xsettings = (cfg / "xfce4/xfconf/xfce-perchannel-xml/xsettings.xml").read_text(encoding="utf-8")++ desktop = (cfg / "xfce4/xfconf/xfce-perchannel-xml/xfce4-desktop.xml").read_text(encoding="utf-8-sig")++ xsettings = (cfg / "xfce4/xfconf/xfce-perchannel-xml/xsettings.xml").read_text(encoding="utf-8-sig")+ assert str(LAUNCHER.with_name("wallpaper.png")) in desktop+ assert "PLACEHOLDER" not in desktop + xsettings+ assert os.path.isfile(LAUNCHER.with_name("wallpaper.png"))diff --cc tests/tools/test_bot_desktop_launcher_xvnc.pyindex 00000000000,9db7f0651de..cea71597889mode 000000,100644..100644--- a/tests/tools/test_bot_desktop_launcher_xvnc.py+++ b/tests/tools/test_bot_desktop_launcher_xvnc.py@@@ -1,0 -1,44 +1,44 @@@+ """The Bot Desktop's Xvnc is started with the RFB options the lease design relies on."""++ from __future__ import annotations++ import os+ import shutil+ import subprocess+ from pathlib import Path++ import pytest++ LAUNCHER = Path(__file__).resolve().parents[2] / "tools" / "bot_desktop" / "launcher.sh"-pytestmark = pytest.mark.linux_only++pytestmark = pytest.mark.platforms("linux")+++ def test_xvnc_never_sends_the_holders_clipboard_to_watchers(tmp_path):+ """Whoever holds control may paste INTO the screen (AcceptCutText), but the screen's clipboard must+ not be pushed to every connected viewer (SendCutText off): watchers are not the holder."""+ bindir = tmp_path / "bin"+ bindir.mkdir()+ argv_log = tmp_path / "xvnc-argv"+ (bindir / "Xvnc").write_text(f'#!/bin/sh\nprintf "%s\\n" "$@" > "{argv_log}"\nexec sleep 3\n', encoding="utf-8")- for stub in ("xdpyinfo", "setxkbmap", "xsetroot", "xset", "dbus-run-session"):++ for stub in ("xdpyinfo", "setxkbmap", "xsetroot", "xset", "dbus-run-session", "xauth"):+ (bindir / stub).write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")+ for exe in bindir.iterdir():+ exe.chmod(0o755)- for tool in ("mkdir", "sed", "cat", "printf", "dirname", "bash", "sh", "rm", "ln", "touch", "chmod", "xauth", "od", "tr", "awk", "seq", "sleep", "kill"):++ for tool in ("mkdir", "sed", "cat", "printf", "dirname", "bash", "sh", "rm", "ln", "touch", "chmod", "xauth", "od", "tr", "awk", "grep", "seq", "sleep", "kill"):+ real = shutil.which(tool)+ if real and not (bindir / tool).exists():+ (bindir / tool).symlink_to(real)+ env = {+ "PATH": str(bindir), "HOME": str(tmp_path),+ "HERMES_BD_PROFILE": "t", "HERMES_BD_DISPLAY_NUM": "99",+ "HERMES_BD_SOCKET": str(tmp_path / "rfb.sock"), "HERMES_BD_XAUTH": str(tmp_path / "Xauthority"),+ "HERMES_BD_ENV_FILE": str(tmp_path / "env"), "HERMES_BD_CONFIG_HOME": str(tmp_path / "xdg"),+ }+ subprocess.run(["bash", str(LAUNCHER)], env=env, check=True, stdin=subprocess.DEVNULL, capture_output=True, timeout=30)- argv = argv_log.read_text(encoding="utf-8").split("\n")++ argv = argv_log.read_text(encoding="utf-8-sig").split("\n")+ assert "-SendCutText=0" in argv, argv+ assert not any(a.startswith("-AcceptCutText") for a in argv), "paste into the screen must keep working"+ # Xvnc's own cut-text cap and the bridge filter's must agree, or one side drops a paste the other admits.+ from tools.bot_desktop.rfb_filter import _MAX_CUT_TEXT+ assert int(argv[argv.index("-MaxCutText") + 1]) == _MAX_CUT_TEXT, argv+ assert not os.path.exists(tmp_path / "rfb.sock") # stub never bound it; nothing leakeddiff --cc tests/tools/test_bot_desktop_lease.pyindex 00000000000,5023c5bf594..8cc83fed2a8mode 000000,100644..100644--- a/tests/tools/test_bot_desktop_lease.py+++ b/tests/tools/test_bot_desktop_lease.py@@@ -1,0 -1,212 +1,212 @@@+ """Bot Desktop invariants: the byte-level RFB input gate follows the lease, and computer_use refuses+ every action (capture included) while a human holds the screen."""++ from __future__ import annotations++ import json++ import pytest++ from tools.bot_desktop import lease+ from tools.bot_desktop.rfb_filter import RfbClientFilter++ _HANDSHAKE = b"RFB 003.008\n" + b"\x01" + b"\x00"+ _KEY = b"\x04\x01\x00\x00\x00\x00\x00\x61" # KeyEvent 'a' down+ # QEMU Extended KeyEvent (type 255, sub 0): what noVNC sends once Xvnc advertises the pseudo-encoding.+ _QEMU_KEY = bytes([255, 0, 0, 1]) + (0x65).to_bytes(4, "big") + (0x12).to_bytes(4, "big")+ _POINTER = b"\x05\x01\x00\x10\x00\x10" # PointerEvent, button 1+ _CUT = b"\x06\x00\x00\x00\x00\x00\x00\x02hi" # ClientCutText "hi"+ _FBUR = b"\x03\x00" + b"\x00" * 8 # FramebufferUpdateRequest+ _SETENC = b"\x02\x00\x00\x02" + b"\x00\x00\x00\x07" + b"\xff\xff\xff\x21" # SetEncodings x2+++ @pytest.fixture(autouse=True)+ def _fresh_lease():+ from tools.computer_use import tool++ tool.reset_backend_for_tests()+ lease._reset_for_tests()+ yield+ tool.reset_backend_for_tests()+ lease._reset_for_tests()+++ def test_rfb_filter_forwards_input_only_from_the_lease_holder_across_arbitrary_chunking():+ f = RfbClientFilter(lambda: lease.viewer_may_send_input("v1"))+ head = f.feed(_HANDSHAKE)+ assert head[-1:] == b"\x01", "ClientInit is forced shared so a viewer never kicks the agent's watcher"++ # Agent holds: read-only messages pass, input is dropped, even when split byte by byte.+ stream = _KEY + _FBUR + _POINTER + _SETENC + _CUT + _QEMU_KEY+ out = b"".join(f.feed(stream[i:i + 1]) for i in range(len(stream)))+ assert out == _FBUR + _SETENC++ lease.acquire("v1")+ assert f.feed(_KEY + _POINTER + _QEMU_KEY) == _KEY + _POINTER + _QEMU_KEY++ lease.acquire("v2") # last writer wins: v1 is evicted from input on the very next message+ assert f.feed(_KEY) == b""+ assert lease.release("v1").holder == lease.HUMAN, "a stale viewer's release must not yank control from v2"+ assert lease.release("v2").holder == lease.AGENT+++ def test_computer_use_refuses_every_action_while_a_human_holds_the_screen(monkeypatch):+ from tools.computer_use import tool++ calls = []+ monkeypatch.setattr(tool, "_get_backend", lambda session_id="": calls.append(session_id) or object())+ lease.acquire("human")+ for action in ("capture", "click", "type", "list_windows"):+ res = json.loads(tool.handle_computer_use({"action": action, "text": "pw"}))+ assert res["code"] == "human_has_control", action+ assert calls == [], "the driver is never touched while the human may be typing a credential"+ lease.release("human")+ assert lease.get().holder == lease.AGENT+++ def test_lease_authority_is_shared_across_processes(tmp_path):+ """The gateway that streams the screen and the process running the agent are different processes;+ a human takeover in one must refuse actions in the other."""+ import os+ import subprocess+ import sys++ lease.acquire("desktop-viewer")+ probe = ("import sys; sys.path.insert(0, %r)\n"+ "from tools.bot_desktop import lease\n"+ "try:\n lease.assert_agent_may_act(); print('AGENT')\n"+ "except lease.HumanHasControl:\n print('HUMAN')\n"+ "lease.release('desktop-viewer')\n") % os.getcwd()+ out = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True, encoding="utf-8", timeout=30,+ stdin=subprocess.DEVNULL, env={**os.environ, "HERMES_HOME": os.environ["HERMES_HOME"]})+ assert out.stdout.strip() == "HUMAN", out.stderr+ assert lease.get().holder == lease.AGENT, "the other process's release is visible here"+++ def test_takeover_during_an_admitted_action_discards_its_result(monkeypatch):+ """Approval / backend start-up can take seconds; a human who takes over meanwhile must not have+ their keystrokes captured by an action admitted before they did."""+ from tools.computer_use import tool++ monkeypatch.setattr(tool, "_new_backend", lambda mode: tool._NoopBackend())++ def _dispatch_then_takeover(backend, action, args, **_):+ lease.acquire("human") # a whole take-over / hand-back cycle inside the driver call:+ lease.release("human") # control is back, but the frame is still the human's turn+ return json.dumps({"ok": True, "action": action, "png_b64": "SECRET"})++ monkeypatch.setattr(tool, "_dispatch", _dispatch_then_takeover)+ res = json.loads(tool.handle_computer_use({"action": "capture"}))+ assert res["code"] == "human_has_control" and "SECRET" not in json.dumps(res)+++ def test_takeover_handback_during_approval_does_not_start_the_device_op(monkeypatch):+ """A full take-over / hand-back during approval leaves holder=agent, so assert_agent_may_act+ succeeds. Input still belongs to the human's turn: compare admitted.epoch before _dispatch,+ not only after. Do not patch _dispatch — a recording backend must never be called."""+ from tools.computer_use import tool++ class Rec(tool._NoopBackend):+ def __init__(self):+ self.calls = []++ def click(self, **_kw):+ self.calls.append("click")+ return json.dumps({"ok": True, "action": "click"})++ rec = Rec()+ monkeypatch.setattr(tool, "_new_backend", lambda mode: rec)++ def _approval_cycles_the_lease(scope, args, session_id=""):+ lease.acquire("human")+ lease.release("human")+ return None++ monkeypatch.setattr(tool, "_request_approval", _approval_cycles_the_lease)+ res = json.loads(tool.handle_computer_use({"action": "click", "coordinate": [1, 1]}))+ assert rec.calls == []+ assert res.get("code") == "human_has_control"+++ def test_unreadable_lease_file_fails_closed_and_takeover_keeps_the_agents_reason(tmp_path):+ """Missing file = fresh profile (agent). A file that exists but cannot be parsed must not read as+ "agent holds": a torn write must never let the agent act on a human's screen. Taking over after a+ request keeps the agent's reason so the human still sees WHY while they act."""+ from hermes_constants import hermes_home_key++ home = str(tmp_path)+ assert lease.get(profile_key=home).holder == lease.AGENT+ path = lease._path(home)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("{ torn", encoding="utf-8")+ assert lease.get(profile_key=home).holder == lease.HUMAN+ lease.release(profile_key=home) # a successful write repairs it+ assert lease.get(profile_key=home).holder == lease.AGENT++ # Valid JSON of the wrong shape is just as untrustworthy as torn JSON: never read it as "agent holds".+ for wrong_shape in ("[]", "null", "5", "{}", '{"holder": "root"}'):+ path.write_text(wrong_shape, encoding="utf-8")+ assert lease.get(profile_key=home).holder == lease.HUMAN, wrong_shape+ lease.release(profile_key=home)+ assert lease.get(profile_key=home).holder == lease.AGENT++ held = lease.acquire("desk-1", reason="log in to the bank, 2FA on your phone", profile_key=home)+ assert held.reason == "log in to the bank, 2FA on your phone"+ assert hermes_home_key(home) # sanity: the key derivation used by the bridge is available+++ def test_lease_works_without_fcntl(tmp_path):+ """Windows and fcntl-less hosts: ``computer_use`` imports the lease on EVERY call, so a module-level+ fcntl dependency turns every desktop action into ModuleNotFoundError there. The file semantics must+ still work; only the cross-process lock degrades. Subprocess so the module cache is clean."""+ import os+ import subprocess+ import sys++ probe = ("import sys; sys.modules['fcntl'] = None; sys.path.insert(0, %r)\n"+ "from tools.bot_desktop import lease\n"+ "import tools.computer_use.tool\n"+ "assert lease.get().holder == lease.AGENT\n"+ "assert lease.acquire('v1').holder == lease.HUMAN\n"+ "assert lease.get().holder == lease.HUMAN\n"+ "assert lease.release('v1').holder == lease.AGENT\n"+ "print('OK')\n") % os.getcwd()+ out = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True, encoding="utf-8", timeout=60,+ stdin=subprocess.DEVNULL, env={**os.environ, "HERMES_HOME": str(tmp_path)})+ assert out.stdout.strip() == "OK", out.stderr++[email protected]_only[email protected]("linux")+ def test_lease_files_are_private_even_when_the_lease_is_written_before_the_screen_exists(tmp_path, monkeypatch):+ """A takeover can be recorded before start() ever created bot-desktop/ 0700. The lease path then created+ the directory and files with the umask (0755 / 0644): who holds the screen, and the lock the RFB bridge+ serialises on, readable and clobberable by every other local user. Every piece must be owner-only."""+ import os+ import stat++ home = tmp_path / "deep" / "home"+ home.mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(lease, "get_hermes_home", lambda: home)+ old = os.umask(0o022)+ try:+ lease.acquire("v1")+ finally:+ os.umask(old)+ sd = home / "bot-desktop"+ for path in (sd, sd / "lease.json", sd / "lease.lock"):+ assert path.exists(), path+ assert stat.S_IMODE(path.stat().st_mode) & 0o077 == 0, f"{path.name} is {oct(path.stat().st_mode)}"+++ def test_no_op_transitions_do_not_bump_the_epoch():+ """Callers void an admitted in-flight action when the epoch moved. A release on an agent-held lease+ (double-clicked Hand back, a stray CLI stop) or the same viewer re-acquiring changes nothing real, so+ it must not make a legitimate agent action look overtaken."""+ e0 = lease.get().epoch+ assert lease.release().epoch == e0+ got = lease.acquire("v1", reason="log in please")+ assert got.epoch == e0 + 1+ again = lease.acquire("v1")+ assert again.epoch == got.epoch and again.reason == "log in please" and again.since == got.since+ assert lease.acquire("v2").epoch == got.epoch + 1 # a different viewer IS a transitiondiff --cc tests/tools/test_bot_desktop_resources.pyindex 00000000000,f49d90e3e1f..eb28dc13362mode 000000,100644..100644--- a/tests/tools/test_bot_desktop_resources.py+++ b/tests/tools/test_bot_desktop_resources.py@@@ -1,0 -1,64 +1,64 @@@+ """Bot Desktop memory gate: the screen is refused, with a reason clients can show, while the host+ cannot spare ``bot_desktop.min_free_memory_mb``; a host we cannot read is never treated as small."""++ from __future__ import annotations++ import pytest++ from tools.bot_desktop import resources, runtime+++ def test_start_refuses_and_status_explains_when_memory_is_short(tmp_path, monkeypatch):+ monkeypatch.setattr(runtime, "state_dir", lambda: tmp_path / "bd")+ monkeypatch.setattr(runtime, "missing_binaries", lambda: [])+ monkeypatch.setattr(runtime, "_launcher_pid", lambda: None)+ monkeypatch.setattr(resources, "min_free_mb", lambda: 1536)+ monkeypatch.setattr(resources, "memory_info", lambda: resources.MemoryInfo(available_mb=900, limit_mb=4096))+ spawned = []+ monkeypatch.setattr(runtime, "_spawn_and_wait", lambda *a, **k: spawned.append(a))++ st = runtime.status()+ assert st.running is False and st.blocker and "900 MB" in st.blocker and "4096 MB" in st.blocker+ assert st.memory_available_mb == 900 and st.memory_limit_mb == 4096+ with pytest.raises(RuntimeError, match="Not enough free memory"):+ runtime.start()+ assert spawned == [], "the launcher must not be spawned on a host that cannot hold it"+++ @pytest.mark.parametrize("info", [+ resources.MemoryInfo(available_mb=None, limit_mb=None), # unreadable: not evidence of a small host+ resources.MemoryInfo(available_mb=1536, limit_mb=2048), # exactly the threshold is enough+ ])+ def test_unknown_or_sufficient_memory_never_blocks(monkeypatch, info):+ monkeypatch.setattr(resources, "min_free_mb", lambda: 1536)+ assert resources.memory_blocker(info) is None+++ def test_running_screen_is_not_reported_blocked_by_later_pressure(tmp_path, monkeypatch):+ """The gate guards the allocation; once the desktop is up, memory pressure is the browser's problem,+ not a reason to tell the pane its running screen is blocked."""+ monkeypatch.setattr(runtime, "state_dir", lambda: tmp_path / "bd")+ monkeypatch.setattr(runtime, "missing_binaries", lambda: [])+ monkeypatch.setattr(runtime, "_launcher_pid", lambda: 4242)+ monkeypatch.setattr(runtime, "published_env", lambda: {"DISPLAY": ":20"})+ monkeypatch.setattr(resources, "min_free_mb", lambda: 1536)+ monkeypatch.setattr(resources, "memory_info", lambda: resources.MemoryInfo(available_mb=100, limit_mb=4096))+ st = runtime.status()+ assert st.running is True and st.blocker is None+++ def test_memory_info_takes_the_tighter_of_cgroup_and_host(tmp_path, monkeypatch):+ """A 16 GB cgroup limit on a 4 GB box is still a 4 GB box; a 2 GB limit on a 64 GB box is 2 GB."""+ v2 = tmp_path / "cg"; v2.mkdir()+ monkeypatch.setattr(resources, "_CGROUP_V2", v2)+ monkeypatch.setattr(resources, "_CGROUP_V1", tmp_path / "nope")+ meminfo = tmp_path / "meminfo"+ monkeypatch.setattr(resources, "_MEMINFO", meminfo)- meminfo.write_text("MemTotal: 4194304 kB\nMemAvailable: 3145728 kB\n")- (v2 / "memory.max").write_text(str(16 * 1024 ** 3)); (v2 / "memory.current").write_text(str(1024 ** 3))++ meminfo.write_text("MemTotal: 4194304 kB\nMemAvailable: 3145728 kB\n", encoding="utf-8")++ (v2 / "memory.max").write_text(str(16 * 1024 ** 3), encoding="utf-8"); (v2 / "memory.current").write_text(str(1024 ** 3), encoding="utf-8")+ assert resources.memory_info().available_mb == 3072- (v2 / "memory.max").write_text(str(2 * 1024 ** 3))++ (v2 / "memory.max").write_text(str(2 * 1024 ** 3), encoding="utf-8")+ info = resources.memory_info()+ assert info.available_mb == 1024 and info.limit_mb == 2048- (v2 / "memory.max").write_text("max") # no limit: host numbers++ (v2 / "memory.max").write_text("max", encoding="utf-8") # no limit: host numbers+ assert resources.memory_info() == resources.MemoryInfo(available_mb=3072, limit_mb=4096)diff --cc tests/tools/test_bot_desktop_runtime.pyindex 00000000000,45500aee831..d90913fbe62mode 000000,100644..100644--- a/tests/tools/test_bot_desktop_runtime.py+++ b/tests/tools/test_bot_desktop_runtime.py@@@ -1,0 -1,367 +1,377 @@@+ """Bot Desktop runtime: thumbnail and display-number allocation invariants."""++ from __future__ import annotations++ import contextlib+ import threading+ import time+ import sys+ from pathlib import Path++ import pytest++ from tools.bot_desktop import runtime, thumbnail+++ @pytest.mark.parametrize("pm", sorted(runtime.PACKAGES))+ def test_every_required_binary_maps_to_an_installed_package(pm):+ """Each binary the launcher execs must come from a package the distro list actually installs; dnf5+ refuses the whole transaction on one retired name, so the map is the contract, not the list."""+ mapping = runtime.BINARY_PACKAGES[pm]+ assert set(mapping) == set(runtime.REQUIRED_BINARIES)+ assert set(mapping.values()) <= set(runtime.PACKAGES[pm])+ assert not {"xorg-x11-server-utils", "xorg-x11-utils"} & set(runtime.PACKAGES["dnf"]), "retired on Fedora"+++ def test_no_running_screen_returns_none_without_grabbing(monkeypatch):+ monkeypatch.setattr(runtime, "published_env", lambda: {"DISPLAY": ":99"})+ monkeypatch.setattr(runtime, "_launcher_pid", lambda: None)+ monkeypatch.setitem(sys.modules, "PIL.ImageGrab", None) # an import would now fail loudly+ assert thumbnail.thumbnail_data_url() is None+++ def test_recycled_pid_is_not_our_launcher(tmp_path, monkeypatch):+ """launcher.pid names pid + create_time; a live pid born at another time is a stranger (recycled pid)+ and must read as not running, or stop() would killpg an unrelated session. Legacy single-number+ files and absurd digit strings are also not running."""+ import os++ monkeypatch.setattr(runtime, "state_dir", lambda: tmp_path)+ pidfile = tmp_path / "launcher.pid"+ pidfile.write_text(f"{os.getpid()} 12345.0", encoding="utf-8") # alive, wrong birth+ assert runtime._launcher_pid() is None+ pidfile.write_text(str(os.getpid()), encoding="utf-8") # pre-identity format+ assert runtime._launcher_pid() is None+ pidfile.write_text("9" * 40 + " 1.0", encoding="utf-8")+ assert runtime._launcher_pid() is None+ pidfile.write_text(f"{os.getpid()} {runtime._create_time(os.getpid())}", encoding="utf-8")+ assert runtime._launcher_pid() == os.getpid()+++ def test_recorded_display_held_by_a_live_server_is_not_reused(tmp_path, monkeypatch):+ """After profile A stops, B may take A's number; A restarting must pick another rather than+ unlink B's socket and lock."""+ import os++ monkeypatch.setattr(runtime, "state_dir", lambda: tmp_path)+ (tmp_path / "display").write_text("37", encoding="utf-8")+ live = {37: os.getpid()} # :37 is owned by a running server (this very process stands in for it)+ monkeypatch.setattr(runtime, "_display_in_use", lambda num: num in live)+ monkeypatch.setattr(runtime, "_ALLOC_LOCK", tmp_path / "alloc.lock")+ assert runtime._allocate_display() != 37+ live.clear()+ assert runtime._allocate_display() == 37, "a free recorded number is reclaimed"+++ def test_live_server_without_its_lock_file_still_owns_the_display(tmp_path, monkeypatch):+ """Regression for #109941: a /tmp reaper removes ``.X<n>-lock`` while Xvnc keeps running. The server's+ abstract socket ``@/tmp/.X11-unix/X<n>`` stays bound for its whole life, so that is the liveness the+ allocator must honour — handing the number out makes the next launcher die with 'server already running'."""+ monkeypatch.setattr(runtime, "_X_LOCK_DIR", tmp_path / "xlocks") # no lock file for anyone+ (tmp_path / "xlocks").mkdir()+ table = tmp_path / "unix"+ table.write_text(+ "Num RefCount Protocol Flags Type St Inode Path\n"+ "0000000000000000: 00000002 00000000 00010000 0001 01 22242 @/tmp/.X11-unix/X20\n"+ "0000000000000000: 00000002 00000000 00010000 0001 01 22243 /tmp/.X11-unix/X21\n"+ "0000000000000000: 00000003 00000000 00000000 0001 03 22244 @/tmp/.X11-unix/X200\n", encoding="utf-8")+ monkeypatch.setattr(runtime, "_X_UNIX_TABLE", table)+ assert runtime._display_in_use(20) is True+ assert runtime._display_in_use(21) is True+ assert runtime._display_in_use(22) is False # :200 is not :22 — no prefix matching+ monkeypatch.setattr(runtime, "_X_UNIX_TABLE", tmp_path / "missing")+ assert runtime._display_in_use(20) is False, "no table (non-Linux procfs) falls back to the lock alone"++++ _FAKE_LAUNCHER = """#!/usr/bin/env bash+ # Stands in for launcher.sh + Xvnc: the X lock appears only after a delay (the TOCTOU window), then the+ # env file + socket are published; stays alive until killed like the real supervisor.+ : > "$HERMES_BD_XLOCK_DIR/spawned.$$"+ sleep 0.4+ echo $$ > "$HERMES_BD_XLOCK_DIR/.X${HERMES_BD_DISPLAY_NUM}-lock"+ : > "$HERMES_BD_SOCKET"+ printf 'DISPLAY=:%s\\n' "$HERMES_BD_DISPLAY_NUM" > "$HERMES_BD_ENV_FILE"+ sleep 30+ """++ # One start() per process: state_dir() is HERMES_HOME-scoped and process-global, so two profiles need two+ # interpreters — which is also how two gateway profiles race on a real host.+ _DRIVER = """+ import json, os, sys+ from pathlib import Path+ sys.path.insert(0, {repo!r})+ from tools.bot_desktop import runtime+ scratch = Path({scratch!r})+ runtime._LAUNCHER = scratch / "launcher.sh"+ runtime._X_LOCK_DIR = scratch / "xlocks"+ runtime._ALLOC_LOCK = scratch / "alloc.lock"+ runtime.missing_binaries = lambda: []+ runtime.geometry = lambda: "800x600"+ os.environ["HERMES_BD_XLOCK_DIR"] = str(scratch / "xlocks")+ try:+ st = runtime.start(wait_seconds=10)+ print(json.dumps({{"display": st.display, "pid": st.pid}}), flush=True)+ except Exception as exc:+ print(json.dumps({{"error": str(exc)}}), flush=True)+ sys.stdin.readline() # the test releases us once every driver has reported; we own the launcher, we stop it+ runtime.stop()+ """+++ @pytest.fixture+ def start_in_fresh_process(tmp_path):+ import os+ import subprocess++ (tmp_path / "launcher.sh").write_text(_FAKE_LAUNCHER, encoding="utf-8")+ (tmp_path / "xlocks").mkdir()+ repo = str(Path(__file__).resolve().parents[2])+ procs: list[subprocess.Popen] = []++ def launch(home: Path) -> subprocess.Popen:+ env = {**os.environ, "HERMES_HOME": str(home)}+ proc = subprocess.Popen([sys.executable, "-c", _DRIVER.format(repo=repo, scratch=str(tmp_path))],+ env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)+ procs.append(proc)+ return proc++ yield launch+ for proc in procs:+ with contextlib.suppress(OSError):+ proc.communicate("go\n", timeout=20)+ proc.kill()+++ def _collect(procs):+ import json+ out = [json.loads(p.stdout.readline()) for p in procs] # every driver holds its launcher until released+ assert all("error" not in o for o in out), out+ return out++[email protected]_only[email protected]("linux")+ def test_concurrent_cold_starts_of_two_profiles_get_distinct_displays(tmp_path, start_in_fresh_process):+ """The allocation lock must outlive the pick: Xvnc writes /tmp/.X<n>-lock well after start() chose n, so+ a second profile starting in that window used to pick the same n (and its launcher's stale-lock cleanup+ could then unlink the winner's socket)."""+ out = _collect([start_in_fresh_process(tmp_path / "a"), start_in_fresh_process(tmp_path / "b")])+ assert len({o["display"] for o in out}) == 2, out++[email protected]_only[email protected]("linux")+ def test_concurrent_starts_of_one_profile_spawn_one_launcher(tmp_path, start_in_fresh_process):+ """Two start() calls for one profile spawn ONE launcher; the second used to spawn its own, overwrite+ launcher.pid and orphan the first (both callers then reported the last-written pid)."""+ out = _collect([start_in_fresh_process(tmp_path / "a"), start_in_fresh_process(tmp_path / "a")])+ assert len({o["pid"] for o in out}) == 1, out+ assert len(list((tmp_path / "xlocks").glob("spawned.*"))) == 1+++ _ORPHANING_LAUNCHER = """#!/usr/bin/env bash+ # Stands in for launcher.sh whose Xvnc child ("sleep") lives in the launcher's process group and+ # outlives a SIGKILL of the launcher itself — the X lock names the child, as the real one does.+ : > "$HERMES_BD_XLOCK_DIR/spawned.$$"+ sleep 30 &+ echo $! > "$HERMES_BD_XLOCK_DIR/.X${HERMES_BD_DISPLAY_NUM}-lock"+ : > "$HERMES_BD_SOCKET"+ printf 'DISPLAY=:%s\\n' "$HERMES_BD_DISPLAY_NUM" > "$HERMES_BD_ENV_FILE"+ wait+ """+++ def _gone(pid: int) -> bool:+ import psutil+ try:+ return psutil.Process(pid).status() == psutil.STATUS_ZOMBIE+ except psutil.NoSuchProcess:+ return True+++ def _wait_until(pred, timeout=5.0) -> bool:+ import time+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if pred():+ return True+ time.sleep(0.05)+ return pred()+++ @pytest.fixture+ def in_process_runtime(tmp_path, monkeypatch):+ """runtime.start()/stop() against a scratch state dir and a fake launcher script (set by the test)."""+ import os++ home = tmp_path / "home"+ (tmp_path / "xlocks").mkdir()+ monkeypatch.setattr(runtime, "state_dir", lambda: home / "bot-desktop")+ monkeypatch.setattr(runtime, "_LAUNCHER", tmp_path / "launcher.sh")+ monkeypatch.setattr(runtime, "_X_LOCK_DIR", tmp_path / "xlocks")+ monkeypatch.setattr(runtime, "_X_UNIX_TABLE", tmp_path / "unix") # the host's real X servers stay out of the band+ monkeypatch.setattr(runtime, "_ALLOC_LOCK", tmp_path / "alloc.lock")+ monkeypatch.setattr(runtime, "missing_binaries", lambda: [])+ monkeypatch.setattr(runtime, "geometry", lambda: "800x600")+ monkeypatch.setenv("HERMES_BD_XLOCK_DIR", str(tmp_path / "xlocks"))+ yield tmp_path+ with contextlib.suppress(Exception):+ runtime.stop()+ for lock in (tmp_path / "xlocks").glob(".X*-lock"): # anything the code under test failed to reap+ with contextlib.suppress(OSError, ValueError):- os.kill(int(lock.read_text()), 9)++ os.kill(int(lock.read_text(encoding="utf-8-sig")), 9)++[email protected]_only[email protected]("linux")+ @pytest.mark.live_system_guard_bypass # the orphan is reparented to init: signalling it is the point+ def test_orphaned_x_server_of_a_dead_launcher_is_reaped_on_next_start(in_process_runtime):+ """SIGKILL the launcher and its Xvnc survives, holding the display and rfb.sock. status() keys on the+ launcher pid and says stopped; start() must find that orphan through the recorded display's X lock+ and kill it instead of allocating a second server beside it (two servers, one socket path)."""+ import os+ import signal++ scratch = in_process_runtime+ (scratch / "launcher.sh").write_text(_ORPHANING_LAUNCHER, encoding="utf-8")+ first = runtime.start(wait_seconds=10)+ lock = scratch / "xlocks" / f".X{first.display.lstrip(':')}-lock"- orphan = int(lock.read_text())- os.kill(first.pid, signal.SIGKILL)++ orphan = int(lock.read_text(encoding="utf-8-sig"))++ os.kill(first.pid, signal.SIGKILL) # windows-footgun: ok — Linux-only test requires an uncatchable launcher death+ assert _wait_until(lambda: _gone(first.pid))+ assert not _gone(orphan), "the X server outlives its launcher (that is the bug's precondition)"+ assert runtime.status().running is False++ second = runtime.start(wait_seconds=10)+ assert second.pid != first.pid and second.running+ assert _wait_until(lambda: _gone(orphan)), "the dead launcher's X server must be reaped, not leaked"+ assert runtime.stop() is True++[email protected]_only[email protected]("linux")+ @pytest.mark.live_system_guard_bypass # the orphan is reparented to init: signalling it is the point+ def test_orphaned_x_server_is_found_by_its_socket_when_the_lock_file_is_gone(tmp_path, monkeypatch):+ """Case B of #109941: the launcher was SIGKILLed AND a /tmp reaper removed ``.X<n>-lock`` (or the failed+ launch dropped ``display``). The lock was the reaper's only handle, so the live Xvnc leaked forever and+ each restart allocated a new number beside it. The socket path on its command line names it too."""+ import os- import shutil+ import subprocess++ sd = tmp_path / "bot-desktop"+ sd.mkdir()+ (sd / "rfb.sock").touch()+ (sd / "launcher.pid").write_text("1 0.0", encoding="utf-8") # a dead launcher, not our process group+ monkeypatch.setattr(runtime, "_X_LOCK_DIR", tmp_path / "xlocks") # no lock file at all+ (tmp_path / "xlocks").mkdir()- # argv[0] names the fake Xvnc and argv carries our socket path, exactly what launcher.sh's Xvnc shows;- # `tail -f` on the socket file just blocks like a server would (a multicall coreutils rejects a symlink).- orphan = subprocess.Popen([str(tmp_path / "Xvnc"), "-f", str(sd / "rfb.sock")], executable=shutil.which("tail"),++ # argv[0] names the fake Xvnc and argv carries our socket path, exactly what launcher.sh's Xvnc shows.++ # Python is the portable long-lived payload here: Nix's multicall coreutils dispatches from argv[0], so++ # executing `tail` under the Xvnc spelling exits immediately instead of establishing the precondition.++ orphan = subprocess.Popen([str(tmp_path / "Xvnc"), "-c", "import time; time.sleep(60)", str(sd / "rfb.sock")], executable=sys.executable,+ start_new_session=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL)+ try:++ import psutil++++ def orphan_command_is_published() -> bool:++ try:++ command = psutil.Process(orphan.pid).cmdline()++ except psutil.Error:++ return False++ return bool(command and "Xvnc" in Path(command[0]).name and str(sd / "rfb.sock") in command)++++ assert _wait_until(orphan_command_is_published), "establish the psutil discovery precondition"+ assert runtime._reap_orphaned_server(sd) is True+ assert _wait_until(lambda: _gone(orphan.pid)), "the lock-less orphan must be reaped, not leaked"+ assert not (sd / "rfb.sock").exists()+ finally:+ with contextlib.suppress(ProcessLookupError):+ os.kill(orphan.pid, 9)+ orphan.wait()+++ _SLOW_LAUNCHER = """#!/usr/bin/env bash+ # Publishes only AFTER runtime.start()'s readiness deadline has passed.+ sleep 30 &+ echo $! > "$HERMES_BD_XLOCK_DIR/.X${HERMES_BD_DISPLAY_NUM}-lock"+ sleep 1+ : > "$HERMES_BD_SOCKET"+ printf 'DISPLAY=:%s\\n' "$HERMES_BD_DISPLAY_NUM" > "$HERMES_BD_ENV_FILE"+ wait+ """++[email protected]_only[email protected]("linux")+ @pytest.mark.live_system_guard_bypass # the launcher's group must really be signalled+ def test_readiness_timeout_terminates_the_launch_it_gave_up_on(in_process_runtime):+ """When the launcher misses the readiness deadline start() raises — and must take the launch down with+ it. It used to leave the launcher running; the child then published DISPLAY/rfb.sock a moment later and+ a screen nobody asked for (and whose start() had reported failure) stayed up behind a 'running' status."""+ import time++ scratch = in_process_runtime+ (scratch / "launcher.sh").write_text(_SLOW_LAUNCHER, encoding="utf-8")+ sd = runtime.state_dir()+ with pytest.raises(RuntimeError, match="did not publish"):+ runtime.start(wait_seconds=0.05)+ launcher = runtime._recorded_launcher_pid()+ assert launcher is None or _gone(launcher), "the timed-out launcher must be reaped, not left to publish later"+ time.sleep(1.5) # past the slow launcher's publish time+ assert not (sd / "env").exists() and not (sd / "rfb.sock").exists()+ assert runtime.status().running is False+ for lock in (scratch / "xlocks").glob(".X*-lock"):- assert _gone(int(lock.read_text())), "the launch's X server must die with its launcher"++ assert _gone(int(lock.read_text(encoding="utf-8-sig"))), "the launch's X server must die with its launcher"+++ _DYING_LAUNCHER = """#!/usr/bin/env bash+ # Xvnc refusing the number ('server already running'): the launcher exits non-zero at once.+ exit 1+ """++[email protected]_only[email protected]("linux")+ def test_failed_start_does_not_pin_the_profile_to_the_number_that_failed(in_process_runtime):+ """Regression for #109941: after a launcher failure the recorded ``display`` kept naming the number, and+ ``_pick_display`` reuses the recorded number first — so every retry picked the same occupied display and+ the profile wedged. A failed start forgets its number; the next attempt allocates afresh."""+ scratch = in_process_runtime+ (scratch / "launcher.sh").write_text(_DYING_LAUNCHER, encoding="utf-8")+ sd = runtime.state_dir()+ with pytest.raises(RuntimeError, match="launcher exited"):+ runtime.start(wait_seconds=5)+ assert not (sd / "display").exists(), "a number that just failed must not be recorded for reuse"++[email protected]_only[email protected]("linux")+ def test_allocation_lock_is_released_once_xvnc_claims_the_number(in_process_runtime):+ """The host-wide allocation lock exists for the pick→X-lock window only. Holding it for the whole Xfce+ bring-up serialized every profile's start behind one desktop launch (and a hung launcher blocked them+ all for the full timeout): once /tmp/.X<n>-lock exists the number is Xvnc's and the lock must be free."""+ import fcntl++ scratch = in_process_runtime+ # X lock at once, env file only much later: the lock must be free in between.+ (scratch / "launcher.sh").write_text(+ '#!/usr/bin/env bash\necho $$ > "$HERMES_BD_XLOCK_DIR/.X${HERMES_BD_DISPLAY_NUM}-lock"\n'+ 'sleep 1.5\n: > "$HERMES_BD_SOCKET"\nprintf \'DISPLAY=:%s\\n\' "$HERMES_BD_DISPLAY_NUM" > "$HERMES_BD_ENV_FILE"\nsleep 30\n',+ encoding="utf-8")+ seen: dict = {}++ def probe():+ deadline = time.monotonic() + 3+ while time.monotonic() < deadline:+ if list((scratch / "xlocks").glob(".X*-lock")):+ time.sleep(0.2) # let start() notice the claim- with open(scratch / "alloc.lock", "a+") as fh:++ with open(scratch / "alloc.lock", "a+", encoding="utf-8") as fh:+ try:+ fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)+ seen["free"] = True+ fcntl.flock(fh.fileno(), fcntl.LOCK_UN)+ except OSError:+ seen["free"] = False+ return+ time.sleep(0.05)++ t = threading.Thread(target=probe)+ t.start()+ st = runtime.start(wait_seconds=10)+ t.join()+ assert st.running+ assert seen.get("free") is True, "allocation lock still held after Xvnc wrote its X lock"diff --cc tests/tools/test_browser_chromium_check.pyindex 0ac48bdb9a4,fd00581da72..00000000000deleted file mode 100644,100644--- a/tests/tools/test_browser_chromium_check.py+++ /dev/null@@@ -1,65 -1,77 +1,0 @@@--"""Tests for Chromium-presence detection in browser_tool.----Regression guard for the "browser tool advertised but Chromium missing"--class of bug — where ``agent-browser`` CLI is discoverable but no--Chromium build is on disk, causing every browser_* tool call to hang--for the full command timeout before surfacing a useless error.--"""----import os--import shutil----import pytest----from tools import browser_tool as bt--from tools import browser_tool_install as bt_install--from tools import browser_tool_cloud as bt_cloud---[email protected](autouse=True)--def _reset_chromium_cache():-- bt._cached_chromium_installed = None-- yield-- bt._cached_chromium_installed = None-----class TestChromiumSearchRoots:-- def test_respects_playwright_browsers_path_env(self, monkeypatch, tmp_path):-- monkeypatch.setenv("PLAYWRIGHT_BROWSERS_PATH", str(tmp_path))-- roots = bt_install._chromium_search_roots()-- assert str(tmp_path) == roots[0]----- def test_always_includes_default_ms_playwright_cache(self, monkeypatch):-- monkeypatch.delenv("PLAYWRIGHT_BROWSERS_PATH", raising=False)-- roots = bt_install._chromium_search_roots()-- home = os.path.expanduser("~")-- assert any(r == os.path.join(home, ".cache", "ms-playwright") for r in roots)-----class TestChromiumInstalled:-- def test_true_when_plain_chromium_on_path(self, monkeypatch):-- monkeypatch.delenv("AGENT_BROWSER_EXECUTABLE_PATH", raising=False)-- monkeypatch.setattr(-- shutil,-- "which",-- lambda name, path=None: "/usr/bin/chromium" if name == "chromium" else None,-- )---- assert bt_install._chromium_installed() is True-------class TestCheckBrowserRequirementsChromium:---- def test_local_mode_with_chromium_returns_true(self, monkeypatch, tmp_path):-- monkeypatch.setattr(bt, "_is_camofox_mode", lambda: False)-- monkeypatch.setattr(bt_install, "_find_agent_browser", lambda **_kw: "/usr/local/bin/agent-browser")-- monkeypatch.setattr("tools.browser_tool_install._requires_real_termux_browser_install", lambda _: False)-- monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: None)-- monkeypatch.setenv("PLAYWRIGHT_BROWSERS_PATH", str(tmp_path))-- (tmp_path / "chromium-1208").mkdir()---- assert bt_install.check_browser_requirements() is True----- def test_camofox_mode_does_not_require_chromium(self, monkeypatch, tmp_path):-- monkeypatch.setattr(bt, "_is_camofox_mode", lambda: True)-- # Even with no chromium on disk, camofox drives its own backend.-- monkeypatch.setenv("PLAYWRIGHT_BROWSERS_PATH", str(tmp_path))-- monkeypatch.setattr("os.path.expanduser", lambda p: str(tmp_path / "fakehome"))---- assert bt_install.check_browser_requirements() is True----diff --cc tests/tools/test_browser_homebrew_paths.pyindex a01beb018bb,a01beb018bb..00000000000deleted file mode 100644,100644--- a/tests/tools/test_browser_homebrew_paths.py+++ /dev/null@@@ -1,562 -1,562 +1,0 @@@--"""Tests for macOS Homebrew PATH discovery in browser_tool.py."""----import json--import os--import shutil--import sys--from pathlib import Path--from unittest.mock import patch, MagicMock, mock_open----import pytest----from tools.browser_tool_install import _find_agent_browser, check_browser_requirements--from tools.browser_tool_session import _run_browser_command--from tools.browser_tool import AGENT_BROWSER_NPX_SPEC--from tools.browser_tool_install import _agent_browser_candidate_present, _discover_homebrew_node_dirs--from tools.browser_tool_lightpanda_fallback import _run_chrome_fallback_command--import tools.browser_tool as _bt--from tools import browser_tool_install as bt_install----[email protected](autouse=True)--def _clear_browser_caches():-- """Clear lru_cache and manual caches between tests."""-- _discover_homebrew_node_dirs.cache_clear()-- _bt._cached_agent_browser = None-- _bt._agent_browser_resolved = False-- yield-- _discover_homebrew_node_dirs.cache_clear()-- _bt._cached_agent_browser = None-- _bt._agent_browser_resolved = False----------class TestDiscoverHomebrewNodeDirs:-- """Tests for _discover_homebrew_node_dirs()."""---- def test_returns_empty_when_no_homebrew(self):-- """Non-macOS systems without /opt/homebrew/opt should return empty."""-- with patch("os.path.isdir", return_value=False):-- assert _discover_homebrew_node_dirs() == ()------ def test_excludes_plain_node(self):-- """'node' (unversioned) should be excluded — covered by /opt/homebrew/bin."""-- with patch("os.path.isdir", return_value=True), \-- patch("os.listdir", return_value=["node"]):-- result = _discover_homebrew_node_dirs()-- assert result == ()---- def test_handles_oserror_gracefully(self):-- """Should return empty list if listdir raises OSError."""-- with patch("os.path.isdir", return_value=True), \-- patch("os.listdir", side_effect=OSError("Permission denied")):-- assert _discover_homebrew_node_dirs() == ()------class TestFindAgentBrowser:-- """Tests for _find_agent_browser() Homebrew path search."""---- def test_finds_in_current_path(self):-- """Should return result from shutil.which if available on current PATH."""-- with patch("shutil.which", return_value="/usr/local/bin/agent-browser"), \-- patch("tools.browser_tool_install.agent_browser_runnable", return_value=True):-- assert _find_agent_browser() == "/usr/local/bin/agent-browser"------ def test_raises_when_not_found(self):-- """Should raise FileNotFoundError when nothing works."""-- original_path_exists = Path.exists---- def mock_path_exists(self):-- if "node_modules" in str(self) and "agent-browser" in str(self):-- return False-- return original_path_exists(self)---- with patch("shutil.which", return_value=None), \-- patch("os.path.isdir", return_value=False), \-- patch.object(Path, "exists", mock_path_exists), \-- patch(-- "tools.browser_tool_install._discover_homebrew_node_dirs",-- return_value=[],-- ), \-- patch("tools.browser_tool_install._resolve_npx_bin", return_value=None), \-- patch("hermes_cli.dep_ensure.ensure_dependency", return_value=False):-- with pytest.raises(FileNotFoundError, match="agent-browser CLI not found"):-- _find_agent_browser()---- def test_finds_in_local_node_modules_bin(self):-- """Should fall through to the repo's node_modules/.bin when both the-- bare PATH and the extended (Homebrew/fallback) PATH miss."""-- repo_root = Path(_bt.__file__).parent.parent-- local_bin_dir = repo_root / "node_modules" / ".bin"-- local_bin_path = str(local_bin_dir / "agent-browser")---- def mock_which(cmd, path=None):-- if cmd == "agent-browser" and path and str(local_bin_dir) in path:-- return local_bin_path-- return None---- original_is_dir = Path.is_dir---- def mock_is_dir(self):-- if self == local_bin_dir:-- return True-- return original_is_dir(self)---- with patch("shutil.which", side_effect=mock_which), \-- patch("os.path.isdir", return_value=False), \-- patch.object(Path, "is_dir", mock_is_dir), \-- patch("tools.browser_tool_install.agent_browser_runnable", return_value=True), \-- patch(-- "tools.browser_tool_install._discover_homebrew_node_dirs",-- return_value=[],-- ):-- result = _find_agent_browser()---- assert result == local_bin_path---- def test_extended_path_hit_validate_false_skips_runnable_check(self, tmp_path):-- """Readiness probes (validate=False, used by _has_agent_browser) must-- resolve a candidate found via the extended PATH's path= kwarg lookup-- without calling agent_browser_runnable — that keeps the probe a cheap-- existence check with no subprocess spawn."""-- fake_binary = tmp_path / "agent-browser"-- fake_binary.write_text("#!/bin/sh\n")-- fake_binary.chmod(0o755)---- def mock_which(cmd, path=None):-- if cmd == "agent-browser" and path:-- return str(fake_binary)-- return None # bare (path=None) PATH lookup misses---- with patch("shutil.which", side_effect=mock_which), \-- patch("os.path.isdir", return_value=True), \-- patch(-- "tools.browser_tool_install.agent_browser_runnable",-- side_effect=AssertionError(-- "validate=False must not call agent_browser_runnable"-- ),-- ), \-- patch(-- "tools.browser_tool_install._discover_homebrew_node_dirs",-- return_value=["/opt/homebrew/bin"],-- ):-- result = _find_agent_browser(validate=False)---- assert result == str(fake_binary)---- def test_local_bin_hit_validate_false_skips_runnable_check(self, tmp_path):-- """Same no-subprocess-spawn contract for the node_modules/.bin-- candidate: validate=False relies on _agent_browser_candidate_present's-- existence+exec-bit check instead of shelling out to --version."""-- repo_root = Path(_bt.__file__).parent.parent-- local_bin_dir = repo_root / "node_modules" / ".bin"---- fake_binary = tmp_path / "agent-browser"-- fake_binary.write_text("#!/bin/sh\n")-- fake_binary.chmod(0o755)---- def mock_which(cmd, path=None):-- if cmd == "agent-browser" and path and str(local_bin_dir) in path:-- return str(fake_binary)-- return None---- original_is_dir = Path.is_dir---- def mock_is_dir(self):-- if self == local_bin_dir:-- return True-- return original_is_dir(self)---- with patch("shutil.which", side_effect=mock_which), \-- patch("os.path.isdir", return_value=False), \-- patch.object(Path, "is_dir", mock_is_dir), \-- patch(-- "tools.browser_tool_install.agent_browser_runnable",-- side_effect=AssertionError(-- "validate=False must not call agent_browser_runnable"-- ),-- ), \-- patch(-- "tools.browser_tool_install._discover_homebrew_node_dirs",-- return_value=[],-- ):-- result = _find_agent_browser(validate=False)---- assert result == str(fake_binary)---- def test_npx_fallback_validate_false(self):-- """The npx sentinel must resolve through the validate=False path too,-- independent of the fully-mocked coverage in test_nous_subscription.py."""-- def mock_which(cmd, path=None):-- if cmd == "agent-browser":-- return None-- if cmd == "npx":-- return "/usr/bin/npx"-- return None---- original_path_exists = Path.exists---- def mock_path_exists(self):-- if "node_modules" in str(self) and "agent-browser" in str(self):-- return False-- return original_path_exists(self)---- with patch("shutil.which", side_effect=mock_which), \-- patch("os.path.isdir", return_value=False), \-- patch.object(Path, "exists", mock_path_exists), \-- patch("tools.browser_tool_install.node_tool_runnable", return_value=True), \-- patch(-- "tools.browser_tool_install._discover_homebrew_node_dirs",-- return_value=[],-- ):-- result = _find_agent_browser(validate=False)---- assert result == "npx agent-browser"------class TestAgentBrowserCandidatePresent:-- """Direct unit tests for the validate=False candidate check used by every-- branch of _find_agent_browser's readiness-probe (no-subprocess) mode."""---- def test_none_is_false(self):-- assert _agent_browser_candidate_present(None) is False---- def test_empty_string_is_false(self):-- assert _agent_browser_candidate_present("") is False---- def test_npx_sentinel_is_true_without_touching_filesystem(self):-- assert _agent_browser_candidate_present("npx agent-browser") is True---- def test_executable_file_is_true(self, tmp_path):-- binary = tmp_path / "agent-browser"-- binary.write_text("#!/bin/sh\n")-- binary.chmod(0o755)-- assert _agent_browser_candidate_present(str(binary)) is True---- @pytest.mark.skipif(-- sys.platform == "win32",-- reason="exec-bit is not meaningful on Windows; os.name == 'nt' short-circuits",-- )-- def test_nonexecutable_file_is_false(self, tmp_path):-- binary = tmp_path / "agent-browser"-- binary.write_text("#!/bin/sh\n")-- binary.chmod(0o644)-- assert _agent_browser_candidate_present(str(binary)) is False---- def test_nonexistent_path_is_false(self, tmp_path):-- assert _agent_browser_candidate_present(str(tmp_path / "missing")) is False------class TestBrowserRequirements:-- def test_cdp_override_does_not_require_agent_browser_cli(self, monkeypatch):-- monkeypatch.setenv("BROWSER_CDP_URL", "ws://127.0.0.1:9222/devtools/browser/test")-- monkeypatch.setattr("tools.browser_tool._is_camofox_mode", lambda: False)-- monkeypatch.setattr("tools.browser_tool_install._find_agent_browser", lambda: (_ for _ in ()).throw(FileNotFoundError("not found")))---- assert check_browser_requirements() is True---- def test_termux_requires_real_agent_browser_install_not_npx_fallback(self, monkeypatch):-- monkeypatch.setenv("TERMUX_VERSION", "0.118.3")-- monkeypatch.setenv("PREFIX", "/data/data/com.termux/files/usr")-- monkeypatch.setattr("tools.browser_tool._is_camofox_mode", lambda: False)-- monkeypatch.setattr("tools.browser_tool_cloud._get_cloud_provider", lambda: None)-- monkeypatch.setattr("tools.browser_tool_install._find_agent_browser", lambda **_kw: "npx agent-browser")---- assert check_browser_requirements() is False------class TestRunBrowserCommandTermuxFallback:-- def test_termux_local_mode_rejects_bare_npx_fallback(self, monkeypatch):-- monkeypatch.setenv("TERMUX_VERSION", "0.118.3")-- monkeypatch.setenv("PREFIX", "/data/data/com.termux/files/usr")-- monkeypatch.setattr("tools.browser_tool_install._find_agent_browser", lambda **_kw: "npx agent-browser")-- monkeypatch.setattr("tools.browser_tool_cloud._get_cloud_provider", lambda: None)---- result = _run_browser_command("task-1", "navigate", ["https://example.com"])---- assert result["success"] is False-- assert "bare npx fallback" in result["error"]-- assert "agent-browser install" in result["error"]------class TestRunBrowserCommandPathConstruction:-- """Verify _run_browser_command() includes Homebrew node dirs in subprocess PATH."""---- def test_subprocess_preserves_executable_path_with_spaces(self, tmp_path):-- """A local agent-browser path containing spaces must stay one argv entry."""-- captured_cmd = None---- mock_proc = MagicMock()-- mock_proc.returncode = 0-- mock_proc.wait.return_value = 0---- def capture_popen(cmd, **kwargs):-- nonlocal captured_cmd-- captured_cmd = cmd-- return mock_proc---- fake_session = {-- "session_name": "test-session",-- "session_id": "test-id",-- "cdp_url": None,-- }-- fake_json = json.dumps({"success": True})-- browser_path = "/Users/test/Library/Application Support/hermes/node_modules/.bin/agent-browser"-- hermes_home = str(tmp_path / "hermes-home")---- with patch("tools.browser_tool_install._find_agent_browser", return_value=browser_path), \-- patch("tools.browser_tool_install._chromium_installed", return_value=True), \-- patch("tools.browser_tool_session._get_session_info", return_value=fake_session), \-- patch("tools.browser_tool._socket_safe_tmpdir", return_value=str(tmp_path)), \-- patch("tools.browser_tool_install._discover_homebrew_node_dirs", return_value=[]), \-- patch("hermes_constants.Path.home", return_value=tmp_path), \-- patch("subprocess.Popen", side_effect=capture_popen), \-- patch("os.open", return_value=99), \-- patch("os.close"), \-- patch("tools.interrupt.is_interrupted", return_value=False), \-- patch.dict(-- os.environ,-- {-- "PATH": "/usr/bin:/bin",-- "HOME": "/home/test",-- "HERMES_HOME": hermes_home,-- },-- clear=True,-- ):-- with patch("builtins.open", mock_open(read_data=fake_json)):-- _run_browser_command("test-task", "navigate", ["https://example.com"])---- assert captured_cmd is not None-- assert captured_cmd[0] == browser_path-- assert captured_cmd[1:5] == [-- "--session",-- "test-session",-- "--json",-- "navigate",-- ]------ def test_npx_sentinel_resolves_via_resolve_npx_bin_with_pinned_spec(self, tmp_path):-- """When _find_agent_browser resolves the npx sentinel, the cmd prefix-- must come from _resolve_npx_bin() (not a bare shutil.which("npx"), which-- could let a broken system npx shadow a healthy Hermes-managed one) and-- use the pinned agent-browser npx spec, not a bare "agent-browser"."""-- captured_cmd = None---- mock_proc = MagicMock()-- mock_proc.returncode = 0-- mock_proc.wait.return_value = 0---- def capture_popen(cmd, **kwargs):-- nonlocal captured_cmd-- captured_cmd = cmd-- return mock_proc---- fake_session = {-- "session_name": "test-session",-- "session_id": "test-id",-- "cdp_url": None,-- }-- fake_json = json.dumps({"success": True})-- hermes_home = str(tmp_path / "hermes-home")---- with patch("tools.browser_tool_install._find_agent_browser", return_value="npx agent-browser"), \-- patch("tools.browser_tool_install._resolve_npx_bin", return_value="/opt/hermes/node/bin/npx"), \-- patch("tools.browser_tool_install._chromium_installed", return_value=True), \-- patch("tools.browser_tool_session._get_session_info", return_value=fake_session), \-- patch("tools.browser_tool._socket_safe_tmpdir", return_value=str(tmp_path)), \-- patch("tools.browser_tool_install._discover_homebrew_node_dirs", return_value=[]), \-- patch("hermes_constants.Path.home", return_value=tmp_path), \-- patch("subprocess.Popen", side_effect=capture_popen), \-- patch("os.open", return_value=99), \-- patch("os.close"), \-- patch("tools.interrupt.is_interrupted", return_value=False), \-- patch.dict(-- os.environ,-- {-- "PATH": "/usr/bin:/bin",-- "HOME": "/home/test",-- "HERMES_HOME": hermes_home,-- },-- clear=True,-- ):-- with patch("builtins.open", mock_open(read_data=fake_json)):-- _run_browser_command("test-task", "navigate", ["https://example.com"])---- assert captured_cmd is not None-- assert captured_cmd[:5] == [-- "/opt/hermes/node/bin/npx", "--ignore-scripts", "--prefer-offline", "-y",-- AGENT_BROWSER_NPX_SPEC,-- ]-- assert captured_cmd[5:9] == ["--session", "test-session", "--json", "navigate"]---- def test_subprocess_path_includes_termux_fallback_dirs(self, tmp_path):-- """Termux fallback dirs should survive browser PATH rebuilding."""-- captured_env = {}---- mock_proc = MagicMock()-- mock_proc.returncode = 0-- mock_proc.wait.return_value = 0---- def capture_popen(cmd, **kwargs):-- captured_env.update(kwargs.get("env", {}))-- return mock_proc---- fake_session = {-- "session_name": "test-session",-- "session_id": "test-id",-- "cdp_url": None,-- }---- fake_json = json.dumps({"success": True})-- real_isdir = os.path.isdir---- def selective_isdir(path):-- if path in {-- "/data/data/com.termux/files/usr/bin",-- "/data/data/com.termux/files/usr/sbin",-- }:-- return True-- if path.startswith(str(tmp_path)):-- return True-- return real_isdir(path)---- with patch("tools.browser_tool_install._find_agent_browser", return_value="/usr/local/bin/agent-browser"), \-- patch("tools.browser_tool_install._chromium_installed", return_value=True), \-- patch("tools.browser_tool_session._get_session_info", return_value=fake_session), \-- patch("tools.browser_tool._socket_safe_tmpdir", return_value=str(tmp_path)), \-- patch("tools.browser_tool_install._discover_homebrew_node_dirs", return_value=[]), \-- patch("os.path.isdir", side_effect=selective_isdir), \-- patch("subprocess.Popen", side_effect=capture_popen), \-- patch("os.open", return_value=99), \-- patch("os.close"), \-- patch("tools.interrupt.is_interrupted", return_value=False), \-- patch.dict(os.environ, {"PATH": "/usr/bin:/bin", "HOME": "/home/test"}, clear=True):-- with patch("builtins.open", mock_open(read_data=fake_json)):-- _run_browser_command("test-task", "navigate", ["https://example.com"])---- result_path = captured_env.get("PATH", "")-- assert "/data/data/com.termux/files/usr/bin" in result_path-- assert "/data/data/com.termux/files/usr/sbin" in result_path------class TestRunChromeFallbackCommandNpxResolution:-- """_run_chrome_fallback_command builds its own npx cmd prefix independently-- of _run_browser_command's — it must resolve npx the same way (via-- _resolve_npx_bin(), not a bare shutil.which("npx")) and use the pinned-- agent-browser npx spec."""---- def test_npx_sentinel_resolves_via_resolve_npx_bin_with_pinned_spec(self, tmp_path):-- captured_cmds = []---- mock_proc = MagicMock()-- mock_proc.returncode = 0-- mock_proc.wait.return_value = 0---- def capture_popen(cmd, **kwargs):-- captured_cmds.append(cmd)-- return mock_proc---- url_result = {"success": True, "data": {"url": "https://example.com"}}---- with patch("tools.browser_tool_session._run_browser_command", return_value=url_result), \-- patch("tools.browser_tool_install._find_agent_browser", return_value="npx agent-browser"), \-- patch("tools.browser_tool_install._resolve_npx_bin", return_value="/opt/hermes/node/bin/npx"), \-- patch("tools.browser_tool_install._chromium_installed", return_value=True), \-- patch("tools.browser_tool_install._running_in_docker", return_value=False), \-- patch("tools.browser_tool._socket_safe_tmpdir", return_value=str(tmp_path)), \-- patch("subprocess.Popen", side_effect=capture_popen):-- _run_chrome_fallback_command("test-task", "navigate", ["https://example.com"], timeout=10)---- assert captured_cmds, "expected at least one Popen call for the chrome-fallback session"-- first_cmd = captured_cmds[0]-- assert first_cmd[:5] == [-- "/opt/hermes/node/bin/npx", "--ignore-scripts", "--prefer-offline", "-y",-- AGENT_BROWSER_NPX_SPEC,-- ]-- assert first_cmd[5] == "--engine" and first_cmd[6] == "chrome"-- assert first_cmd[7] == "--session" and first_cmd[8].startswith("h_cfb_")-- assert first_cmd[9] == "--json"------class TestResolveNpxBinPriority:-- """The extended/managed search must be checked before a bare ambient-- PATH lookup, so a broken/unexpected system npx can't shadow a healthy-- Hermes-managed one — and each candidate must be validated (actually-- runs) before being trusted, mirroring _find_agent_browser's own-- validation discipline for agent-browser itself."""---- def test_prefers_managed_extended_path_over_bare_path(self, monkeypatch):---- monkeypatch.setattr("tools.browser_tool_install._merge_browser_path", lambda _p: "/hermes/node/bin")-- monkeypatch.setattr(-- shutil, "which",-- lambda cmd, path=None: (-- "/hermes/node/bin/npx" if path == "/hermes/node/bin"-- else "/usr/local/bin/npx"-- ),-- )-- monkeypatch.setattr("tools.browser_tool_install.node_tool_runnable", lambda p: True)---- assert bt_install._resolve_npx_bin() == "/hermes/node/bin/npx"---- def test_falls_back_to_bare_path_when_managed_candidate_is_broken(self, monkeypatch):---- monkeypatch.setattr("tools.browser_tool_install._merge_browser_path", lambda _p: "/hermes/node/bin")-- monkeypatch.setattr(-- shutil, "which",-- lambda cmd, path=None: (-- "/hermes/node/bin/npx" if path == "/hermes/node/bin"-- else "/usr/local/bin/npx"-- ),-- )-- monkeypatch.setattr("tools.browser_tool_install.node_tool_runnable", lambda p: p == "/usr/local/bin/npx")---- assert bt_install._resolve_npx_bin() == "/usr/local/bin/npx"---- def test_returns_none_when_nothing_runnable(self, monkeypatch):---- monkeypatch.setattr("tools.browser_tool_install._merge_browser_path", lambda _p: "")-- monkeypatch.setattr(shutil, "which", lambda cmd, path=None: "/usr/local/bin/npx")-- monkeypatch.setattr("tools.browser_tool_install.node_tool_runnable", lambda p: False)---- assert bt_install._resolve_npx_bin() is None---- def test_skips_extended_lookup_when_merge_browser_path_returns_empty(self, monkeypatch):-- """_merge_browser_path("") returning a falsy string (no extended-- candidate dirs found on disk) must short-circuit straight to the-- bare-PATH rung — shutil.which must not be called with a path=""-- kwarg (which would silently mean "search cwd only" on some-- platforms rather than "no extended search"), and node_tool_runnable-- must only be asked about the one real candidate."""---- which_calls = []---- def fake_which(cmd, path=None):-- which_calls.append((cmd, path))-- return "/usr/bin/npx" if path is None else None---- monkeypatch.setattr("tools.browser_tool_install._merge_browser_path", lambda _p: "")-- monkeypatch.setattr(shutil, "which", fake_which)-- monkeypatch.setattr("tools.browser_tool_install.node_tool_runnable", lambda p: p == "/usr/bin/npx")---- assert bt_install._resolve_npx_bin() == "/usr/bin/npx"-- assert which_calls == [("npx", None)]---- def test_falls_back_to_bare_path_when_extended_dir_has_no_npx(self, monkeypatch):-- """A non-empty extended search PATH that simply doesn't contain an-- npx binary (shutil.which returns None there) must fall through to-- the bare-PATH rung rather than treating "no extended npx" the same-- as "extended npx found but broken"."""---- monkeypatch.setattr("tools.browser_tool_install._merge_browser_path", lambda _p: "/hermes/node/bin")-- monkeypatch.setattr(-- shutil, "which",-- lambda cmd, path=None: None if path == "/hermes/node/bin" else "/usr/bin/npx",-- )-- monkeypatch.setattr("tools.browser_tool_install.node_tool_runnable", lambda p: True)---- assert bt_install._resolve_npx_bin() == "/usr/bin/npx"diff --cc tests/tools/test_browser_npx_warmup.pyindex a556b336541,9412160020d..00000000000deleted file mode 100644,100644--- a/tests/tools/test_browser_npx_warmup.py+++ /dev/null@@@ -1,238 -1,258 +1,0 @@@--"""Tests for tools.browser_tool_install.warm_agent_browser_npx_cache (#43564, security--hardening follow-up on PR #44772 review).----warm_agent_browser_npx_cache() is the fire-and-forget helper `hermes update` /--`hermes doctor --fix` call to pre-fetch agent-browser via npx so the first real--browser-tool invocation in a session doesn't pay npx's registry-lookup cost.--It must never raise, must accurately report success/failure via its return--value, must use a credential-scrubbed and PATH-propagated environment (it--runs registry-fetched, potentially install-scripted npm code on every--`hermes update` — not only when a browser tool is actually used), must pass----ignore-scripts (AGENT_BROWSER_NPX_SPEC is a floating ^0.26.0 range, not an--exact pin), and must kill the whole process tree — not just the top-level--npx PID — on timeout.--"""----from __future__ import annotations----import subprocess--from unittest.mock import MagicMock, patch----from tools.browser_tool import AGENT_BROWSER_NPX_SPEC--from tools.browser_tool_install import warm_agent_browser_npx_cache--from tools.browser_tool_lifecycle import _legacy_kill_process_tree-----def _mock_proc(returncode=0, communicate_side_effect=None, pid=4242):-- proc = MagicMock()-- proc.pid = pid-- if communicate_side_effect is not None:-- proc.communicate.side_effect = communicate_side_effect-- else:-- proc.communicate.return_value = ("", "")-- proc.returncode = returncode-- return proc-----def test_returns_false_without_spawning_when_npx_unresolvable():-- with patch("tools.browser_tool_install._resolve_npx_bin", return_value=None), patch(-- "subprocess.Popen"-- ) as mock_popen:-- assert warm_agent_browser_npx_cache() is False-- mock_popen.assert_not_called()-----def test_invokes_npx_with_ignore_scripts_prefer_offline_and_pinned_spec():-- with patch("tools.browser_tool_install._resolve_npx_bin", return_value="/usr/bin/npx"), patch(-- "subprocess.Popen", return_value=_mock_proc()-- ) as mock_popen:-- assert warm_agent_browser_npx_cache() is True---- mock_popen.assert_called_once()-- args, _kwargs = mock_popen.call_args-- assert args[0] == [-- "/usr/bin/npx", "--ignore-scripts", "--prefer-offline", "-y",-- AGENT_BROWSER_NPX_SPEC, "--version",-- ]-----def test_stdin_is_explicitly_devnull_not_inherited():-- """Every subprocess call in tools/ must set stdin= explicitly-- (scripts/check_subprocess_stdin.py) — in the TUI gateway, an inherited-- stdin fd can be consumed by a child and cause the gateway's own-- JSON-RPC stdin read to see a premature EOF (issue #14036). This call-- has no reason to read from stdin at all, so it must be DEVNULL, not-- merely "present in kwargs somewhere" (the checker is a literal-argument-- textual scan, so stdin= folded into a shared kwargs dict wouldn't-- satisfy it either — it must appear as a literal keyword on the call)."""-- with patch("tools.browser_tool_install._resolve_npx_bin", return_value="/usr/bin/npx"), \-- patch("subprocess.Popen", return_value=_mock_proc()) as mock_popen:-- warm_agent_browser_npx_cache()---- _args, kwargs = mock_popen.call_args-- assert kwargs.get("stdin") == subprocess.DEVNULL-----def test_captures_stdout_and_stderr_instead_of_inheriting_parent_fds():-- """The npx registry fetch runs on every `hermes update` — its stdout/-- stderr must not bleed into the caller's own output (and, on POSIX, an-- inherited fd is one more handle a runaway grandchild could hold open)."""-- with patch("tools.browser_tool_install._resolve_npx_bin", return_value="/usr/bin/npx"), \-- patch("subprocess.Popen", return_value=_mock_proc()) as mock_popen:-- warm_agent_browser_npx_cache()---- _args, kwargs = mock_popen.call_args-- assert kwargs.get("stdout") == subprocess.PIPE-- assert kwargs.get("stderr") == subprocess.PIPE-----def test_uses_credential_scrubbed_environment():-- """Must not inherit the full parent environment — matching every other-- agent-browser subprocess spawn (_build_browser_env), not the ambient-- os.environ with every provider/gateway credential Hermes holds."""-- scrubbed_env = {"PATH": "/scrubbed/bin", "SCRUBBED": "1"}-- with patch("tools.browser_tool_install._resolve_npx_bin", return_value="/usr/bin/npx"), \-- patch("tools.browser_tool._build_browser_env", return_value=dict(scrubbed_env)), \-- patch("tools.browser_tool_install._merge_browser_path", side_effect=lambda p: p), \-- patch("subprocess.Popen", return_value=_mock_proc()) as mock_popen:-- warm_agent_browser_npx_cache()---- _args, kwargs = mock_popen.call_args-- assert kwargs["env"]["SCRUBBED"] == "1"-- assert "OPENAI_API_KEY" not in kwargs["env"]-----def test_merges_extended_path_so_managed_only_npx_can_find_sibling_node():-- """If npx was resolved via the Hermes-managed/extended search (not the-- ambient PATH), the child's own PATH must include that same directory —-- npx's #!/usr/bin/env node shebang resolves `node` via the child's PATH-- at exec time, not the resolving process's PATH."""-- with patch("tools.browser_tool_install._resolve_npx_bin", return_value="/opt/hermes/node/bin/npx"), \-- patch("tools.browser_tool._build_browser_env", return_value={"PATH": "/usr/bin"}), \-- patch(-- "tools.browser_tool_install._merge_browser_path",-- return_value="/opt/hermes/node/bin:/usr/bin",-- ), \-- patch("subprocess.Popen", return_value=_mock_proc()) as mock_popen:-- warm_agent_browser_npx_cache()---- _args, kwargs = mock_popen.call_args-- assert kwargs["env"]["PATH"] == "/opt/hermes/node/bin:/usr/bin"-----def test_runs_in_its_own_process_group_on_posix(monkeypatch):-- monkeypatch.setattr("os.name", "posix")-- with patch("tools.browser_tool_install._resolve_npx_bin", return_value="/usr/bin/npx"), \-- patch("subprocess.Popen", return_value=_mock_proc()) as mock_popen:-- warm_agent_browser_npx_cache()---- _args, kwargs = mock_popen.call_args-- assert kwargs.get("start_new_session") is True-------def test_timeout_kills_the_whole_process_tree_not_just_the_pid():-- """subprocess.Popen.kill() only signals the direct child; npm/npx can-- fork descendants that survive it and hold a capture pipe open past the-- nominal timeout. On timeout, the whole process group/tree must be-- killed, not just the top-level PID."""-- proc = _mock_proc(-- communicate_side_effect=[-- subprocess.TimeoutExpired(cmd=["npx"], timeout=60.0), ("", ""),-- ]-- )-- with patch("tools.browser_tool_install._resolve_npx_bin", return_value="/usr/bin/npx"), \-- patch("subprocess.Popen", return_value=proc), \-- patch("tools.browser_tool_lifecycle._kill_process_tree") as mock_kill:-- assert warm_agent_browser_npx_cache(timeout=60.0) is False---- mock_kill.assert_called_once_with(proc)-- assert proc.communicate.call_count == 2, (-- "must attempt a second, bounded communicate() after the kill to reap "-- "the now-dead process and drain its pipes, not just abandon it"-- )-----def test_timeout_cleanup_communicate_itself_raising_does_not_propagate():-- """The post-kill drain call is itself best-effort — if the process is-- stuck badly enough that even the 5s cleanup communicate() times out (or-- raises for any other reason), that must not escape and crash the-- fire-and-forget caller (hermes_cli/doctor.py calls this bare)."""-- proc = _mock_proc(-- communicate_side_effect=[-- subprocess.TimeoutExpired(cmd=["npx"], timeout=60.0),-- subprocess.TimeoutExpired(cmd=["npx"], timeout=5),-- ]-- )-- with patch("tools.browser_tool_install._resolve_npx_bin", return_value="/usr/bin/npx"), \-- patch("subprocess.Popen", return_value=proc), \-- patch("tools.browser_tool_lifecycle._kill_process_tree") as mock_kill:-- assert warm_agent_browser_npx_cache(timeout=60.0) is False---- mock_kill.assert_called_once_with(proc)-----def test_returns_false_on_nonzero_exit():-- with patch("tools.browser_tool_install._resolve_npx_bin", return_value="/usr/bin/npx"), patch(-- "subprocess.Popen", return_value=_mock_proc(returncode=1)-- ):-- assert warm_agent_browser_npx_cache() is False-----def test_returns_false_instead_of_raising_on_popen_failure():-- with patch("tools.browser_tool_install._resolve_npx_bin", return_value="/usr/bin/npx"), patch(-- "subprocess.Popen", side_effect=OSError("fork failed")-- ):-- assert warm_agent_browser_npx_cache() is False-----def test_returns_false_instead_of_raising_on_unexpected_communicate_exception():-- """Fire-and-forget contract: hermes_cli/doctor.py calls this bare (no-- try/except of its own), so any exception must be swallowed here."""-- proc = _mock_proc(communicate_side_effect=OSError("broken pipe"))-- with patch("tools.browser_tool_install._resolve_npx_bin", return_value="/usr/bin/npx"), \-- patch("subprocess.Popen", return_value=proc), \-- patch("tools.browser_tool_lifecycle._kill_process_tree") as mock_kill:-- assert warm_agent_browser_npx_cache() is False-- mock_kill.assert_called_once_with(proc)-----class TestLegacyKillProcessTree:-- """Contract of the pre-#85125 local fallback (used when agent.deadline-- delegation fails); the delegating wrapper is covered in-- tests/agent/test_treekill_consolidation.py."""---- def test_posix_kills_process_group_term_then_kill(self, monkeypatch):-- import signal---- proc = MagicMock()-- proc.pid = 999-- monkeypatch.setattr("os.name", "posix")-- monkeypatch.setattr("os.getpgid", lambda pid: 999)-- killpg_calls = []-- monkeypatch.setattr(-- "os.killpg", lambda pgid, sig: killpg_calls.append((pgid, sig))-- )---- _legacy_kill_process_tree(proc)---- assert killpg_calls == [(999, signal.SIGTERM), (999, signal.SIGKILL)]---- def test_posix_missing_process_returns_silently(self, monkeypatch):-- proc = MagicMock()-- proc.pid = 999-- monkeypatch.setattr("os.name", "posix")---- def _raise(pid):-- raise ProcessLookupError()---- monkeypatch.setattr("os.getpgid", _raise)---- _legacy_kill_process_tree(proc) # must not raise------ def test_posix_sigterm_permission_denied_does_not_attempt_sigkill(self, monkeypatch):-- """If SIGTERM itself is rejected (e.g. a stale pgid reused by an-- unrelated, unkillable process), the loop must bail out rather than-- plow ahead into a second signal against the wrong target."""-- import signal---- proc = MagicMock()-- proc.pid = 999-- monkeypatch.setattr("os.name", "posix")-- monkeypatch.setattr("os.getpgid", lambda pid: 999)-- killpg_calls = []---- def fake_killpg(pgid, sig):-- killpg_calls.append((pgid, sig))-- raise PermissionError()---- monkeypatch.setattr("os.killpg", fake_killpg)---- _legacy_kill_process_tree(proc) # must not raise---- assert killpg_calls == [(999, signal.SIGTERM)]--diff --cc tests/tools/test_browser_use_cli.pyindex 19857c31ca5,19857c31ca5..64f1dfafd4c--- a/tests/tools/test_browser_use_cli.py+++ b/tests/tools/test_browser_use_cli.py@@@ -19,6 -19,6 +19,7 @@@ import syimport timeimport pytest++import psutilimport tools.browser_use_cli as bu_clifrom tools import browser_tool_install as bt_install@@@ -270,28 -270,28 +271,6 @@@ class TestVaultEgressRedactionassert serialized.count("«redacted-vault-secret»") == 2--class TestFindCli:-- """The tests/tools conftest pins _find_cli to None (host isolation);-- exercise the real function via the preserved _find_cli_unpatched."""---- def test_prefers_installed_binary(self, monkeypatch):-- monkeypatch.setattr(-- bu_cli.shutil, "which",-- lambda name, path=None: "/usr/local/bin/browser-use" if name == "browser-use" and path is None else ("/usr/local/bin/uvx" if path is None else None),-- )-- assert bu_cli._find_cli_unpatched() == ["/usr/local/bin/browser-use"]---- def test_falls_back_to_uvx(self, monkeypatch):-- monkeypatch.setattr(-- bu_cli.shutil, "which",-- lambda name, path=None: "/usr/local/bin/uvx" if name == "uvx" and path is None else None,-- )-- assert bu_cli._find_cli_unpatched() == ["/usr/local/bin/uvx", "browser-use"]---- def test_none_when_neither_available(self, monkeypatch):-- monkeypatch.setattr(bu_cli.shutil, "which", lambda name, path=None: None)-- assert bu_cli._find_cli_unpatched() is None--class TestLegacyCloudMigration:"""Pre-CLI direct-API Browser Use cloud configs (cloud_provider:@@@ -969,174 -969,174 +948,6 @@@ class TestBrowserExec--class TestFindCliManagedBin:-- """MANAGED-FIRST: _find_cli probes $HERMES_HOME/bin before PATH and-- ~/.local/bin, so the Hermes-installed copy always wins."""---- @pytest.fixture(autouse=True)-- def _hermetic_home(self, tmp_path, monkeypatch):-- """Pin HOME so the ~/.local/bin probe can't leak the host's real-- user-level installs into these real-PATH-probing tests."""-- monkeypatch.setenv("HOME", str(tmp_path / "userhome"))-- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))-- monkeypatch.setenv("PATH", str(tmp_path / "empty"))---- def test_managed_bin_browser_use_found(self, tmp_path, monkeypatch):-- bin_dir = tmp_path / "home" / "bin"-- bin_dir.mkdir(parents=True)-- bu = bin_dir / "browser-use"-- bu.write_text("#!/bin/sh\n", encoding="utf-8")-- bu.chmod(bu.stat().st_mode | stat.S_IXUSR)-- assert bu_cli._find_cli_unpatched() == [str(bu)]---- def test_managed_bin_uvx_fallback(self, tmp_path, monkeypatch):-- bin_dir = tmp_path / "home" / "bin"-- bin_dir.mkdir(parents=True)-- uvx = bin_dir / "uvx"-- uvx.write_text("#!/bin/sh\n", encoding="utf-8")-- uvx.chmod(uvx.stat().st_mode | stat.S_IXUSR)-- assert bu_cli._find_cli_unpatched() == [str(uvx), "browser-use"]------ def test_user_local_bin_browser_use_found(self, tmp_path, monkeypatch):-- """#83788: Desktop/TUI workers spawn with a minimal PATH that omits-- ~/.local/bin, where `uv tool install browser-use` links the binary-- by default — _find_cli must probe it explicitly."""-- cli_dir = tmp_path / "userhome" / ".local" / "bin"-- cli_dir.mkdir(parents=True)-- cli = cli_dir / "browser-use"-- cli.write_text("#!/bin/sh\n", encoding="utf-8")-- cli.chmod(cli.stat().st_mode | stat.S_IXUSR)-- assert bu_cli._find_cli_unpatched() == [str(cli)]---- def test_managed_bin_precedes_user_local_bin(self, tmp_path, monkeypatch):-- """MANAGED-FIRST: Hermes' managed copy wins over a user-level side-- install — every backend selection provisions/updates the managed-- copy, so resolution must land on the binary we control (no version-- drift from stray `uv tool install` runs)."""-- user_dir = tmp_path / "userhome" / ".local" / "bin"-- user_dir.mkdir(parents=True)-- user_cli = user_dir / "browser-use"-- user_cli.write_text("#!/bin/sh\n", encoding="utf-8")-- user_cli.chmod(user_cli.stat().st_mode | stat.S_IXUSR)-- managed_dir = tmp_path / "home" / "bin"-- managed_dir.mkdir(parents=True)-- managed_cli = managed_dir / "browser-use"-- managed_cli.write_text("#!/bin/sh\n", encoding="utf-8")-- managed_cli.chmod(managed_cli.stat().st_mode | stat.S_IXUSR)-- assert bu_cli._find_cli_unpatched() == [str(managed_cli)]---- def test_managed_bin_precedes_path(self, tmp_path, monkeypatch):-- """MANAGED-FIRST: the managed copy also wins over one on PATH."""-- path_dir = tmp_path / "onpath"-- path_dir.mkdir()-- path_cli = path_dir / "browser-use"-- path_cli.write_text("#!/bin/sh\n", encoding="utf-8")-- path_cli.chmod(path_cli.stat().st_mode | stat.S_IXUSR)-- monkeypatch.setenv("PATH", str(path_dir))-- managed_dir = tmp_path / "home" / "bin"-- managed_dir.mkdir(parents=True)-- managed_cli = managed_dir / "browser-use"-- managed_cli.write_text("#!/bin/sh\n", encoding="utf-8")-- managed_cli.chmod(managed_cli.stat().st_mode | stat.S_IXUSR)-- assert bu_cli._find_cli_unpatched() == [str(managed_cli)]---- def test_user_local_bin_uvx_fallback(self, tmp_path, monkeypatch):-- cli_dir = tmp_path / "userhome" / ".local" / "bin"-- cli_dir.mkdir(parents=True)-- uvx = cli_dir / "uvx"-- uvx.write_text("#!/bin/sh\n", encoding="utf-8")-- uvx.chmod(uvx.stat().st_mode | stat.S_IXUSR)-- assert bu_cli._find_cli_unpatched() == [str(uvx), "browser-use"]------class TestInstallCli:-- def test_path_install_does_not_short_circuit(self, tmp_path, monkeypatch):-- """MANAGED-FIRST: a browser-use on PATH is a user-level side install-- and must NOT satisfy install_cli() — only the managed copy does,-- otherwise resolution stays pinned to a binary Hermes can't update."""-- cli = _fake_cli(tmp_path, "")-- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))-- monkeypatch.setattr(bu_cli.shutil, "which", lambda name, path=None: cli if name == "browser-use" and path is None else None)-- import sys as _sys-- import types as _types-- fake = _types.ModuleType("hermes_cli.managed_uv")-- fake.ensure_uv = lambda **kw: None-- monkeypatch.setitem(_sys.modules, "hermes_cli.managed_uv", fake)-- ok, msg = bu_cli.install_cli()-- # No uv available in this fixture, so the attempted managed install-- # fails — the point is that the PATH copy did not short-circuit.-- assert ok is False-- assert "already installed" not in msg---- def test_already_installed_in_managed_bin(self, tmp_path, monkeypatch):-- bin_dir = tmp_path / "home" / "bin"-- bin_dir.mkdir(parents=True)-- cli = bin_dir / "browser-use"-- cli.write_text("#!/bin/sh\n", encoding="utf-8")-- cli.chmod(cli.stat().st_mode | stat.S_IXUSR)-- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))-- monkeypatch.setenv("PATH", str(tmp_path / "empty"))-- ok, msg = bu_cli.install_cli()-- assert ok is True-- assert "already installed" in msg---- def test_no_uv_anywhere_fails_with_guidance(self, tmp_path, monkeypatch):-- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))-- monkeypatch.setenv("PATH", str(tmp_path / "empty"))-- import sys as _sys-- import types as _types-- fake = _types.ModuleType("hermes_cli.managed_uv")-- fake.ensure_uv = lambda **kw: None-- monkeypatch.setitem(_sys.modules, "hermes_cli.managed_uv", fake)-- ok, msg = bu_cli.install_cli()-- assert ok is False-- assert "uv" in msg---- def test_successful_install_via_fake_uv(self, tmp_path, monkeypatch):-- home = tmp_path / "home"-- bin_dir = home / "bin"-- bin_dir.mkdir(parents=True)-- monkeypatch.setenv("HERMES_HOME", str(home))-- monkeypatch.setenv("PATH", str(tmp_path / "empty"))-- # install_cli verifies via _find_cli(), which the tests/tools conftest-- # pins to None — restore the real resolver for this test.-- monkeypatch.setattr(bu_cli, "_find_cli", bu_cli._find_cli_unpatched)-- # fake uv: `uv tool install browser-use` drops a binary into UV_TOOL_BIN_DIR.-- # Absolute /bin/chmod: PATH is emptied above, so bare chmod won't resolve.-- uv = tmp_path / "uv"-- uv.write_text(-- "#!/bin/sh\n"-- 'target="$UV_TOOL_BIN_DIR/browser-use"\n'-- 'echo "#!/bin/sh" > "$target"\n'-- '/bin/chmod +x "$target"\n'-- , encoding="utf-8")-- uv.chmod(uv.stat().st_mode | stat.S_IXUSR)-- import sys as _sys-- import types as _types-- fake = _types.ModuleType("hermes_cli.managed_uv")-- fake.ensure_uv = lambda **kw: str(uv)-- monkeypatch.setitem(_sys.modules, "hermes_cli.managed_uv", fake)-- ok, msg = bu_cli.install_cli()-- assert ok is True, msg-- assert (bin_dir / "browser-use").exists()---- def test_failed_install_surfaces_stderr_tail(self, tmp_path, monkeypatch):-- home = tmp_path / "home"-- monkeypatch.setenv("HERMES_HOME", str(home))-- monkeypatch.setenv("PATH", str(tmp_path / "empty"))-- uv = tmp_path / "uv"-- uv.write_text('#!/bin/sh\necho "no network" >&2\nexit 1\n', encoding="utf-8")-- uv.chmod(uv.stat().st_mode | stat.S_IXUSR)-- import sys as _sys-- import types as _types-- fake = _types.ModuleType("hermes_cli.managed_uv")-- fake.ensure_uv = lambda **kw: str(uv)-- monkeypatch.setitem(_sys.modules, "hermes_cli.managed_uv", fake)-- ok, msg = bu_cli.install_cli()-- assert ok is False-- assert "no network" in msg--class TestDefaultDowngradeNotice:def _isolate(self, tmp_path, monkeypatch):@@@ -1370,16 -1370,16 +1181,11 @@@ class TestTimeoutProcessGroupKill# Pre-fix, this hangs until the 60s sleeps expire — and forever with a daemon child.assert elapsed < 30# The pipe-holding grandchild died with the group instead of leaking.-- pid = int(pid_file.read_text().strip())++ pid = int(pid_file.read_text(encoding="utf-8-sig").strip())deadline = time.time() + 5-- while time.time() < deadline:-- try:-- os.kill(pid, 0)-- except OSError:-- break++ while time.time() < deadline and psutil.pid_exists(pid):time.sleep(0.05)-- with pytest.raises(OSError):-- os.kill(pid, 0)++ assert not psutil.pid_exists(pid)def test_post_kill_drain_is_bounded(self, monkeypatch):"""If even the post-kill drain misses its deadline, give up instead of wedging."""diff --cc tests/tools/test_computer_use.pyindex c40d8b012a6,c4f822b5a2c..e0899136002--- a/tests/tools/test_computer_use.py+++ b/tests/tools/test_computer_use.py@@@ -763,48 -783,48 +783,7 @@@ class TestElementLabelParsingassert labels[201] == "" # pure order number, no label--class TestUpdateCheck:-- """cua_driver_update_check() / _nudge(): native `check-update --json`.-- Prefers cua-driver's source-of-truth update check over a hardcoded- version floor. Stays quiet (None) when indeterminate: an old driver with- no `check-update` verb, offline, an `error` payload, or unparseable output.- """-- @pytest.fixture(autouse=True)- def _driver_resolves(self):- # The update check now short-circuits to None when no driver- # resolves; CI has none installed, so pin a resolved path.- with patch(- "tools.computer_use.cua_backend_driver.resolve_cua_driver_cmd",- return_value="/usr/local/bin/cua-driver",- ):- yield-- @staticmethod- def _run_returning(stdout: str):- fake = MagicMock()- fake.stdout = stdout- return patch("tools.computer_use.cua_backend.subprocess.run", return_value=fake)- Prefers cua-driver's source-of-truth update check over a hardcoded- version floor. Stays quiet (None) when indeterminate: an old driver with- no `check-update` verb, offline, an `error` payload, or unparseable output.- """-- @pytest.fixture(autouse=True)- def _driver_resolves(self):- # The update check now short-circuits to None when no driver- # resolves; CI has none installed, so pin a resolved path.- with patch(- "tools.computer_use.cua_backend_driver.resolve_cua_driver_cmd",- return_value="/usr/local/bin/cua-driver",- ):- yield-- @staticmethod- def _run_returning(stdout: str):- fake = MagicMock()- fake.stdout = stdout- return patch("tools.computer_use.cua_backend.subprocess.run", return_value=fake)--- def test_update_available(self):-- from tools.computer_use import cua_backend-- from tools.computer_use import cua_backend_driver-- payload = '{"current_version":"0.3.1","latest_version":"0.3.2","update_available":true}'-- with self._run_returning(payload):-- st = cua_backend_driver.cua_driver_update_check()-- assert st is not None and st["update_available"] is True-- msg = cua_backend.cua_driver_update_nudge()-- assert msg is not None-- assert "0.3.2" in msg and "0.3.1" in msg---- def test_error_payload_is_indeterminate(self):-- from tools.computer_use import cua_backend-- from tools.computer_use import cua_backend_driver-- payload = '{"current_version":"0.3.2","update_available":false,"error":"github 503"}'-- with self._run_returning(payload):-- assert cua_backend_driver.cua_driver_update_check() is None-- assert cua_backend.cua_driver_update_nudge() is Noneclass TestLazyMcpInstall:"""`mcp` is an optional extra; the backend lazy-installs it on start().@@@ -813,160 -833,160 +792,45 @@@partial installs, matching how every other optional backend behaves."""---- def test_start_reports_incompatible_existing_driver_before_mcp_setup(self):++ def test_start_lazy_installs_mcp(self):from tools.computer_use import cua_backend---- state = {-- "ready": False,-- "reason": "Hermes computer use requires cua-driver 0.20.0 or newer",-- }with patch.object(cua_backend,"cua_driver_runtime_contract_status",-- return_value=state,-- ), patch("tools.lazy_deps.ensure") as mock_ensure:-- with pytest.raises(RuntimeError, match="hermes computer-use install"):-- cua_backend.CuaDriverBackend().start()++ return_value={"ready": True},++ ), \++ patch("pm.ensure") as driver_ensure, \++ patch("pm.ensure_import") as mock_ensure, \++ patch.object(cua_backend._CuaDriverSession, "start") as mock_sess_start:++ cua_backend.CuaDriverBackend().start()++ mock_ensure.assert_called_once_with("computer-use")++ driver_ensure.assert_called_once_with("cua-driver")++ mock_sess_start.assert_called_once()-- mock_ensure.assert_not_called()def test_start_propagates_feature_unavailable(self):"""When mcp can't be installed (lazy installs off / network), start()surfaces the actionable FeatureUnavailable rather than a session thatcrashes later on a bare import."""from tools.computer_use import cua_backend-- from tools.lazy_deps import FeatureUnavailable++ from pm import InstallError as FeatureUnavailableunavailable = FeatureUnavailable(-- "tool.computer_use", ("mcp==1.28.1",), "lazy installs disabled"++ "computer-use", "lazy installs disabled")with patch.object(cua_backend,"cua_driver_runtime_contract_status",return_value={"ready": True},), \-- patch.object(cua_backend, "_maybe_nudge_update"), \-- patch("tools.lazy_deps.ensure", side_effect=unavailable), \++ patch("pm.ensure"), \++ patch("pm.ensure_import", side_effect=unavailable), \patch.object(cua_backend._CuaDriverSession, "start") as mock_sess_start:with pytest.raises(FeatureUnavailable):cua_backend.CuaDriverBackend().start()mock_sess_start.assert_not_called() # never reaches the MCP session--class TestContractAutoRepair:-- """An installed-but-incompatible driver is repaired automatically, once.---- The 0.20 runtime-contract gate fails closed; when the failure is an old-- installed driver (a state Hermes' own version-floor bump created),-- start() runs the standard install/repair path once instead of failing-- every computer_use call until the user runs the CLI by hand.-- """---- def _incompatible(self):-- return {-- "ready": False,-- "binary": "/usr/local/bin/cua-driver",-- "version": "0.19.3",-- "reason": "Hermes computer use requires cua-driver 0.20.0 or newer",-- }---- def test_start_auto_repairs_incompatible_driver(self, monkeypatch):-- from unittest.mock import MagicMock, patch-- from tools.computer_use import cua_backend---- monkeypatch.setattr(cua_backend, "_contract_repair_attempted", False)-- backend = cua_backend.CuaDriverBackend()-- backend._session = MagicMock()-- with patch.object(- cua_backend,- "cua_driver_runtime_contract_status",- side_effect=[self._incompatible(), {"ready": True}],- ), \- patch("hermes_cli.tools_config.install_cua_driver",- return_value=True) as installer, \- patch.object(cua_backend, "_maybe_nudge_update"), \- patch("tools.lazy_deps.ensure"):- backend.start()-- installer.assert_called_once_with(- upgrade=False, show_installer_progress=False- )- backend._session.start.assert_called_once()-- def test_failed_repair_surfaces_original_error(self, monkeypatch):- from unittest.mock import patch- from tools.computer_use import cua_backend-- monkeypatch.setattr(cua_backend, "_contract_repair_attempted", False)- with patch.object(- cua_backend,- "cua_driver_runtime_contract_status",- return_value=self._incompatible(),- ), \- patch("hermes_cli.tools_config.install_cua_driver",- return_value=False), \- patch("tools.lazy_deps.ensure") as mock_ensure:- with pytest.raises(RuntimeError, match="0.20.0 or newer"):- cua_backend.CuaDriverBackend().start()- mock_ensure.assert_not_called()-- def test_repair_is_attempted_once_per_process(self, monkeypatch):- from unittest.mock import patch- from tools.computer_use import cua_backend-- monkeypatch.setattr(cua_backend, "_contract_repair_attempted", False)- with patch.object(- cua_backend,- "cua_driver_runtime_contract_status",- return_value=self._incompatible(),- ), \- patch("hermes_cli.tools_config.install_cua_driver",- return_value=False) as installer, \- patch("tools.lazy_deps.ensure"):- for _ in range(2):- with pytest.raises(RuntimeError):- cua_backend.CuaDriverBackend().start()- installer.assert_called_once()-- def test_explicit_override_is_never_repaired(self, monkeypatch):- from unittest.mock import patch- from tools.computer_use import cua_backend-- monkeypatch.setattr(cua_backend, "_contract_repair_attempted", False)- monkeypatch.setenv("HERMES_CUA_DRIVER_CMD", "/opt/custom/cua-driver")- with patch.object(- cua_backend,- "cua_driver_runtime_contract_status",- return_value=self._incompatible(),- ), \- patch("hermes_cli.tools_config.install_cua_driver") as installer, \- patch("tools.lazy_deps.ensure"):- with pytest.raises(RuntimeError, match="HERMES_CUA_DRIVER_CMD"):- cua_backend.CuaDriverBackend().start()- installer.assert_not_called()-- def test_missing_binary_is_not_repaired(self, monkeypatch):- from unittest.mock import patch- from tools.computer_use import cua_backend- with patch.object(- cua_backend,- "cua_driver_runtime_contract_status",- side_effect=[self._incompatible(), {"ready": True}],- ), \- patch("hermes_cli.tools_config.install_cua_driver",- return_value=True) as installer, \- patch.object(cua_backend, "_maybe_nudge_update"), \- patch("tools.lazy_deps.ensure"):- backend.start()-- installer.assert_called_once_with(- upgrade=False, show_installer_progress=False- )- backend._session.start.assert_called_once()-- def test_failed_repair_surfaces_original_error(self, monkeypatch):- from unittest.mock import patch- from tools.computer_use import cua_backend-- monkeypatch.setattr(cua_backend, "_contract_repair_attempted", False)- with patch.object(- cua_backend,- "cua_driver_runtime_contract_status",- return_value=self._incompatible(),- ), \- patch("hermes_cli.tools_config.install_cua_driver",- return_value=False), \- patch("tools.lazy_deps.ensure") as mock_ensure:- with pytest.raises(RuntimeError, match="0.20.0 or newer"):- cua_backend.CuaDriverBackend().start()- mock_ensure.assert_not_called()-- def test_repair_is_attempted_once_per_process(self, monkeypatch):- from unittest.mock import patch- from tools.computer_use import cua_backend-- monkeypatch.setattr(cua_backend, "_contract_repair_attempted", False)- with patch.object(- cua_backend,- "cua_driver_runtime_contract_status",- return_value=self._incompatible(),- ), \- patch("hermes_cli.tools_config.install_cua_driver",- return_value=False) as installer, \- patch("tools.lazy_deps.ensure"):- for _ in range(2):- with pytest.raises(RuntimeError):- cua_backend.CuaDriverBackend().start()- installer.assert_called_once()-- def test_explicit_override_is_never_repaired(self, monkeypatch):- from unittest.mock import patch- from tools.computer_use import cua_backend-- monkeypatch.setattr(cua_backend, "_contract_repair_attempted", False)- monkeypatch.setenv("HERMES_CUA_DRIVER_CMD", "/opt/custom/cua-driver")- with patch.object(- cua_backend,- "cua_driver_runtime_contract_status",- return_value=self._incompatible(),- ), \- patch("hermes_cli.tools_config.install_cua_driver") as installer, \- patch("tools.lazy_deps.ensure"):- with pytest.raises(RuntimeError, match="HERMES_CUA_DRIVER_CMD"):- cua_backend.CuaDriverBackend().start()- installer.assert_not_called()-- def test_missing_binary_is_not_repaired(self, monkeypatch):- from unittest.mock import patch- from tools.computer_use import cua_backend--- monkeypatch.setattr(cua_backend, "_contract_repair_attempted", False)-- state = {-- "ready": False,-- "binary": None,-- "version": None,-- "reason": "cua-driver is not installed",-- }-- with patch.object(-- cua_backend,-- "cua_driver_runtime_contract_status",-- return_value=state,-- ), \-- patch("hermes_cli.tools_config.install_cua_driver") as installer, \-- patch("tools.lazy_deps.ensure"):-- with pytest.raises(RuntimeError, match="not installed"):-- cua_backend.CuaDriverBackend().start()-- installer.assert_not_called()class TestCaptureAfterAppContext:@@@ -1461,7 -1481,7 +1325,7 @@@ class TestCaptureAppFilterNoMatchassert backend._active_pid is Noneassert backend._active_window_id is None-- @pytest.mark.linux_only++ @pytest.mark.platforms("linux")def test_linux_default_capture_skips_gnome_shell_helper(self):windows = [{"app_name": "", "pid": 100, "window_id": 1,@@@ -2240,12 -2260,12 +2104,11 @@@ class TestSessionLifecycle"structuredContent": None, "isError": False,})-- # Stub the optional-dep lazy-install so start() runs end-to-end-- # without trying to pip-install anything.++ # Session lifecycle is independent of PM acquisition.with patch("tools.computer_use.cua_backend.cua_driver_runtime_contract_status",return_value={"ready": True},-- ), patch("tools.lazy_deps.ensure"):++ ), patch("pm.ensure"), patch("pm.ensure_import"):backend.start()# First call_tool after _session.start() must be start_session@@@ -2272,7 -2292,7 +2135,7 @@@with patch("tools.computer_use.cua_backend.cua_driver_runtime_contract_status",return_value={"ready": True},-- ), patch("tools.lazy_deps.ensure"):++ ), patch("pm.ensure"), patch("pm.ensure_import"):backend.start() # must not raise@@@ -2426,7 -2446,7 +2289,7 @@@ class TestElementSpillFileassert "elements_file" in outassert str(out["elements_file"]) in out["summary"]spill = json.loads(-- open(out["elements_file"], encoding="utf-8").read())++ open(out["elements_file"], encoding="utf-8-sig").read())# Everything the in-context response dropped is in the file:assert spill["total_elements"] == 120assert len(spill["elements"]) == 120 # beyond max_elements capdiff --cc tools/bot_desktop/browser.pyindex 00000000000,fa44c637190..f9451e06ee0mode 000000,100644..100644--- a/tools/bot_desktop/browser.py+++ b/tools/bot_desktop/browser.py@@@ -1,0 -1,176 +1,174 @@@+ """The bot's browser on its Bot Desktop: one executable, one persistent user-data-dir per profile.++ The agent drives Chromium through agent-browser; a human who takes over clicks the dock's Browser+ icon. Both must be THE SAME browser — same binary, same ``--user-data-dir`` — or the human logs in+ to a jar the bot never sees. Chromium's singleton makes a second launch on the same user-data-dir+ open a window in the running instance, which is exactly the hand-over we want — in ONE direction. When the+ human's dock instance is already up, agent-browser's own launch is forwarded to it and dies without a+ DevTools endpoint, so the dock exposes a debugging port and the agent ATTACHES to it (see+ :func:`running_instance_cdp_port`) instead of launching.+ """++ from __future__ import annotations+-import glob+ import os+ import shutil+ import socket+ from pathlib import Path+ from typing import Optional, Tuple++ from tools.bot_desktop import runtime++ DISK_CACHE_BYTES = 256 * 1024 * 1024++ _SYSTEM_BROWSERS = ("google-chrome", "google-chrome-stable", "chromium", "chromium-browser")+++ def profile_dir() -> Path:+ """User-data-dir the bot's browser uses on this profile's screen. ``AGENT_BROWSER_PROFILE`` pins your own:+ ``~`` expands, and a relative path is anchored at this profile's HERMES_HOME (where the rest of the screen's+ state lives), so ``pin`` means ``<HERMES_HOME>/pin`` and two profiles never share one jar by accident."""+ override = os.path.expanduser(os.environ.get("AGENT_BROWSER_PROFILE", "").strip())+ if override:+ return Path(override) if os.path.isabs(override) else runtime.get_hermes_home() / override+ return runtime.state_dir() / "browser-profile"+++ def executable() -> Optional[str]:+ """The Chromium agent-browser launches: an explicit ``AGENT_BROWSER_EXECUTABLE_PATH``, else the newest+ Playwright Chromium it bundles, else a system Chrome/Chromium. ``None`` when there is none.++ Non-root under ``kernel.apparmor_restrict_unprivileged_userns=1`` (Ubuntu 23.10+) flips the order:+ Playwright's bundle has no setuid ``chrome_sandbox`` and dies 'FATAL: No usable sandbox!' there, while+ a distro chromium ships the helper. The bundle stays the answer when it is the only browser — a dock+ icon that fails loudly beats a non-root ``--no-sandbox``.+ """+ explicit = os.environ.get("AGENT_BROWSER_EXECUTABLE_PATH", "").strip()+ if explicit and os.access(explicit, os.X_OK) and not _is_headless_shell(explicit):+ return explicit- finders = [_playwright_executable, _system_executable]++ finders = [_managed_executable, _system_executable]+ if not _is_root() and _userns_restricted():+ finders.reverse()+ return next((exe for find in finders if (exe := find())), None)++-def _playwright_executable() -> Optional[str]:- from tools.browser_tool_install import _chromium_search_roots- candidates = sorted(- (p for root in _chromium_search_roots() for p in glob.glob(os.path.join(root, "chromium-*", "chrome-linux*", "chrome"))),- key=os.path.getmtime, reverse=True)- return next((exe for exe in candidates if os.access(exe, os.X_OK)), None)++def _managed_executable() -> Optional[str]:++ from hermes_cli.browser_runtime import chromium_executable++++ exe = chromium_executable()++ return exe if exe and os.access(exe, os.X_OK) and not _is_headless_shell(exe) else None+++ def _is_headless_shell(exe: str) -> bool:+ """Playwright's ``chrome-headless-shell`` can drive pages but cannot open a window: the official Docker+ image ships only that build and its boot hook exports it as ``AGENT_BROWSER_EXECUTABLE_PATH``, so+ trusting the override blindly would pin a windowless binary to the dock's Browser icon."""+ return "headless" in os.path.basename(exe).lower() or "headless_shell" in exe+++ def _system_executable() -> Optional[str]:+ return next((shutil.which(name) for name in _SYSTEM_BROWSERS if shutil.which(name)), None)+++ def _is_root() -> bool:+ return hasattr(os, "geteuid") and os.geteuid() == 0+++ def _userns_restricted() -> bool:+ from tools.browser_tool_session import apparmor_restricts_unprivileged_userns+ return apparmor_restricts_unprivileged_userns()+++ def dock_launch() -> Optional[Tuple[str, str]]:+ """``(executable, user_data_dir)`` for the dock's Browser icon, or ``None`` when no Chromium exists."""+ exe = executable()+ return (exe, str(profile_dir())) if exe else None+++ def dock_argv(exe: str, user_data_dir: str) -> list[str]:+ """Command the dock's Browser icon runs. ``--remote-debugging-port=0`` makes a human-started+ instance attachable (Chromium writes the chosen port to ``<user-data-dir>/DevToolsActivePort``);+ first-run / default-browser dialogs would sit between the human and the bot's tabs."""+ # --test-type hides the "Chrome for Testing is only for automated testing" and unsupported-flag+ # (--no-sandbox as root) infobars, which otherwise sit at the top of the human's takeover view.+ # The same sandbox policy agent-browser starts this binary with (root, Docker, AppArmor userns): the+ # human's Browser is the bot's browser, in the same container; a stricter rule here just made the dock+ # icon die with 'No usable sandbox!' in the official image while the agent's own Chromium ran fine.+ from tools.browser_tool_session import CHROMIUM_SANDBOX_BYPASS_ARGS, _needs_chromium_sandbox_bypass+ # The profile is persistent by design (logins survive handoffs); its HTTP cache is not worth a+ # gateway's disk: uncapped it grows for months toward a hosted instance's 6 GB.+ return [exe, f"--user-data-dir={user_data_dir}", "--remote-debugging-port=0", "--no-first-run",+ "--no-default-browser-check", "--test-type", f"--disk-cache-size={DISK_CACHE_BYTES}",+ *(CHROMIUM_SANDBOX_BYPASS_ARGS if _needs_chromium_sandbox_bypass() else ())]+++ def dock_exec_line(exe: str, user_data_dir: str) -> str:+ """The ``Exec=`` line of the dock's ``.desktop`` entry. Every argument is double-quoted per the+ Desktop Entry spec (a browser under ``/opt/Google Chrome/`` or a profile under a spaced HERMES_HOME+ otherwise splits into garbage): inside the quotes ``" ` $ \\`` are backslash-escaped, and because the+ value is itself a string field, each of those backslashes is escaped once more."""+ def quote(arg: str) -> str:+ quoted = "".join("\\" + ch if ch in '"`$\\' else ch for ch in arg)+ return '"' + quoted.replace("\\", "\\\\") + '"'+ return "Exec=" + " ".join(quote(arg) for arg in dock_argv(exe, user_data_dir))+++ def running_instance_cdp_port(user_data_dir: str, *, exclude_session: Optional[str] = None) -> Optional[int]:+ """DevTools port of a Chromium currently running on ``user_data_dir``, or ``None``.++ Both files outlive a crashed or closed Chromium: ``SingletonLock`` is a symlink to ``host-pid`` and+ ``DevToolsActivePort`` keeps the last port, so the pid must be alive AND the port must accept a+ connection before it is trusted. An instance agent-browser launched for ``exclude_session`` itself is+ reported as ``None``: its daemon already owns that browser, and handing it ``--cdp`` would make it+ close the browser as a config change and then attach to the port that just died with it.+ """+ try:- with open(os.path.join(user_data_dir, "DevToolsActivePort"), encoding="utf-8") as fh:++ with open(os.path.join(user_data_dir, "DevToolsActivePort"), encoding="utf-8-sig") as fh:+ port_line = fh.readline().strip()+ target = os.readlink(os.path.join(user_data_dir, "SingletonLock"))+ except OSError:+ return None+ _host, _, pid_text = target.rpartition("-")+ if not (port_line.isdigit() and pid_text.isdigit()) or not _pid_alive(int(pid_text)):+ return None+ if exclude_session and _launched_by_session(int(pid_text)) == exclude_session:+ return None+ port = int(port_line)+ try:+ with socket.create_connection(("127.0.0.1", port), timeout=0.5):+ pass+ except OSError:+ return None+ return port+++ def _launched_by_session(chromium_pid: int) -> Optional[str]:+ """``AGENT_BROWSER_SESSION`` of the agent-browser daemon that spawned ``chromium_pid``, or ``None``+ for a human-started (dock) instance. Chromium itself gets a scrubbed environment, so the daemon's+ ``/proc/<ppid>/environ`` is the marker (Linux-only, same user)."""+ try:- with open(f"/proc/{chromium_pid}/status", encoding="utf-8") as fh:++ with open(f"/proc/{chromium_pid}/status", encoding="utf-8-sig") as fh:+ ppid = next((int(line.split()[1]) for line in fh if line.startswith("PPid:")), 0)+ with open(f"/proc/{ppid}/environ", "rb") as fh:+ raw = fh.read()+ except (OSError, ValueError):+ return None+ for item in raw.split(b"\0"):+ key, sep, value = item.partition(b"=")+ if sep and key == b"AGENT_BROWSER_SESSION":+ return value.decode("utf-8", "replace") or None+ return None+++ def _pid_alive(pid: int) -> bool:+ import psutil+ return psutil.pid_exists(pid)+++ def env_for_agent(env: dict) -> dict:+ """Pin agent-browser to the screen's browser identity unless the user pinned their own."""+ env.setdefault("AGENT_BROWSER_PROFILE", str(profile_dir()))+ exe = executable()+ if exe:+ env.setdefault("AGENT_BROWSER_EXECUTABLE_PATH", exe)+ return envdiff --cc tools/bot_desktop/lease.pyindex 00000000000,ffba3d2e3bf..6bf8f1c58a8mode 000000,100644..100644--- a/tools/bot_desktop/lease.py+++ b/tools/bot_desktop/lease.py@@@ -1,0 -1,252 +1,252 @@@+ """Who may drive a profile's Bot Desktop screen: the agent (default) or exactly one human viewer.++ The lease is the single truth shared by the RFB bridge (drops human input from non-holders), the+ ``computer_use`` tool (refuses to act while a human holds control — the person may be typing a+ credential, so even screenshots are refused; fail closed rather than trusting the agent to pause+ itself) and the Desktop UI (Watch / Take over / Hand back).++ Scope: the lease is a TOOL-LEVEL fence, not a property of the X server. ``computer_use`` and the browser+ tools consult it; a process the agent starts by hand against the published ``DISPLAY``/``XAUTHORITY``+ (the ``terminal`` tool, a script) is inside the documented same-user boundary and is not stopped by it+ (bot-screen.md, "Threat model"; #110040).++ Authority lives ON DISK, ``<HERMES_HOME>/bot-desktop/lease.json`` under an fcntl lock, because the+ processes that must agree do not share memory: ``hermes serve`` (viewer bridge), the messaging+ gateway, a CLI turn and isolated workers all drive the same display. Every read goes to the file;+ the in-process Condition only wakes local waiters early. ``epoch`` increments on every transition so+ an action admitted under one lease can tell that control changed underneath it.+ """++ from __future__ import annotations++ import json+ import logging+ import os+ import threading+ import time+ from dataclasses import asdict, dataclass, field+ from pathlib import Path+ from typing import Callable, Dict, List, Optional++ from hermes_constants import get_hermes_home, hermes_home_key, secure_parent_dir++ try:+ import fcntl+ except ImportError: # Windows/macOS without fcntl: computer_use imports this module on every call, and no+ fcntl = None # multi-process Bot Desktop exists there, so the cross-process lock degrades to a no-op.++ logger = logging.getLogger(__name__)++ AGENT = "agent"+ HUMAN = "human"+++ class HumanHasControl(RuntimeError):+ """Raised by screen-driving tools while a human holds the lease."""+++ @dataclass+ class Lease:+ holder: str = AGENT+ viewer_id: Optional[str] = None+ since: float = field(default_factory=time.time)+ reason: str = ""+ epoch: int = 0++ def as_dict(self) -> Dict[str, object]:+ return asdict(self)+++ def public_view(lease: Lease) -> Dict[str, object]:+ """The lease as anything outside the gateway may see it (RPC results, the ``display.lease`` broadcast,+ the CLI): the holder's viewer id is a capability — whoever presents it co-drives or releases the lease —+ so it is replaced by a short hash the holder can match against its own id to know it is in control."""+ import hashlib+ d = lease.as_dict()+ d["viewer_id"] = None+ d["viewer_hash"] = hashlib.sha256(lease.viewer_id.encode()).hexdigest()[:12] if lease.viewer_id else None+ return d+++ _lock = threading.Condition()+ _listeners: List[Callable[[str, Lease], None]] = []+++ def _path(profile_key: Optional[str]) -> Path:+ """``profile_key`` is the HERMES_HOME path of the profile whose lease is meant (the RFB bridge+ serves several profiles from one process); ``None`` means the current profile."""+ home = Path(profile_key) if profile_key else get_hermes_home()+ return home / "bot-desktop" / "lease.json"+++ def _read(path: Path) -> Lease:+ """No file = fresh profile, agent holds. A file that exists but cannot be parsed is a torn write+ or tampering: fail CLOSED (human holds) — an unreadable lease must never let the agent act on a+ screen a human may be using; the next successful write repairs it."""+ try:- raw = path.read_text(encoding="utf-8")++ raw = path.read_text(encoding="utf-8-sig")+ except FileNotFoundError:+ return Lease()+ except OSError:+ return Lease(holder=HUMAN, viewer_id="unreadable-lease", reason="lease file unreadable")+ try:+ data = json.loads(raw)+ except ValueError:+ data = None+ if not isinstance(data, dict) or data.get("holder") not in (AGENT, HUMAN):+ return Lease(holder=HUMAN, viewer_id="unreadable-lease", reason="lease file corrupt")+ try:+ return Lease(**{k: v for k, v in data.items() if k in Lease.__dataclass_fields__})+ except TypeError:+ return Lease(holder=HUMAN, viewer_id="unreadable-lease", reason="lease file corrupt")+++ def _private_dir(path: Path) -> None:+ """``bot-desktop/`` owner-only even when the lease is the first thing written there (a takeover can be+ recorded before start() ever ran, and the umask would otherwise leave it 0755)."""+ path.parent.mkdir(parents=True, exist_ok=True)+ secure_parent_dir(path)+++ def _open_private(path: str | bytes | os.PathLike, flags: int) -> int:+ """``open(..., opener=_open_private)``: the file is created 0600 regardless of the umask."""+ return os.open(path, flags, 0o600)+++ def _write(path: Path, lease: Lease) -> None:+ _private_dir(path)+ tmp = path.with_suffix(".json.tmp")+ with open(tmp, "w", encoding="utf-8", opener=_open_private) as fh:+ fh.write(json.dumps(lease.as_dict()))+ os.replace(tmp, path)+++ class _locked:+ """Cross-process critical section over the lease file (fcntl on a sibling lock file)."""++ def __init__(self, path: Path):+ self._lockfile = path.with_suffix(".lock")+ self._fh = None++ def __enter__(self):+ if fcntl is None:+ return self+ _private_dir(self._lockfile)+ self._fh = open(self._lockfile, "a+", encoding="utf-8", opener=_open_private) # noqa: SIM115 — closed in __exit__+ fcntl.flock(self._fh.fileno(), fcntl.LOCK_EX)+ return self++ def __exit__(self, *exc):+ if self._fh is None:+ return+ fcntl.flock(self._fh.fileno(), fcntl.LOCK_UN)+ self._fh.close()+++ def get(profile_key: Optional[str] = None) -> Lease:+ return _read(_path(profile_key))+++ def on_change(listener: Callable[[str, Lease], None]) -> Callable[[], None]:+ """Subscribe to lease transitions made IN THIS PROCESS (the gateway broadcasts them to Desktop+ clients). Transitions made by another process are observed by reading, not by callback."""+ with _lock:+ _listeners.append(listener)++ def _off() -> None:+ with _lock:+ if listener in _listeners:+ _listeners.remove(listener)+ return _off+++ def _notify(key: str, lease: Lease) -> None:+ for cb in list(_listeners):+ try:+ cb(key, lease)+ except Exception: # a broken subscriber must not wedge the handoff+ pass+++ def _transition(profile_key: Optional[str], mutate: Callable[[Lease], bool]) -> Lease:+ key, path = hermes_home_key(profile_key) if profile_key else hermes_home_key(), _path(profile_key)+ with _locked(path):+ lease = _read(path)+ if not mutate(lease):+ return lease+ lease.epoch += 1+ _write(path, lease)+ with _lock:+ _lock.notify_all()+ _notify(key, lease)+ return lease+++ def acquire(viewer_id: str, *, profile_key: Optional[str] = None, reason: str = "") -> Lease:+ """Human ``viewer_id`` takes control. Last writer wins: a second viewer evicts the first, and the+ RFB bridge closes the evicted socket so its UI drops to view-only."""+ def _m(lease: Lease) -> bool:+ if lease.holder == HUMAN and lease.viewer_id == viewer_id:+ return False # already theirs: no epoch bump, `since` and the reason on screen stay put+ # The agent's ask ("please log in to X") stays as the takeover reason: the human needs it+ # on screen WHILE they act, not only before they clicked Take over.+ lease.holder, lease.viewer_id, lease.since = HUMAN, viewer_id, time.time()+ lease.reason = reason or ""+ return True+ return _transition(profile_key, _m)+++ def release(viewer_id: Optional[str] = None, *, profile_key: Optional[str] = None,+ unless_human: bool = False) -> Lease:+ """Return control to the agent. With ``viewer_id`` only that holder may release (a stale viewer+ closing its window must not yank control from the one who took over after it). ``unless_human``+ makes a bare release a no-op while any human holds: the decision is taken under the file lock,+ so a takeover racing a check-then-release cannot be silently revoked. Callers read the returned+ lease's holder to learn whether anything happened."""+ def _m(lease: Lease) -> bool:+ if unless_human and lease.holder == HUMAN:+ logger.info("bot-desktop lease: bare release ignored, a human holds")+ return False+ if viewer_id is not None and lease.holder == HUMAN and lease.viewer_id != viewer_id:+ # Ignored, not an error: the returned lease still shows the real holder. Logged so a+ # caller that never inspects the return value leaves a trace.+ logger.info("bot-desktop lease: release by %r ignored, another viewer holds", viewer_id)+ return False+ if lease.holder == AGENT:+ # Already the agent's. Bumping the epoch here would make a legitimately admitted in-flight+ # agent action (a double-clicked Hand back, a stray CLI stop) look overtaken and get voided.+ return False+ lease.holder, lease.viewer_id, lease.since, lease.reason = AGENT, None, time.time(), ""+ return True+ return _transition(profile_key, _m)+++ def human_holds(profile_key: Optional[str] = None) -> bool:+ return get(profile_key).holder == HUMAN+++ def viewer_may_send_input(viewer_id: str, *, profile_key: Optional[str] = None) -> bool:+ lease = get(profile_key)+ return lease.holder == HUMAN and lease.viewer_id == viewer_id+++ def assert_agent_may_act(profile_key: Optional[str] = None) -> Lease:+ """The lease as of now, or ``HumanHasControl``. Callers keep the returned ``epoch`` and compare it+ with ``get().epoch`` after an admitted action: a change means a human took over mid-flight."""+ lease = get(profile_key)+ if lease.holder == HUMAN:+ raise HumanHasControl(+ "A human has taken over this desktop (they may be entering a credential). Screen actions and "+ "captures are refused until they hand control back. Tell the user what you need in your reply.")+ return lease+++ def _reset_for_tests() -> None:+ with _lock:+ _listeners.clear()+ p = get_hermes_home() / "bot-desktop" / "lease.json"+ for f in (p, p.with_suffix(".lock"), p.with_suffix(".json.tmp")):+ try:+ f.unlink()+ except OSError:+ passdiff --cc tools/bot_desktop/resources.pyindex 00000000000,99f3e93e724..6bd21090179mode 000000,100644..100644--- a/tools/bot_desktop/resources.py+++ b/tools/bot_desktop/resources.py@@@ -1,0 -1,101 +1,101 @@@+ """Host resources the screen needs before it starts: memory.++ A headed desktop is a big allocation relative to a small gateway host: Xvnc + Xfce idle at ~220 MiB+ and the browser a human opens during a takeover adds 500 MiB to 1 GiB (measured in the official image:+ gateway 304 MiB → +Xfce 520 MiB → +Chromium on one page 1,073 MiB). On a 4 GB container the loser+ of that squeeze is Chromium, killed mid-login, or the gateway itself. So ``runtime.start()`` refuses+ while the host cannot spare ``bot_desktop.min_free_memory_mb`` and ``display.status`` says why, which+ the pane shows in place of the Start button.++ "Available" is the tighter of two numbers: what the cgroup still allows (a container limit; v2+ ``memory.max``/``memory.current``, v1 ``memory.limit_in_bytes``/``memory.usage_in_bytes``) and what+ the kernel reports free for the whole machine (``MemAvailable``) — a limit of 8 GB on a 4 GB host is+ not 8 GB.+ """++ from __future__ import annotations++ from dataclasses import dataclass+ from pathlib import Path+ from typing import Optional++ _CGROUP_V2 = Path("/sys/fs/cgroup")+ _CGROUP_V1 = Path("/sys/fs/cgroup/memory")+ _MEMINFO = Path("/proc/meminfo")+ _MIB = 1024 * 1024+ DEFAULT_MIN_FREE_MB = 1536+++ @dataclass+ class MemoryInfo:+ available_mb: Optional[int] # None when nothing readable (non-Linux, odd sandboxes)+ limit_mb: Optional[int] # the cgroup limit when there is one, else the machine's MemTotal+++ def _read_int(path: Path) -> Optional[int]:+ try:- text = path.read_text(encoding="utf-8").strip()++ text = path.read_text(encoding="utf-8-sig").strip()+ except OSError:+ return None+ return int(text) if text.isdigit() else None # "max" → None+++ def _meminfo() -> dict[str, int]:+ try:- lines = _MEMINFO.read_text(encoding="utf-8").splitlines()++ lines = _MEMINFO.read_text(encoding="utf-8-sig").splitlines()+ except OSError:+ return {}+ out: dict[str, int] = {}+ for line in lines:+ key, _, rest = line.partition(":")+ parts = rest.split()+ if parts and parts[0].isdigit():+ out[key] = int(parts[0]) * 1024 # kB+ return out+++ def _cgroup_limit_and_usage() -> tuple[Optional[int], Optional[int]]:+ limit = _read_int(_CGROUP_V2 / "memory.max")+ usage = _read_int(_CGROUP_V2 / "memory.current")+ if limit is None and usage is None:+ limit = _read_int(_CGROUP_V1 / "memory.limit_in_bytes")+ usage = _read_int(_CGROUP_V1 / "memory.usage_in_bytes")+ if limit is not None and limit >= 1 << 60: # v1 "unlimited" is a huge sentinel+ limit = None+ return limit, usage+++ def memory_info() -> MemoryInfo:+ info = _meminfo()+ host_available = info.get("MemAvailable")+ host_total = info.get("MemTotal")+ limit, usage = _cgroup_limit_and_usage()+ candidates = [x for x in (host_available, (limit - usage) if limit is not None and usage is not None else None)+ if x is not None]+ available = min(candidates) if candidates else None+ limit_bytes = limit if limit is not None else host_total+ return MemoryInfo(available_mb=None if available is None else max(0, available // _MIB),+ limit_mb=None if limit_bytes is None else limit_bytes // _MIB)+++ def min_free_mb() -> int:+ from hermes_cli.config import load_config_readonly+ cfg = load_config_readonly().get("bot_desktop") or {}+ try:+ return max(0, int(cfg.get("min_free_memory_mb", DEFAULT_MIN_FREE_MB)))+ except (TypeError, ValueError):+ return DEFAULT_MIN_FREE_MB+++ def memory_blocker(info: Optional[MemoryInfo] = None) -> Optional[str]:+ """Why the screen must not start now, or None. Unknown memory is not a blocker: a host we cannot+ read is not a host we know to be small."""+ need = min_free_mb()+ if need == 0:+ return None+ info = info or memory_info()+ if info.available_mb is None or info.available_mb >= need:+ return None+ limit = f" of {info.limit_mb} MB" if info.limit_mb else ""+ return (f"Not enough free memory for a desktop: {info.available_mb} MB available{limit}, "+ f"{need} MB needed (bot_desktop.min_free_memory_mb)")diff --cc tools/bot_desktop/runtime.pyindex 00000000000,1af9d16625b..9b87e08de4bmode 000000,100644..100644--- a/tools/bot_desktop/runtime.py+++ b/tools/bot_desktop/runtime.py@@@ -1,0 -1,591 +1,591 @@@+ """Bot Desktop runtime: one headless Xfce desktop per Hermes profile, served over RFB on a private+ Unix socket, viewed and driven from Hermes Desktop.++ Layout under ``<HERMES_HOME>/bot-desktop/``: ``display`` (allocated X display number), ``rfb.sock``+ (Xvnc RFB Unix socket, 0600), ``Xauthority``, ``env`` (DISPLAY/XAUTHORITY/DBUS_SESSION_BUS_ADDRESS+ published by the launcher once Xfce's bus exists), ``launcher.pid``, ``launcher.log``, ``xdg/``+ (per-profile XDG_CONFIG_HOME so two profiles never share xfconf). Everything is profile-scoped via+ ``get_hermes_home()`` so N profiles in one gateway get N desktops: one screen per bot on the shared+ machine.++ The launcher is ``launcher.sh`` next to this module; :func:`desktop_env` is what cua-driver and headed+ Chromium spawns merge in so the agent acts on this profile's screen and nowhere else.+ """++ from __future__ import annotations++ import contextlib+ import logging+ import os+ import shutil+ import signal+ import subprocess+ import sys+ import time+ from dataclasses import dataclass+ from pathlib import Path+ from typing import Dict, Optional++ from hermes_constants import get_hermes_home++ logger = logging.getLogger(__name__)++ _LAUNCHER = Path(__file__).with_name("launcher.sh")++ # Display numbers below 10 collide with real seats and default Xvfb recipes (:99 is popular too); scan a+ # private band and record the choice so restarts reuse it.+ _DISPLAY_MIN, _DISPLAY_MAX = 20, 89++ # Binaries the launcher execs; the package hint is per distro family.+ REQUIRED_BINARIES = ("Xvnc", "xfwm4", "xfce4-panel", "xfdesktop", "xfsettingsd", "dbus-run-session",+ "xauth", "xdpyinfo", "setxkbmap", "xprop")++ # Which package in each distro list ships each required binary. Fedora retired the xorg-x11-utils /+ # xorg-x11-server-utils umbrellas (per-binary packages since F35) and dnf5 refuses the whole transaction on+ # one unknown name, so every binary must map to a package that still resolves; the test suite checks that+ # each mapped package is in PACKAGES for its manager.+ BINARY_PACKAGES = {+ "apt": {"Xvnc": "tigervnc-standalone-server", "xfwm4": "xfwm4", "xfce4-panel": "xfce4-panel",+ "xfdesktop": "xfdesktop4", "xfsettingsd": "xfce4-settings", "dbus-run-session": "dbus-x11",+ "xauth": "xauth", "xdpyinfo": "x11-utils", "setxkbmap": "x11-xkb-utils", "xprop": "x11-utils"},+ # tigervnc-x11-server is the real package (tigervnc-server-minimal is only a Provides on it); dbus-run-session+ # is in dbus-daemon (dbus-x11 ships dbus-launch only).+ "dnf": {"Xvnc": "tigervnc-x11-server", "xfwm4": "xfwm4", "xfce4-panel": "xfce4-panel",+ "xfdesktop": "xfdesktop", "xfsettingsd": "xfce4-settings", "dbus-run-session": "dbus-daemon",+ "xauth": "xorg-x11-xauth", "xdpyinfo": "xdpyinfo", "setxkbmap": "setxkbmap", "xprop": "xprop"},+ "pacman": {"Xvnc": "tigervnc", "xfwm4": "xfwm4", "xfce4-panel": "xfce4-panel", "xfdesktop": "xfdesktop",+ "xfsettingsd": "xfce4-settings", "dbus-run-session": "dbus",+ "xauth": "xorg-xauth", "xdpyinfo": "xorg-xdpyinfo", "setxkbmap": "xorg-setxkbmap", "xprop": "xorg-xprop"},+ }++ PACKAGES = {+ "apt": ["tigervnc-standalone-server", "xfce4-panel", "xfwm4", "xfdesktop4", "xfce4-settings",+ "xfce4-terminal", "dbus-x11", "x11-xserver-utils", "x11-utils", "x11-xkb-utils", "xauth",+ "fonts-dejavu-core"],+ "dnf": ["tigervnc-x11-server", "xfce4-panel", "xfwm4", "xfdesktop", "xfce4-settings",+ "xfce4-terminal", "dbus-daemon", "xsetroot", "xset", "xdpyinfo", "xprop", "xorg-x11-xauth", "setxkbmap",+ "dejavu-sans-fonts"],+ "pacman": ["tigervnc", "xfce4-panel", "xfwm4", "xfdesktop", "xfce4-settings", "xfce4-terminal", "dbus",+ "xorg-xsetroot", "xorg-xset", "xorg-xdpyinfo", "xorg-xprop", "xorg-xauth", "xorg-setxkbmap",+ "ttf-dejavu"],+ }+++ def state_dir() -> Path:+ return get_hermes_home() / "bot-desktop"+++ def is_supported_host() -> bool:+ return sys.platform.startswith("linux")+++ def missing_binaries() -> list[str]:+ return [b for b in REQUIRED_BINARIES if shutil.which(b) is None]+++ def package_manager() -> Optional[str]:+ for pm in ("apt-get", "dnf", "pacman"):+ if shutil.which(pm):+ return "apt" if pm == "apt-get" else pm+ return None+++ def install_command() -> Optional[str]:+ """The distro command that installs the Bot Desktop packages, as the human would type it on THIS host:+ prefixed with ``sudo`` unless Hermes already runs as root (the official Docker image is uid 0 with no+ sudo binary), so it is both what the pane shows and what :mod:`tools.bot_desktop.install` runs."""+ pm = package_manager()+ if pm is None:+ return None+ pkgs = " ".join(PACKAGES[pm])+ body = {+ "apt": f"apt-get install -y --no-install-recommends {pkgs}",+ "dnf": f"dnf install -y {pkgs}",+ "pacman": f"pacman -S --needed --noconfirm {pkgs}",+ }[pm]+ return body if is_root() else f"sudo {body}"+++ def is_root() -> bool:+ return hasattr(os, "geteuid") and os.geteuid() == 0+++ @dataclass+ class DesktopStatus:+ profile: str+ supported: bool+ installed: bool+ missing: list[str]+ running: bool+ pid: Optional[int]+ display: Optional[str]+ socket: Optional[str]+ geometry: str+ install_command: Optional[str]+ browser: Optional[str] # headed Chromium the dock's Browser icon and agent-browser share; None = no headed browser+ blocker: Optional[str] = None # why start() would refuse right now (memory); None = may start+ memory_available_mb: Optional[int] = None+ memory_limit_mb: Optional[int] = None++ def as_dict(self) -> Dict[str, object]:+ return dict(self.__dict__)+++ def _read(path: Path) -> Optional[str]:+ try:- return path.read_text(encoding="utf-8").strip() or None++ return path.read_text(encoding="utf-8-sig").strip() or None+ except OSError:+ return None+++ def _pid_alive(pid: int) -> bool:+ """A zombie is dead for our purposes: a SIGKILLed launcher stays a zombie in the gateway until the next+ Popen reaps it, and reporting it as running would hide its orphaned X server behind a live status."""+ import psutil+ try:+ return psutil.Process(pid).status() != psutil.STATUS_ZOMBIE+ except psutil.Error:+ return False+++ def _create_time(pid: int) -> Optional[float]:+ import psutil+ try:+ return psutil.Process(pid).create_time()+ except (psutil.Error, OverflowError, ValueError):+ return None+++ def _launcher_pid() -> Optional[int]:+ """The live launcher's pid, or None. ``launcher.pid`` holds ``"<pid> <create_time>"``: a recycled pid+ with a different start time is somebody else's process and must never be reported as ours nor+ killed by :func:`stop`. The pre-identity single-number format is treated as not running."""+ raw = _read(state_dir() / "launcher.pid")+ pid_s, _, born_s = (raw or "").partition(" ")+ if not pid_s.isdigit() or not born_s:+ return None+ try:+ pid, born = int(pid_s), float(born_s)+ except ValueError:+ return None+ actual = _create_time(pid)+ return pid if actual is not None and abs(actual - born) < 0.01 and _pid_alive(pid) else None+++ def _recorded_launcher_pid() -> Optional[int]:+ """The pid ``launcher.pid`` names, alive or not (the orphan sweep matches process groups against it)."""+ pid_s, _, born_s = (_read(state_dir() / "launcher.pid") or "").partition(" ")+ return int(pid_s) if pid_s.isdigit() and born_s else None+++ _X_LOCK_DIR = Path("/tmp") # no-tmp: ok — X servers write .X<n>-lock here by protocol (tests point it at a scratch dir)+ _X_UNIX_TABLE = Path("/proc/net/unix") # the kernel's list of bound Unix sockets (tests point it at a fixture)+++ def _x_lock_pid(num: int) -> Optional[int]:+ try:- return int((_X_LOCK_DIR / f".X{num}-lock").read_text(encoding="utf-8").strip())++ return int((_X_LOCK_DIR / f".X{num}-lock").read_text(encoding="utf-8-sig").strip())+ except (OSError, ValueError):+ return None+++ def _x_socket_bound(num: int) -> bool:+ """A running X server keeps ``@/tmp/.X11-unix/X<n>`` (abstract namespace) bound for its whole life; the+ kernel drops it only when the process exits. A /tmp reaper can remove the lock file under a live Xvnc,+ and only this binding then still says the number is taken (a new server on it dies 'already running')."""+ try:- lines = _X_UNIX_TABLE.read_text(encoding="utf-8").splitlines()++ lines = _X_UNIX_TABLE.read_text(encoding="utf-8-sig").splitlines()+ except OSError:+ return False+ # no-tmp: ok — detects the X server's display socket at the path the X11 protocol fixes+ return any(line.split()[-1].lstrip("@") == f"/tmp/.X11-unix/X{num}" for line in lines if line.strip())+++ def _display_in_use(num: int) -> bool:+ """A live X server owns ``:num``: its lock file names a running pid, or its X11 socket is bound. A lock+ left by a crashed server (dead pid, no socket) does not count, so the number can be reclaimed."""+ pid = _x_lock_pid(num)+ return (pid is not None and _pid_alive(pid)) or _x_socket_bound(num)+++ def _reap_orphaned_server(sd: Path) -> bool:+ """Caller holds ``start.lock`` and has established that no live launcher exists. The launcher runs Xvnc in+ its own session, so a SIGKILLed launcher leaves the X server alive, holding the display and ``rfb.sock``;+ ``status()`` keys on the launcher and says stopped, and a naive restart allocates a second server next+ to it and overwrites the socket path both now claim. The X lock of the recorded display names that+ server: it is ours when it sits in the dead launcher's process group or its command line binds OUR+ socket. When a /tmp reaper took the lock too (or the failed launch dropped ``display``), the socket path+ on the Xvnc command line is the remaining handle — without it one X server leaks per occurrence. Kill it+ (group first), drop the state it left, and report whether anything was signalled."""+ import psutil++ def _binds_our_socket(cmdline: list) -> bool:+ return "Xvnc" in Path(cmdline[0] if cmdline else "").name and str(sd / "rfb.sock") in cmdline++ recorded = _read(sd / "display")+ pid = _x_lock_pid(int(recorded)) if recorded and recorded.isdigit() else None+ if pid is None or not _pid_alive(pid):+ pid = next((p.pid for p in psutil.process_iter(["cmdline"]) if _binds_our_socket(p.info["cmdline"] or [])), None)+ if pid is None:+ return False+ launcher = _recorded_launcher_pid()+ try:+ pgid = os.getpgid(pid) # windows-footgun: ok — Linux-only runtime (is_supported_host gates start/stop)+ cmdline = psutil.Process(pid).cmdline()+ except (ProcessLookupError, psutil.Error):+ return False+ if pgid != launcher and not _binds_our_socket(cmdline):+ return False # somebody else's server took the number after we died; never touch it+ logger.warning("Bot Desktop launcher %s is gone but its X server (pid %s) survived on :%s; reaping",+ launcher, pid, recorded or "?")+ _kill_group_then_wait(pgid if pgid == launcher else None, pid)+ if recorded:+ (_X_LOCK_DIR / f".X{recorded}-lock").unlink(missing_ok=True)+ for name in ("launcher.pid", "env", "rfb.sock"):+ (sd / name).unlink(missing_ok=True)+ return True+++ def _kill_group_then_wait(pgid: Optional[int], pid: int, grace: float = 2.0) -> None:+ """SIGTERM the group (or the lone pid), SIGKILL whatever is still there after ``grace``."""+ def _signal(sig: int) -> None:+ with contextlib.suppress(ProcessLookupError, PermissionError):+ if pgid is not None:+ os.killpg(pgid, sig) # windows-footgun: ok — Linux-only runtime (is_supported_host gates start/stop)+ else:+ os.kill(pid, sig)+ def _anything_left() -> bool:+ # The leader dying first is the common case (bash exits on TERM, Xvnc traps it); the group is+ # done only when killpg(0) finds nobody, else a TERM-ignoring descendant keeps the display.+ if pgid is None:+ return _pid_alive(pid)+ try:+ os.killpg(pgid, 0) # windows-footgun: ok — Linux-only runtime (is_supported_host gates start/stop)+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ return True++ def _reap_if_ours() -> None:+ # The launcher was Popen'd by whichever gateway started it; a later gateway that stops it holds+ # no Popen, so the dead leader would sit as a zombie in our table (and count as "left").+ with contextlib.suppress(ChildProcessError, OSError):+ os.waitpid(pid, os.WNOHANG) # windows-footgun: ok — Linux-only runtime (is_supported_host gates start/stop)++ _signal(signal.SIGTERM)+ deadline = time.monotonic() + grace+ while time.monotonic() < deadline:+ _reap_if_ours()+ if not _anything_left():+ return+ time.sleep(0.05)+ _signal(signal.SIGKILL) # windows-footgun: ok — Linux-only runtime (is_supported_host gates start/stop)+ time.sleep(0.1)+ _reap_if_ours()+++ # Host-wide (every profile allocates from one band), so it lives outside any profile home — but not in+ # world-writable /tmp, where a predictable name lets another local user pre-create or squat the file.+ _ALLOC_LOCK = Path(os.environ.get("XDG_RUNTIME_DIR") or Path.home() / ".cache") / "hermes-bot-desktop-alloc.lock"+++ @contextlib.contextmanager+ def _flocked(path: Path):+ import fcntl # windows-footgun: ok — Linux-only runtime (is_supported_host gates start)+ with open(path, "a+", encoding="utf-8") as fh: # windows-footgun: ok — Linux-only runtime+ fcntl.flock(fh.fileno(), fcntl.LOCK_EX)+ try:+ yield fh+ finally:+ fcntl.flock(fh.fileno(), fcntl.LOCK_UN)+++ def _pick_display() -> int:+ """Caller holds ``_ALLOC_LOCK``. The recorded number is only reused when no OTHER server holds it now:+ after profile A stops, B may have taken A's number, and A's launcher must never unlink B's socket."""+ recorded = _read(state_dir() / "display")+ if recorded and recorded.isdigit() and not _display_in_use(int(recorded)):+ return int(recorded)+ for num in range(_DISPLAY_MIN, _DISPLAY_MAX + 1):+ if not _display_in_use(num):+ return num+ raise RuntimeError("no free X display number in the Bot Desktop band")+++ def _allocate_display() -> int:+ _ALLOC_LOCK.parent.mkdir(parents=True, exist_ok=True, mode=0o700)+ with _flocked(_ALLOC_LOCK):+ return _pick_display()+++ def desktop_env(base_env: Optional[Dict[str, str]] = None) -> Dict[str, str]:+ """``base_env`` (default ``os.environ``) with this profile's DISPLAY/XAUTHORITY/DBUS_SESSION_BUS_ADDRESS+ merged in when its desktop is running. Unchanged otherwise, so hosts with a real seat keep it.+ Pure: never starts anything (it is called from env builders, status probes and tests)."""+ env = dict(os.environ if base_env is None else base_env)+ published = published_env()+ if published:+ touch_activity() # a browser / cua-driver spawn is the agent using its screen+ env.update(published)+ env.pop("WAYLAND_DISPLAY", None) # X11 desktop; a leaked Wayland socket flips GTK/Chromium backends+ from tools.bot_desktop.browser import env_for_agent+ env_for_agent(env) # same binary + user-data-dir as the dock's Browser icon+ return env+++ def ensure_started_for_tool() -> None:+ """Tool-boundary hook (``computer_use`` dispatch and the headed Chromium spawn sites of the browser tool): with+ ``bot_desktop.auto_start`` (opt-in, default off) a Linux host that has NO display and the packages installed gets+ its screen started on first use, so a headless gateway works the first time instead of answering "no DISPLAY is+ set". Failure is not an error here; the tool's own "no display" diagnosis is the right message then."""+ if published_env():+ touch_activity()+ return+ if not _should_auto_start(os.environ):+ return+ try:+ start()+ except Exception as exc:+ logger.info("Bot Desktop auto-start skipped: %s", exc)+++ def _should_auto_start(env: Dict[str, str]) -> bool:+ if not is_supported_host() or env.get("DISPLAY") or env.get("WAYLAND_DISPLAY"):+ return False+ if missing_binaries():+ return False+ from hermes_cli.config import load_config_readonly+ cfg = load_config_readonly().get("bot_desktop") or {}+ return bool(cfg.get("auto_start", False))+++ # ---- idle auto-stop -------------------------------------------------------------------------------+ # A desktop nobody is using still holds ~220 MiB (plus whatever browser was left open). Every use —+ # a computer_use action, a browser spawn onto the screen, a viewer attached, a human takeover — stamps+ # ``activity``; the gateway's display watcher stops a screen idle past ``bot_desktop.idle_stop_minutes``+ # unless a human holds it. The next use starts it again (auto_start or the pane's Start).+ DEFAULT_IDLE_STOP_MINUTES = 30+++ def touch_activity() -> None:+ path = state_dir() / "activity"+ try:+ path.touch()+ os.utime(path, None)+ except OSError:+ pass+++ def idle_seconds() -> Optional[float]:+ """Seconds since the last stamped use; None when the screen never recorded one (falls back to the+ env file's publish time so a screen started and then forgotten still ages)."""+ for name in ("activity", "env"):+ try:+ return max(0.0, time.time() - (state_dir() / name).stat().st_mtime)+ except OSError:+ continue+ return None+++ def idle_stop_seconds() -> float:+ from hermes_cli.config import load_config_readonly+ cfg = load_config_readonly().get("bot_desktop") or {}+ try:+ minutes = float(cfg.get("idle_stop_minutes", DEFAULT_IDLE_STOP_MINUTES))+ except (TypeError, ValueError):+ minutes = DEFAULT_IDLE_STOP_MINUTES+ return max(0.0, minutes) * 60+++ def stop_if_idle() -> bool:+ """Stop this profile's screen when it has been idle past the limit and no human holds it. True when+ it was stopped."""+ limit = idle_stop_seconds()+ if limit <= 0 or _launcher_pid() is None:+ return False+ idle = idle_seconds()+ if idle is None or idle < limit:+ return False+ from tools.bot_desktop import lease as _bd_lease+ if _bd_lease.get().holder == _bd_lease.HUMAN:+ return False+ logger.info("Bot Desktop for profile %s idle for %.0f min; stopping", _profile_name(), idle / 60)+ return stop()+++ def published_env() -> Dict[str, str]:+ """Variables the launcher wrote once Xfce's private bus existed; empty when the desktop is down."""+ if _launcher_pid() is None:+ return {}+ raw = _read(state_dir() / "env")+ if not raw:+ return {}+ out: Dict[str, str] = {}+ for line in raw.splitlines():+ key, sep, value = line.partition("=")+ if sep:+ out[key.strip()] = value.strip()+ return out+++ def rfb_socket_path() -> Optional[Path]:+ sock = state_dir() / "rfb.sock"+ return sock if _launcher_pid() is not None and sock.exists() else None+++ def geometry() -> str:+ from hermes_cli.config import load_config_readonly+ cfg = load_config_readonly().get("bot_desktop") or {}+ return str(cfg.get("geometry") or "1440x900")+++ def status(profile: Optional[str] = None) -> DesktopStatus:+ from tools.bot_desktop import browser as _bd_browser+ from tools.bot_desktop import resources+ missing: list[str] = missing_binaries() if is_supported_host() else list(REQUIRED_BINARIES)+ pid = _launcher_pid()+ env = published_env()+ running = pid is not None and bool(env.get("DISPLAY"))+ mem = resources.memory_info() if is_supported_host() else resources.MemoryInfo(None, None)+ return DesktopStatus(+ profile=profile or _profile_name(),+ supported=is_supported_host(),+ installed=not missing,+ missing=missing,+ running=running,+ pid=pid,+ display=env.get("DISPLAY"),+ socket=str(rfb_socket_path()) if rfb_socket_path() else None,+ geometry=geometry(),+ install_command=install_command() if missing else None,+ browser=_bd_browser.executable() if is_supported_host() else None,+ # A running screen is never "blocked": the check guards the allocation, not the session.+ blocker=None if running or missing or not is_supported_host() else resources.memory_blocker(mem),+ memory_available_mb=mem.available_mb,+ memory_limit_mb=mem.limit_mb,+ )+++ def _profile_name() -> str:+ try:+ from hermes_cli.profiles import get_active_profile_name+ return get_active_profile_name() or "default"+ except Exception:+ return "default"+++ def start(*, wait_seconds: float = 15.0) -> DesktopStatus:+ """Start this profile's desktop (idempotent). Blocks until the launcher publishes its env file or+ ``wait_seconds`` pass; raises ``RuntimeError`` naming the blocker.++ Two locks: the per-profile ``start.lock``, held from the running-check to the launcher's publish so two+ start() calls for one profile spawn one launcher (the loser sees it running), and the host-wide+ display-allocation lock, held only until this Xvnc has written ``/tmp/.X<n>-lock`` (a second profile+ picking the same number before that would fail and its stale-lock cleanup could remove our socket).+ Holding it for the whole Xfce bring-up serialized every profile's start behind one desktop launch."""+ if not is_supported_host():+ raise RuntimeError("Bot Desktop runs on Linux gateway hosts only")+ missing = missing_binaries()+ if missing:+ hint = install_command() or "install TigerVNC (Xvnc) and the Xfce core components"+ raise RuntimeError(f"Bot Desktop needs {', '.join(missing)} on the gateway host. Install: {hint}")+ sd = state_dir()+ sd.mkdir(parents=True, exist_ok=True)+ os.chmod(sd, 0o700)+ with _flocked(sd / "start.lock"):+ if _launcher_pid() is not None and published_env().get("DISPLAY"):+ return status()+ from tools.bot_desktop import resources+ if (blocker := resources.memory_blocker()) is not None:+ raise RuntimeError(blocker)+ if _launcher_pid() is None:+ _reap_orphaned_server(sd)+ _ALLOC_LOCK.parent.mkdir(parents=True, exist_ok=True, mode=0o700)+ try:+ return _spawn_and_wait(sd, wait_seconds)+ except RuntimeError:+ # _pick_display reuses the recorded number first: left in place after a failed launch (e.g. Xvnc+ # 'server already running' on it), every retry would pick the same number and the profile wedges.+ (sd / "display").unlink(missing_ok=True)+ raise+++ def _spawn_and_wait(sd: Path, wait_seconds: float) -> DesktopStatus:+ """Caller holds ``start.lock``. Takes ``_ALLOC_LOCK`` itself, from picking the number to Xvnc's claim."""+ with contextlib.ExitStack() as alloc:+ alloc.enter_context(_flocked(_ALLOC_LOCK))+ num = _pick_display()+ (sd / "display").write_text(str(num), encoding="utf-8")+ env_file = sd / "env"+ env_file.unlink(missing_ok=True)++ child_env = {k: v for k, v in os.environ.items() if k not in {+ "DISPLAY", "XAUTHORITY", "WAYLAND_DISPLAY", "DBUS_SESSION_BUS_ADDRESS", "SESSION_MANAGER"}}+ child_env.update({+ "HERMES_BD_PROFILE": _profile_name(),+ "HERMES_BD_DISPLAY_NUM": str(num),+ "HERMES_BD_SOCKET": str(sd / "rfb.sock"),+ "HERMES_BD_XAUTH": str(sd / "Xauthority"),+ "HERMES_BD_ENV_FILE": str(env_file),+ "HERMES_BD_CONFIG_HOME": str(sd / "xdg"),+ "HERMES_BD_GEOMETRY": geometry(),+ })+ from tools.bot_desktop.browser import dock_exec_line, dock_launch+ if (browser := dock_launch()) is not None:+ # The bare executable (the launcher checks it exists) and the ready-made, spec-quoted Exec= line.+ child_env["HERMES_BD_BROWSER_EXEC"] = browser[0]+ child_env["HERMES_BD_BROWSER_EXEC_LINE"] = dock_exec_line(*browser)+ # Truncated per start: the log is a diagnostic for THIS launch, and nothing rotates it otherwise.+ log = open(sd / "launcher.log", "wb") # noqa: SIM115 — handed to the child, closed by it+ proc = subprocess.Popen( # windows-footgun: ok — Linux-only runtime (is_supported_host)+ ["bash", str(_LAUNCHER)], env=child_env, stdin=subprocess.DEVNULL, stdout=log, stderr=log,+ start_new_session=True, close_fds=True)+ log.close()+ born = _create_time(proc.pid)+ (sd / "launcher.pid").write_text(f"{proc.pid} {born if born is not None else 0}", encoding="utf-8")++ deadline = time.monotonic() + wait_seconds+ while time.monotonic() < deadline:+ if _x_lock_pid(num) is not None:+ alloc.close() # the number is Xvnc's now; other profiles may allocate (idempotent)+ if proc.poll() is not None:+ tail = (sd / "launcher.log").read_bytes()[-2000:].decode("utf-8", "replace")+ raise RuntimeError(f"Bot Desktop launcher exited with {proc.returncode}:\n{tail}")+ if env_file.exists() and (sd / "rfb.sock").exists():+ logger.info("Bot Desktop for profile %s up on :%s", _profile_name(), num)+ touch_activity()+ return status()+ time.sleep(0.1)+ # Giving up must take the launch down: left alone, the launcher publishes DISPLAY and rfb.sock a moment+ # later and a screen whose start() reported failure stays up as "running". The launcher is its own+ # session leader, so its group is exactly this launch (Xvnc, dbus, Xfce) and nothing else.+ _kill_group_then_wait(proc.pid, proc.pid)+ proc.wait()+ for name in ("launcher.pid", "env", "rfb.sock"):+ (sd / name).unlink(missing_ok=True)+ raise RuntimeError(f"Bot Desktop did not publish its display within {wait_seconds:.0f}s (see {sd / 'launcher.log'})")+++ def stop() -> bool:+ """Stop this profile's desktop; True when a running launcher (or the X server a dead one left behind)+ was signalled."""+ if not is_supported_host():+ return False+ sd = state_dir()+ sd.mkdir(parents=True, exist_ok=True)+ with _flocked(sd / "start.lock"):+ return _stop_locked(sd)+++ def _stop_locked(sd: Path) -> bool:+ pid = _launcher_pid()+ if pid is None:+ reaped = _reap_orphaned_server(sd)+ (sd / "env").unlink(missing_ok=True)+ return reaped+ # The launcher runs in its own session; killing the group takes Xvnc, dbus and Xfce with it.+ _kill_group_then_wait(pid, pid, grace=5.0)+ for name in ("launcher.pid", "env", "activity"):+ (sd / name).unlink(missing_ok=True)+ return Truediff --cc tools/browser_tool_session.pyindex 5120a5bb667,4baf9b42d34..16bb40c3771--- a/tools/browser_tool_session.py+++ b/tools/browser_tool_session.py@@@ -31,6 -31,22 +31,22 @@@ _CHROMIUM_MISSING_DOCKER_HINT = ("Chrom_CHROMIUM_MISSING_HINT = f"Chromium browser is missing. Install it with: {_CHROMIUM_INSTALL}"+ # THE Chromium startup flags for a host where its sandbox cannot work; agent-browser gets them through+ # AGENT_BROWSER_ARGS and the Bot Desktop dock's Browser icon (same binary, same profile) through+ # ``tools.bot_desktop.browser.dock_argv`` — one list, or the human's click dies while the agent's works.+ CHROMIUM_SANDBOX_BYPASS_ARGS = ("--no-sandbox", "--disable-dev-shm-usage")+++ def apparmor_restricts_unprivileged_userns() -> bool:+ """Ubuntu 23.10+ default: unprivileged user namespaces are denied, so a Chromium whose+ ``chrome_sandbox`` helper is not setuid (Playwright's bundle) dies with 'No usable sandbox'."""+ try:- with open("/proc/sys/kernel/apparmor_restrict_unprivileged_userns", encoding="utf-8") as f:++ with open("/proc/sys/kernel/apparmor_restrict_unprivileged_userns", encoding="utf-8-sig") as f:+ return f.read().strip() == "1"+ except OSError:+ return False++def _needs_chromium_sandbox_bypass() -> bool:"""True when Chromium needs --no-sandbox to start reliably (root, Docker, AppArmor userns)."""if hasattr(os, "geteuid") and os.geteuid() == 0:@@@ -145,19 -166,11 +157,19 @@@ def _agent_browser_command_env(socket_d"""Credential-scrubbed env for one command: PATH fallbacks, the session socket dir, anddaemon-side idle self-termination (agent-browser 0.24+) mirroring the Python janitorunless the user set ``AGENT_BROWSER_IDLE_TIMEOUT_MS`` explicitly."""+ from pm import env_for+env = _bt._build_browser_env()env["PATH"] = _install._merge_browser_path(env.get("PATH", ""))+ env = env_for("agent-browser", base_env=env)+ from hermes_cli.browser_runtime import chromium_executable++ executable = chromium_executable()+ if executable:+ env["AGENT_BROWSER_EXECUTABLE_PATH"] = executableenv["AGENT_BROWSER_SOCKET_DIR"] = socket_dirif "AGENT_BROWSER_IDLE_TIMEOUT_MS" not in env:- env["AGENT_BROWSER_IDLE_TIMEOUT_MS"] = str(_bt.BROWSER_SESSION_INACTIVITY_TIMEOUT * 1000)+ env["AGENT_BROWSER_IDLE_TIMEOUT_MS"] = str(_daemon_idle_timeout_seconds() * 1000)return envdiff --cc tui_gateway/server.pyindex 22342ac85f6,ae2d0297a6e..9fc8c6af744--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@@ -3136,7 -3130,7 +3136,7 @@@ def _append_spawn_tree_index(session_didef _read_spawn_tree_index(session_dir) -> list[dict]:out: list[dict] = []try:-- with (session_dir / _SPAWN_TREE_INDEX).open("r", encoding="utf-8") as f:++ with (session_dir / _SPAWN_TREE_INDEX).open("r", encoding="utf-8-sig") as f:for line in f:if line := line.strip():with contextlib.suppress(json.JSONDecodeError):