From c02fe6501bb1f59e47ebdfb55dcc649091ce0f42 Mon Sep 17 00:00:00 2001 From: kshitijk4poor <82637225+kshitijk4poor@users.noreply.github.com> Date: Sun, 23 Aug 2026 14:00:32 +0530 Subject: [PATCH] fix(vision): shrink oversized history embeds via JPEG quality, not halving MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PNG has no quality ladder, so a text-dense screenshot over the 256KB history-embed cap (#92699 / #92783) could only shrink by halving dimensions — 1568px dropped to ~784px and on-screen text became unreadable, the exact fidelity screenshot QA depends on. Add force_jpeg to _resize_image_for_vision: the two history-embed call sites (vision_analyze native, browser_vision native) re-encode resize-needing screenshots as JPEG so the quality ladder (85/70/50) absorbs the byte pressure and the readable resolution survives. Under-cap images are untouched and stay PNG; one-shot/reactive paths keep their existing format behavior. Flagged during the #92783 salvage review. --- tests/tools/test_vision_tools.py | 64 ++++++++++++++++++++++++++++++++ tools/browser_tool.py | 1 + tools/vision_tools.py | 21 +++++++++-- 3 files changed, 83 insertions(+), 3 deletions(-) diff --git a/tests/tools/test_vision_tools.py b/tests/tools/test_vision_tools.py index 806382f649..58a6d8d004 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 0d595f0f5a..fc27d85946 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 074dd14103..e950bbb506 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