Skip to content

The agent that grows with you

fix(vision): shrink oversized history embeds via JPEG quality, not halving

kshitijk4poorc02fe6501bb1
diff --git a/tests/tools/test_vision_tools.py b/tests/tools/test_vision_tools.py
index 806382f649d..58a6d8d0044 100644
--- a/tests/tools/test_vision_tools.py
+++ b/tests/tools/test_vision_tools.py
@@ -740,6 +740,70 @@ class TestResizeImageForVision:
# Should return the original (oversized) data url
assert len(result) > 100
+ def test_force_jpeg_keeps_resolution_of_dense_png(self, tmp_path):
+ """A dense PNG over the byte cap shrinks via JPEG quality, not halving.
+
+ PNG has no quality ladder — before force_jpeg, the only shrink lever
+ for a text-dense screenshot was halving dimensions (1568px → ~784px),
+ destroying text legibility (#92699 follow-up). With force_jpeg the
+ quality ladder absorbs the byte pressure and resolution survives.
+ """
+ try:
+ from PIL import Image
+ except ImportError:
+ pytest.skip("Pillow not installed")
+ import base64 as _b64
+ import random
+ from io import BytesIO
+
+ # Photo-like PNG at exactly the long-edge cap: a gradient with
+ # low-amplitude noise defeats PNG's lossless filters (no exact
+ # repeats → >256KB) but JPEG's DCT quantization absorbs it easily —
+ # the realistic screenshot shape, unlike pure noise which no codec
+ # can fit in-budget at full resolution.
+ rng = random.Random(42)
+ img = Image.new("RGB", (1568, 900))
+ img.putdata([
+ (
+ min(255, (x * 255) // 1568 + rng.randrange(12)),
+ min(255, (y * 255) // 900 + rng.randrange(12)),
+ min(255, ((x + y) * 255) // 2468 + rng.randrange(12)),
+ )
+ for y in range(900)
+ for x in range(1568)
+ ])
+ path = tmp_path / "dense.png"
+ img.save(path, "PNG")
+
+ budget = 256 * 1024
+ result = _resize_image_for_vision(
+ path, mime_type="image/png",
+ max_base64_bytes=budget, max_dimension=1568,
+ force_jpeg=True,
+ )
+ assert result.startswith("data:image/jpeg;base64,")
+ assert len(result) <= budget
+ with Image.open(BytesIO(_b64.b64decode(result.partition(",")[2]))) as out:
+ # Resolution preserved (the PNG path would have halved to 784px).
+ assert max(out.size) == 1568
+
+ def test_force_jpeg_leaves_small_png_untouched(self, tmp_path):
+ """Under-cap images skip the resize entirely — still PNG."""
+ try:
+ from PIL import Image
+ except ImportError:
+ pytest.skip("Pillow not installed")
+ img = Image.new("RGB", (10, 10), (0, 255, 0))
+ path = tmp_path / "tiny.png"
+ img.save(path, "PNG")
+
+ result = _resize_image_for_vision(
+ path, mime_type="image/png",
+ max_base64_bytes=256 * 1024, max_dimension=1568,
+ force_jpeg=True,
+ )
+ assert result.startswith("data:image/png;base64,")
+
# ---------------------------------------------------------------------------
# _image_exceeds_dimension — proactive embed-time pixel-cap detector
diff --git a/tools/browser_tool.py b/tools/browser_tool.py
index 0d595f0f5ab..fc27d85946d 100644
--- a/tools/browser_tool.py
+++ b/tools/browser_tool.py
@@ -4745,6 +4745,7 @@ def browser_vision(question: str, annotate: bool = False, task_id: Optional[str]
mime_type="image/png",
max_base64_bytes=_EMBED_TARGET_BYTES,
max_dimension=_EMBED_MAX_DIMENSION,
+ force_jpeg=True,
)
native_result = _build_native_vision_tool_result(
image_url=str(screenshot_path),
diff --git a/tools/vision_tools.py b/tools/vision_tools.py
index 074dd14103d..e950bbb506a 100644
--- a/tools/vision_tools.py
+++ b/tools/vision_tools.py
@@ -793,7 +793,8 @@ def _build_scale_note(
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,
- scale_out: Optional[dict] = None) -> str:
+ scale_out: Optional[dict] = None,
+ force_jpeg: bool = False) -> str:
"""Convert an image to a base64 data URL, auto-resizing if too large.
Tries Pillow first to progressively downscale oversized images. If Pillow
@@ -805,6 +806,13 @@ def _resize_image_for_vision(image_path: Path, mime_type: Optional[str] = None,
count are forcibly downscaled even if they're under the byte
budget. Anthropic enforces an 8000 px per-side cap independently
of the 5 MB byte cap.
+ force_jpeg: Re-encode as JPEG even for PNG input when a resize is
+ needed. PNG has no quality ladder — its only shrink lever is
+ halving dimensions, which destroys text legibility on dense
+ screenshots. History-reuse embeds (#92699) opt in so a text-heavy
+ screenshot keeps its readable resolution and shrinks via JPEG
+ quality instead. Images already under both caps are returned
+ unchanged (still PNG).
Returns the base64 data URL string.
"""
@@ -862,8 +870,14 @@ def _resize_image_for_vision(image_path: Path, mime_type: Optional[str] = None,
max_base64_bytes / (1024 * 1024), max_dimension)
mime = mime_type or _determine_mime_type(image_path)
- # Choose output format: JPEG for photos (smaller), PNG for transparency
- pil_format = "PNG" if mime == "image/png" else "JPEG"
+ # Choose output format: JPEG for photos (smaller), PNG for transparency.
+ # force_jpeg overrides for history-reuse embeds: a resize-needing PNG
+ # screenshot re-encodes as JPEG so the quality ladder can shrink bytes
+ # without halving resolution (text legibility, #92699).
+ if force_jpeg:
+ pil_format = "JPEG"
+ else:
+ pil_format = "PNG" if mime == "image/png" else "JPEG"
out_mime = "image/png" if pil_format == "PNG" else "image/jpeg"
try:
@@ -1254,6 +1268,7 @@ async def _vision_analyze_native(
max_base64_bytes=_EMBED_TARGET_BYTES,
max_dimension=_EMBED_MAX_DIMENSION,
scale_out=_scale_info,
+ force_jpeg=True,
)
# If even resizing can't get under the absolute hard ceiling,
# there's nothing more we can do — reject rather than embed a