The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(vision): disclose downscale factor and crop offset for coordinate mapping
teknium12278056256be
diff --git a/tests/tools/test_vision_scale_disclosure.py b/tests/tools/test_vision_scale_disclosure.pynew file mode 100644index 00000000000..f3678aeb79c--- /dev/null+++ b/tests/tools/test_vision_scale_disclosure.py@@ -0,0 +1,256 @@+"""Downscale coordinate-scale disclosure tests.++When an image is downscaled (or region-cropped) before reaching a vision+model, the model's reported coordinates are in the *shrunk* (or crop-local)+coordinate space. These tests verify that both vision paths now disclose the+scale factor / crop offset so coordinates can be mapped back deterministically:++* ``tools.computer_use.tool._shrink_capture_for_vision`` returns+ ``(bytes, scale_note)``;+* ``tools.vision_tools.vision_analyze_tool`` emits a ``scale_note`` field and+ prefixes the analysis text when its downscale/region paths fire.++The scale math is verified deterministically with Pillow — no LLM needed.+"""++import io+import json+import os+import re+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++PIL = pytest.importorskip("PIL")+from PIL import Image # noqa: E402++from tools.computer_use.tool import _shrink_capture_for_vision # noqa: E402+from tools.vision_tools import _build_scale_note, vision_analyze_tool # noqa: E402+++ORIG_W, ORIG_H = 3024, 1964+SQUARE_X, SQUARE_Y, SQUARE_SIZE = 2400, 1500, 10+++def _make_marker_png_bytes() -> bytes:+ """Synthetic 3024x1964 black PNG with a red 10px square at (2400, 1500)."""+ img = Image.new("RGB", (ORIG_W, ORIG_H), (0, 0, 0))+ for x in range(SQUARE_X, SQUARE_X + SQUARE_SIZE):+ for y in range(SQUARE_Y, SQUARE_Y + SQUARE_SIZE):+ img.putpixel((x, y), (255, 0, 0))+ buf = io.BytesIO()+ img.save(buf, format="PNG")+ return buf.getvalue()+++def _make_noise_png(path, width: int, height: int) -> None:+ """Random-noise PNG: incompressible, so file size ~ raw pixel bytes."""+ img = Image.frombytes("RGB", (width, height), os.urandom(width * height * 3))+ img.save(path, format="PNG")+++def _red_square_center(img: Image.Image) -> tuple[float, float]:+ """Bounding-box center of reddish pixels (antialiasing-tolerant)."""+ rgb = img.convert("RGB")+ xs, ys = [], []+ px = rgb.load()+ for x in range(rgb.width):+ for y in range(rgb.height):+ r, g, b = px[x, y]+ if r > 100 and g < 100 and b < 100:+ xs.append(x)+ ys.append(y)+ assert xs, "red marker square not found in image"+ return (min(xs) + max(xs)) / 2.0, (min(ys) + max(ys)) / 2.0+++class TestShrinkCaptureForVision:+ def test_downscale_note_recovers_original_position(self):+ raw = _make_marker_png_bytes()+ shrunk_bytes, note = _shrink_capture_for_vision(raw, ".png")++ assert note is not None+ assert "downscaled" in note+ assert f"{ORIG_W}x{ORIG_H}" in note+ # Stated rounded factor: 3024/1456 = 2.0769... -> 2.08+ assert "2.08" in note++ m = re.search(r"downscaled from (\d+)x(\d+) to (\d+)x(\d+)", note)+ assert m, f"note missing dimensions: {note}"+ ow, oh, nw, nh = (int(v) for v in m.groups())+ assert (ow, oh) == (ORIG_W, ORIG_H)++ shrunk = Image.open(io.BytesIO(shrunk_bytes))+ assert shrunk.size == (nw, nh)+ assert max(shrunk.size) <= 1456++ # Recompute the marker position in the shrunk image via PIL and map+ # it back with the factors stated in the note.+ cx, cy = _red_square_center(shrunk)+ fx, fy = ow / nw, oh / nh+ recovered_x, recovered_y = cx * fx, cy * fy+ orig_cx = SQUARE_X + (SQUARE_SIZE - 1) / 2.0+ orig_cy = SQUARE_Y + (SQUARE_SIZE - 1) / 2.0+ assert abs(recovered_x - orig_cx) <= 2.0, (recovered_x, orig_cx)+ assert abs(recovered_y - orig_cy) <= 2.0, (recovered_y, orig_cy)++ def test_no_note_when_under_cap(self):+ img = Image.new("RGB", (800, 600), (10, 20, 30))+ buf = io.BytesIO()+ img.save(buf, format="PNG")+ raw = buf.getvalue()+ out, note = _shrink_capture_for_vision(raw, ".png")+ assert note is None+ assert out == raw # returned unchanged++ def test_no_note_on_undecodable_bytes(self):+ raw = b"not an image at all"+ out, note = _shrink_capture_for_vision(raw, ".png")+ assert out == raw+ assert note is None+++class TestBuildScaleNote:+ def test_none_when_nothing_happened(self):+ assert _build_scale_note(None, None) is None+ assert _build_scale_note({}, {}) is None++ def test_scale_factor_math(self):+ note = _build_scale_note(+ {"orig_width": 3024, "orig_height": 1964,+ "new_width": 1512, "new_height": 982},+ None,+ )+ assert note is not None+ assert "3024x1964" in note and "1512x982" in note+ assert "2.00" in note++ def test_crop_offset_only(self):+ note = _build_scale_note(None, {"x": 300, "y": 200,+ "width": 500, "height": 400})+ assert note is not None+ assert "(300, 200)" in note+ assert "crop" in note.lower()+++def _mock_llm_response(text: str = "described"):+ mock_response = MagicMock()+ mock_choice = MagicMock()+ mock_choice.message.content = text+ mock_response.choices = [mock_choice]+ return mock_response+++class TestVisionAnalyzeScaleDisclosure:+ @pytest.mark.asyncio+ async def test_downscale_path_emits_scale_note(self, tmp_path):+ # Noise is incompressible: 3024x1964 RGB noise -> ~17 MB PNG, base64+ # ~23 MB. With the hard cap patched to 8 MB, the pre-flight resize+ # fires and must disclose the downscale.+ img_path = tmp_path / "big_noise.png"+ _make_noise_png(img_path, ORIG_W, ORIG_H)++ with (+ patch("tools.vision_tools._MAX_BASE64_BYTES", 8 * 1024 * 1024),+ patch(+ "tools.vision_tools.async_call_llm",+ new_callable=AsyncMock,+ return_value=_mock_llm_response(),+ ),+ ):+ result = json.loads(+ await vision_analyze_tool(str(img_path), "describe", "test/model")+ )++ assert result["success"] is True+ assert "scale_note" in result+ note = result["scale_note"]+ assert f"downscaled from {ORIG_W}x{ORIG_H}" in note++ # Deterministic scale math: the factors in the note must equal+ # orig/new from the stated dimensions (2-decimal rounding).+ m = re.search(r"downscaled from (\d+)x(\d+) to (\d+)x(\d+)", note)+ assert m+ ow, oh, nw, nh = (int(v) for v in m.groups())+ assert (ow, oh) == (ORIG_W, ORIG_H)+ assert nw < ORIG_W and nh < ORIG_H+ fx = ow / nw+ assert f"{fx:.2f}" in note++ # Non-schema-aware consumers still see the note: analysis is prefixed.+ assert result["analysis"].startswith(f"[{note}]")++ @pytest.mark.asyncio+ async def test_small_image_has_no_scale_note(self, tmp_path):+ img_path = tmp_path / "small.png"+ Image.new("RGB", (320, 200), (5, 5, 5)).save(img_path, format="PNG")++ with patch(+ "tools.vision_tools.async_call_llm",+ new_callable=AsyncMock,+ return_value=_mock_llm_response(),+ ):+ result = json.loads(+ await vision_analyze_tool(str(img_path), "describe", "test/model")+ )++ assert result["success"] is True+ assert "scale_note" not in result+ assert not result["analysis"].startswith("[")++ @pytest.mark.asyncio+ async def test_region_plus_downscale_discloses_offset_and_factor(self, tmp_path):+ # Crop a 2400x1800 noise region (still ~17 MB base64) so BOTH the+ # crop-offset and the downscale disclosures must appear.+ img_path = tmp_path / "big_noise_region.png"+ _make_noise_png(img_path, ORIG_W, ORIG_H)+ region = [300, 100, 2700, 1900] # 2400x1800 at offset (300, 100)++ with (+ patch("tools.vision_tools._MAX_BASE64_BYTES", 8 * 1024 * 1024),+ patch(+ "tools.vision_tools.async_call_llm",+ new_callable=AsyncMock,+ return_value=_mock_llm_response(),+ ),+ ):+ result = json.loads(+ await vision_analyze_tool(+ str(img_path), "describe", "test/model", region=region,+ )+ )++ assert result["success"] is True+ note = result["scale_note"]+ # Downscale factor disclosed, computed from the crop dimensions.+ m = re.search(r"downscaled from (\d+)x(\d+) to (\d+)x(\d+)", note)+ assert m+ ow, oh, nw, nh = (int(v) for v in m.groups())+ assert (ow, oh) == (2400, 1800)+ assert f"{ow / nw:.2f}" in note+ # Crop offset disclosed: coordinates are relative to the crop origin.+ assert "(300, 100)" in note+ assert "relative" in note+ assert result["analysis"].startswith(f"[{note}]")++ @pytest.mark.asyncio+ async def test_region_only_discloses_offset(self, tmp_path):+ img_path = tmp_path / "small_region.png"+ Image.new("RGB", (800, 600), (0, 0, 0)).save(img_path, format="PNG")++ with patch(+ "tools.vision_tools.async_call_llm",+ new_callable=AsyncMock,+ return_value=_mock_llm_response(),+ ):+ result = json.loads(+ await vision_analyze_tool(+ str(img_path), "describe", "test/model",+ region=[100, 50, 400, 300],+ )+ )++ assert result["success"] is True+ note = result["scale_note"]+ assert "(100, 50)" in note+ assert "downscaled" not in note # crop fits: no scale clausediff --git a/tools/computer_use/tool.py b/tools/computer_use/tool.pyindex 1422ff67e43..cfbf7e03c61 100644--- a/tools/computer_use/tool.py+++ b/tools/computer_use/tool.py@@ -1073,25 +1073,47 @@ _MAX_VISION_DIM = 1456def _shrink_capture_for_vision(raw: bytes, ext: str,- max_dim: int = _MAX_VISION_DIM) -> bytes:+ max_dim: int = _MAX_VISION_DIM,+ ) -> tuple[bytes, Optional[str]]:"""Downscale encoded image bytes so the longest side is <= max_dim.- Returns the original bytes unchanged when the image already fits or when- Pillow is unavailable/fails — no worse than the pre-shrink behavior.+ Returns ``(bytes, scale_note)``. ``scale_note`` is ``None`` when the image+ was returned unchanged (already fits, or Pillow unavailable/failed — no+ worse than the pre-shrink behavior). When a downscale happened, the note+ tells the vision model the scale factor so any coordinates it reports can+ be mapped back to the real screen instead of being silently wrong."""try:from io import BytesIOfrom PIL import Imageimg = Image.open(BytesIO(raw))if max(img.size) <= max_dim:- return raw+ return raw, None+ orig_w, orig_h = img.sizeimg.thumbnail((max_dim, max_dim))+ new_w, new_h = img.sizeout = BytesIO()img.save(out, format="JPEG" if ext == ".jpg" else "PNG")- return out.getvalue()+ fx = orig_w / new_w if new_w else 1.0+ fy = orig_h / new_h if new_h else 1.0+ if f"{fx:.2f}" == f"{fy:.2f}":+ factor_clause = (+ f"multiply any coordinates you report by {fx:.2f} "+ f"to map back to the real screen."+ )+ else:+ factor_clause = (+ f"multiply any x coordinates you report by {fx:.2f} and "+ f"any y coordinates by {fy:.2f} to map back to the real screen."+ )+ scale_note = (+ f"Screenshot downscaled from {orig_w}x{orig_h} to "+ f"{new_w}x{new_h} for vision; {factor_clause}"+ )+ return out.getvalue(), scale_noteexcept Exception as exc:logger.debug("computer_use: vision downscale skipped: %s", exc)- return raw+ return raw, Nonedef _should_route_through_aux_vision() -> bool:"""Return True when ``_capture_response`` should hand the PNG to aux vision.@@ -1195,7 +1217,7 @@ def _route_capture_through_aux_vision(cache_dir = get_hermes_dir("cache/vision", "temp_vision_images")cache_dir.mkdir(parents=True, exist_ok=True)temp_image_path = cache_dir / f"computer_use_{_uuid.uuid4().hex}{ext}"- raw = _shrink_capture_for_vision(raw, ext)+ raw, scale_note = _shrink_capture_for_vision(raw, ext)temp_image_path.write_bytes(raw)prompt = (@@ -1207,6 +1229,8 @@ def _route_capture_through_aux_vision("actually visible.\n\n"f"AX/SOM index for cross-reference:\n{summary}")+ if scale_note:+ prompt += f"\n\nNote: {scale_note}"result_json = _run_async(vision_analyze_tool(str(temp_image_path), prompt)diff --git a/tools/vision_tools.py b/tools/vision_tools.pyindex 1c2b308e86e..e8d2091e404 100644--- a/tools/vision_tools.py+++ b/tools/vision_tools.py@@ -681,6 +681,7 @@ def _image_exceeds_dimension(image_path: Path, max_dimension: int) -> bool:def _crop_image_region(image_path: Path,region: Any,+ offset_out: Optional[dict] = None,) -> tuple[Optional[Path], Optional[str], Optional[str]]:"""Crop ``image_path`` to ``region`` = [x1, y1, x2, y2] (original-image pixels).@@ -731,6 +732,11 @@ def _crop_image_region(f"[0, 0, {width}, {height}].")cropped = img.crop((cx1, cy1, cx2, cy2))+ if offset_out is not None:+ offset_out["x"] = cx1+ offset_out["y"] = cy1+ offset_out["width"] = cx2 - cx1+ offset_out["height"] = cy2 - cy1out_path = image_path.with_name(f"{image_path.stem}_region_{uuid.uuid4().hex[:8]}.png")@@ -742,9 +748,55 @@ def _crop_image_region(return None, None, f"Failed to crop region: {exc}"+def _build_scale_note(+ scale_info: Optional[dict],+ crop_offset: Optional[dict],+) -> Optional[str]:+ """Build a coordinate-mapping disclosure note for the analysis result.++ ``scale_info`` (from :func:`_resize_image_for_vision`) carries the+ original and downscaled pixel dimensions when a downscale actually+ happened. ``crop_offset`` (from :func:`_crop_image_region`) carries the+ clamped crop origin when a region zoom was applied. Returns ``None`` when+ neither applies — no note, no noise.+ """+ parts = []+ if scale_info:+ ow, oh = scale_info["orig_width"], scale_info["orig_height"]+ nw, nh = scale_info["new_width"], scale_info["new_height"]+ fx = ow / nw if nw else 1.0+ fy = oh / nh if nh else 1.0+ if f"{fx:.2f}" == f"{fy:.2f}":+ factor_clause = (+ f"multiply any coordinates you report by {fx:.2f} "+ f"to map back to the original image."+ )+ else:+ factor_clause = (+ f"multiply any x coordinates you report by {fx:.2f} and "+ f"any y coordinates by {fy:.2f} to map back to the "+ f"original image."+ )+ parts.append(+ f"Image downscaled from {ow}x{oh} to {nw}x{nh} for vision; "+ f"{factor_clause}"+ )+ if crop_offset:+ parts.append(+ f"Analysis was performed on a cropped region of the original "+ f"image starting at offset ({crop_offset['x']}, "+ f"{crop_offset['y']}); coordinates are relative to that crop "+ f"origin — add the offset to map back to the full image."+ )+ if not parts:+ return None+ return " ".join(parts)++def _resize_image_for_vision(image_path: Path, mime_type: Optional[str] = None,max_base64_bytes: int = _RESIZE_TARGET_BYTES,- max_dimension: Optional[int] = None) -> str:+ max_dimension: Optional[int] = None,+ scale_out: Optional[dict] = None) -> str:"""Convert an image to a base64 data URL, auto-resizing if too large.Tries Pillow first to progressively downscale oversized images. If Pillow@@ -833,9 +885,18 @@ def _resize_image_for_vision(image_path: Path, mime_type: Optional[str] = None,# For JPEG, also try reducing quality at each size step.# For PNG, quality is irrelevant — only dimension reduction helps.quality_steps = (85, 70, 50) if pil_format == "JPEG" else (None,)+ orig_dims = (img.width, img.height)prev_dims = (img.width, img.height)candidate = None # will be set on first loop iteration+ def _record_scale(w: int, h: int) -> None:+ """Publish the downscale into ``scale_out`` when dims changed."""+ if scale_out is not None and (w, h) != orig_dims:+ scale_out["orig_width"] = orig_dims[0]+ scale_out["orig_height"] = orig_dims[1]+ scale_out["new_width"] = w+ scale_out["new_height"] = h+def _dims_ok(w: int, h: int) -> bool:"""True if both pixel dimensions are within the limit."""if max_dimension is None:@@ -876,6 +937,7 @@ def _resize_image_for_vision(image_path: Path, mime_type: Optional[str] = None,logger.info("Auto-resized image fits: %.1f MB (quality=%s, %dx%d)",len(candidate) / (1024 * 1024), q,img.width, img.height)+ _record_scale(img.width, img.height)return candidate# If we still can't get it small enough, return the best attempt@@ -883,6 +945,7 @@ def _resize_image_for_vision(image_path: Path, mime_type: Optional[str] = None,if candidate is not None:logger.warning("Auto-resize could not fit image under %.1f MB (best: %.1f MB)",max_base64_bytes / (1024 * 1024), len(candidate) / (1024 * 1024))+ _record_scale(img.width, img.height)return candidate# Shouldn't reach here, but fall back to full encode@@ -1008,6 +1071,7 @@ def _build_native_vision_tool_result(question: str,image_data_url: str,image_size_bytes: int,+ scale_note: Optional[str] = None,) -> Dict[str, Any]:"""Build the multimodal tool-result envelope returned by the fast path.@@ -1036,6 +1100,8 @@ def _build_native_vision_tool_result()if isinstance(question, str) and question.strip():text_part += f"\n\nQuestion: {question.strip()}"+ if scale_note:+ text_part += f"\n\nNote: {scale_note}"summary = (f"Image attached natively for the main model "@@ -1149,9 +1215,12 @@ async def _vision_analyze_native(# Optional region zoom: crop BEFORE the downscale/embed-cap pipeline# so the cropped area gets the full resolution budget.+ _crop_offset: dict = {}+ _scale_info: dict = {}if region is not None:cropped_path, cropped_mime, crop_err = await asyncio.to_thread(_crop_image_region, temp_image_path, region,+ offset_out=_crop_offset,)if crop_err or cropped_path is None:return tool_error(crop_err or "Region crop failed.", success=False)@@ -1188,6 +1257,7 @@ async def _vision_analyze_native(temp_image_path, mime_type=detected_mime_type,max_base64_bytes=_EMBED_TARGET_BYTES,max_dimension=_EMBED_MAX_DIMENSION,+ scale_out=_scale_info,)# If even resizing can't get under the absolute hard ceiling,# there's nothing more we can do — reject rather than embed a@@ -1208,6 +1278,9 @@ async def _vision_analyze_native(question=question,image_data_url=image_data_url,image_size_bytes=image_size_bytes,+ scale_note=_build_scale_note(+ _scale_info or None, _crop_offset or None,+ ),)except Exception as exc:@@ -1336,9 +1409,12 @@ async def vision_analyze_tool(# Optional region zoom: crop BEFORE the encode/downscale pipeline so# the cropped area gets the full resolution budget.+ _crop_offset: dict = {}+ _scale_info: dict = {}if region is not None:cropped_path, cropped_mime, crop_err = await asyncio.to_thread(_crop_image_region, temp_image_path, region,+ offset_out=_crop_offset,)if crop_err or cropped_path is None:raise ValueError(crop_err or "Region crop failed.")@@ -1366,7 +1442,8 @@ async def vision_analyze_tool(# Try to resize down to 5 MB before giving up.image_data_url = await _run_encode_on_cpu_executor(_resize_image_for_vision,- temp_image_path, mime_type=detected_mime_type)+ temp_image_path, mime_type=detected_mime_type,+ scale_out=_scale_info)if len(image_data_url) > _MAX_BASE64_BYTES:raise ValueError(f"Image too large for vision API: base64 payload is "@@ -1444,7 +1521,8 @@ async def vision_analyze_tool()image_data_url = await _run_encode_on_cpu_executor(_resize_image_for_vision,- temp_image_path, mime_type=detected_mime_type)+ temp_image_path, mime_type=detected_mime_type,+ scale_out=_scale_info)messages[0]["content"][1]["image_url"]["url"] = image_data_urlresponse = await async_call_llm(**call_kwargs)else:@@ -1464,10 +1542,16 @@ async def vision_analyze_tool(logger.info("Image analysis completed (%s characters)", analysis_length)# Prepare successful response+ analysis = analysis or "There was a problem with the request and the image could not be analyzed."+ scale_note = _build_scale_note(+ _scale_info or None, _crop_offset or None,+ )result = {"success": True,- "analysis": analysis or "There was a problem with the request and the image could not be analyzed."+ "analysis": f"[{scale_note}] {analysis}" if scale_note else analysis,}+ if scale_note:+ result["scale_note"] = scale_notedebug_call_data["success"] = Truedebug_call_data["analysis_length"] = analysis_length