The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(computer-use): expose screenshots for chat delivery
Gille188d47919a92
diff --git a/tests/tools/test_computer_use.py b/tests/tools/test_computer_use.pyindex a717086f9b9..68ca6b7da49 100644--- a/tests/tools/test_computer_use.py+++ b/tests/tools/test_computer_use.py@@ -6,6 +6,7 @@ import base64import jsonimport osimport sys+from pathlib import Pathfrom typing import Any, Dict, List, castfrom unittest.mock import MagicMock, patch@@ -79,7 +80,7 @@ class TestRegistration:from tools.computer_use import cua_backenddriver = tmp_path / "custom-cua-driver"- driver.write_text("#!/bin/sh\nexit 0\n")+ driver.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")driver.chmod(0o755)monkeypatch.setenv("HERMES_CUA_DRIVER_CMD", str(driver))@@ -2553,6 +2554,55 @@ class TestElementSpillFile:assert "elements_file" not in out+class TestCaptureScreenshotPersistence:+ """Image captures expose a bounded file for explicit user delivery."""++ _PNG_B64 = (+ "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76L"+ "AAAADUlEQVR4nGNgGAUgAAABCAABgukLHQAAAABJRU5ErkJggg=="+ )++ def _capture(self):+ from tools.computer_use.backend import CaptureResult++ return CaptureResult(+ mode="vision",+ width=8,+ height=8,+ png_b64=self._PNG_B64,+ image_mime_type="image/png",+ png_bytes_len=len(base64.b64decode(self._PNG_B64)),+ )++ def test_multimodal_capture_exposes_shareable_screenshot(+ self, tmp_path, monkeypatch,+ ):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ from tools.computer_use import tool as cu_tool++ monkeypatch.setattr(+ cu_tool, "_should_route_through_aux_vision", lambda: False,+ )+ out = cu_tool._capture_response(self._capture())++ screenshot_path = out["meta"]["screenshot_path"]+ assert screenshot_path in out["text_summary"]+ assert "MEDIA:" not in out["text_summary"]+ assert screenshot_path.startswith(str(tmp_path / "cache" / "images"))+ assert Path(screenshot_path).read_bytes() == base64.b64decode(self._PNG_B64)++ def test_capture_cache_is_bounded(self, tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ from tools.computer_use import tool as cu_tool++ monkeypatch.setattr(cu_tool, "_MAX_CAPTURE_FILES", 2)+ for _ in range(3):+ assert cu_tool._persist_capture_image(self._capture()) is not None++ captures = list((tmp_path / "cache" / "images").glob("computer_use_*.*"))+ assert len(captures) == 2++class TestBoundsScaleField:def test_scale_reported_when_spaces_diverge(self, tmp_path, monkeypatch):monkeypatch.setenv("HERMES_HOME", str(tmp_path))diff --git a/tools/computer_use/schema.py b/tools/computer_use/schema.pyindex 388a4778a99..1c0d322e418 100644--- a/tools/computer_use/schema.py+++ b/tools/computer_use/schema.py@@ -22,7 +22,11 @@ COMPUTER_USE_SCHEMA: Dict[str, Any] = {"Preferred workflow: call with ""action='capture' (mode='som' gives numbered element overlays), ""then click by `element` index for reliability. Pixel coordinates "- "are supported for models trained on them. Works on any window — "+ "are supported for models trained on them. Image captures include a "+ "shareable `screenshot_path`; when the user asks to receive the image "+ "and the current surface supports attachments, deliver that file using "+ "the platform's native MEDIA attachment syntax. Do not automatically "+ "send screenshots used only for computer control. Works on any window — ""hidden, minimized, or behind another app. Requires cua-driver to ""be installed."),diff --git a/tools/computer_use/tool.py b/tools/computer_use/tool.pyindex 951cf9715ce..ab2824b8d05 100644--- a/tools/computer_use/tool.py+++ b/tools/computer_use/tool.py@@ -1195,6 +1195,11 @@ def _capture_response(cap: CaptureResult, max_elements: int = _DEFAULT_MAX_ELEMEor image_dimensions[1] < _MIN_PROVIDER_IMAGE_DIMENSION))+ screenshot_path = (+ _persist_capture_image(cap)+ if cap.png_b64 and cap.mode != "ax" and not image_too_small+ else None+ )# Index only what's actually surfaced in the response — otherwise the# human-readable summary references element indices the model cannot@@ -1209,6 +1214,10 @@ def _capture_response(cap: CaptureResult, max_elements: int = _DEFAULT_MAX_ELEME]if bounds_note:summary_lines.append(f" ({bounds_note})")+ if screenshot_path:+ summary_lines.append(+ f" (shareable screenshot saved to {screenshot_path})"+ )if elements_file:summary_lines.append(f" (full element tree with untruncated labels saved to "@@ -1243,6 +1252,7 @@ def _capture_response(cap: CaptureResult, max_elements: int = _DEFAULT_MAX_ELEMEvisible_elements=visible_elements,truncated_elements=truncated_elements,elements_file=elements_file,+ screenshot_path=screenshot_path,)if routed is not None:return routed@@ -1278,6 +1288,8 @@ def _capture_response(cap: CaptureResult, max_elements: int = _DEFAULT_MAX_ELEMEpayload["truncated_elements"] = truncated_elementsif elements_file:payload["elements_file"] = elements_file+ if screenshot_path:+ payload["screenshot_path"] = screenshot_pathif bounds_scale:payload["bounds_scale"] = bounds_scalereturn json.dumps(payload)@@ -1303,9 +1315,10 @@ def _capture_response(cap: CaptureResult, max_elements: int = _DEFAULT_MAX_ELEME],"text_summary": summary,"meta": {"mode": cap.mode, "width": response_width, "height": response_height,- "elements": total_elements, "png_bytes": cap.png_bytes_len,- **({"elements_file": elements_file} if elements_file else {}),- **({"bounds_scale": bounds_scale} if bounds_scale else {})},+ "elements": total_elements, "png_bytes": cap.png_bytes_len,+ **({"screenshot_path": screenshot_path} if screenshot_path else {}),+ **({"elements_file": elements_file} if elements_file else {}),+ **({"bounds_scale": bounds_scale} if bounds_scale else {})},}# AX-only (or image-missing fallback): text path actually carries the# `elements` array, so the truncation note applies here.@@ -1446,6 +1459,7 @@ def _route_capture_through_aux_vision(visible_elements: Optional[List[UIElement]] = None,truncated_elements: int = 0,elements_file: Optional[str] = None,+ screenshot_path: Optional[str] = None,) -> Optional[str]:"""Pre-analyse the captured PNG via ``vision_analyze`` and return a text result.@@ -1559,6 +1573,8 @@ def _route_capture_through_aux_vision(payload["truncated_elements"] = truncated_elementsif elements_file:payload["elements_file"] = elements_file+ if screenshot_path:+ payload["screenshot_path"] = screenshot_pathreturn json.dumps(payload)@@ -1648,6 +1664,53 @@ _MAX_ELEMENT_LABEL_CHARS = 120# capture of a dense UI can spill; without pruning the cache grows unbounded._MAX_SPILL_FILES = 20+# Keep user-shareable capture files bounded independently from the gateway's+# periodic media-cache cleanup. CLI-only sessions may never start the gateway,+# and capture_after can otherwise leave an unbounded screenshot trail.+_MAX_CAPTURE_FILES = 20+++def _persist_capture_image(cap: CaptureResult) -> Optional[str]:+ """Save a capture in Hermes' media cache and return its absolute path.++ Captures are normally embedded only in the model's tool context. Persisting+ a bounded copy gives attachment-capable surfaces a real file to deliver+ when the user explicitly asks for the screenshot. This is best-effort: an+ unwritable cache must never break computer control.+ """+ if not cap.png_b64:+ return None+ try:+ import uuid as _uuid++ from hermes_constants import get_hermes_dir++ raw = base64.b64decode(cap.png_b64, validate=False)+ mime = str(cap.image_mime_type or "").lower()+ ext = ".jpg" if mime == "image/jpeg" or (+ not mime and cap.png_b64[:8].startswith("/9j/")+ ) else ".png"++ cache_dir = get_hermes_dir("cache/images", "image_cache")+ cache_dir.mkdir(parents=True, exist_ok=True)+ try:+ captures = sorted(+ cache_dir.glob("computer_use_*.*"),+ key=lambda path: path.stat().st_mtime,+ )+ keep_before_write = max(0, _MAX_CAPTURE_FILES - 1)+ for stale in captures[: max(0, len(captures) - keep_before_write)]:+ stale.unlink(missing_ok=True)+ except Exception:+ pass++ path = cache_dir / f"computer_use_{_uuid.uuid4().hex}{ext}"+ path.write_bytes(raw)+ return str(path)+ except Exception as exc: # pragma: no cover - defensive+ logger.debug("computer_use: screenshot persistence failed: %s", exc)+ return None+def _spill_elements_to_file(cap: CaptureResult) -> Optional[str]:"""Write the FULL element tree (untruncated labels) to a cache file.