Skip to content

The agent that grows with you

feat(vision): decode HEIF/HEIC/AVIF images (iPhone photos)

Samuel Painter0a545f7fa5ec
diff --git a/pyproject.toml b/pyproject.toml
index 486300eb06d..00c1f839830 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -147,6 +147,14 @@ dependencies = [
# install rather than gating it behind an extra + a mid-session lazy install
# (which deadlocked the CLI under prompt_toolkit — see #40490).
"Pillow==12.3.0",
+ # HEIF/HEIC/AVIF decode for the vision tools. iPhone photos and screenshots
+ # are HEIC (frequently mislabeled .jpg by upload pipelines); Pillow has no
+ # built-in HEIF codec, so without this the vision resolver rejects them as
+ # "not a recognized image". pillow-heif registers a Pillow opener so
+ # _normalize_to_supported_image can re-encode HEIF/AVIF to PNG before embed.
+ # Ships prebuilt wheels bundling libheif for the common platforms (no system
+ # libs needed), so it's safe in the base install alongside Pillow.
+ "pillow-heif==1.4.0",
# Windows log rotation. Stdlib ``RotatingFileHandler.doRollover()`` uses
# ``os.rename()`` which fails with ``PermissionError [WinError 32]`` on
# Windows whenever any other process holds an append-mode handle on
diff --git a/tests/tools/test_image_source.py b/tests/tools/test_image_source.py
index 8a2f568e431..0b7745f01a0 100644
--- a/tests/tools/test_image_source.py
+++ b/tests/tools/test_image_source.py
@@ -397,3 +397,80 @@ class TestLazySandboxBringUp:
with pytest.raises(isrc.SourceNotFound):
await isrc.resolve_image_source(str(secret), isrc.ResolveContext(task_id="t1"))
+
+
+# HEIF/HEIC/AVIF ISO-BMFF headers: 'ftyp' box at bytes 4-8, major brand at 8-12.
+# 0x18-byte box length prefix mirrors a real iPhone HEIC (\x00\x00\x00\x18 ftyp...).
+HEIC_HEADER = b"\x00\x00\x00\x18ftypheic\x00\x00\x00\x00mif1heic" + b"\x00" * 32
+AVIF_HEADER = b"\x00\x00\x00\x1cftypavif\x00\x00\x00\x00avifmif1" + b"\x00" * 32
+MIF1_HEADER = b"\x00\x00\x00\x18ftypmif1\x00\x00\x00\x00mif1heic" + b"\x00" * 32
+
+
+class TestHeicDetection:
+ """iPhone HEIC/HEIF (and AVIF) are sniffed from the ISO-BMFF ftyp brand so
+ they reach _normalize_to_supported_image instead of being rejected as
+ 'not a recognized image' (the pre-fix behavior for iPhone photos)."""
+
+ def test_heic_brand_detected(self):
+ from tools.vision_tools import _detect_image_mime_type_from_bytes
+ assert _detect_image_mime_type_from_bytes(HEIC_HEADER) == "image/heic"
+
+ def test_generic_mif1_brand_detected_as_heic(self):
+ from tools.vision_tools import _detect_image_mime_type_from_bytes
+ assert _detect_image_mime_type_from_bytes(MIF1_HEADER) == "image/heic"
+
+ def test_avif_brand_detected(self):
+ from tools.vision_tools import _detect_image_mime_type_from_bytes
+ assert _detect_image_mime_type_from_bytes(AVIF_HEADER) == "image/avif"
+
+ def test_ftyp_with_unknown_brand_not_misdetected(self):
+ """An ISO-BMFF ftyp box that isn't an image brand (e.g. mp4) stays
+ unrecognized — we must not claim every ftyp container is an image."""
+ from tools.vision_tools import _detect_image_mime_type_from_bytes
+ mp4 = b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00mp42isom" + b"\x00" * 32
+ assert _detect_image_mime_type_from_bytes(mp4) is None
+
+ @pytest.mark.asyncio
+ async def test_heic_resolves_and_normalizes_to_png(self, tmp_path, monkeypatch):
+ """End-to-end: a real HEIC file resolves (mime image/heic) and
+ _normalize_to_supported_image re-encodes it to PNG via pillow-heif."""
+ pillow_heif = pytest.importorskip("pillow_heif")
+ pillow_heif.register_heif_opener()
+ from PIL import Image
+ from tools import vision_tools as vt
+ isrc = _reload(monkeypatch, tmp_path / "hermes")
+ monkeypatch.setenv("TERMINAL_ENV", "local")
+
+ heic = tmp_path / "photo.heic"
+ Image.new("RGB", (8, 8), (120, 60, 200)).save(str(heic), format="HEIF")
+
+ res = await isrc.resolve_image_source(str(heic), isrc.ResolveContext())
+ assert res.mime == "image/heic"
+
+ path, mime, err = vt._normalize_to_supported_image(heic, "image/heic")
+ assert err is None
+ assert mime == "image/png"
+ assert path.read_bytes().startswith(b"\x89PNG\r\n\x1a\n")
+ path.unlink()
+
+ def test_heic_actionable_error_when_decoder_missing(self, tmp_path, monkeypatch):
+ """With pillow-heif unavailable, a HEIC image gets an actionable error
+ (install pillow-heif) rather than a generic conversion failure — the
+ same soft-dependency posture as SVG-without-rasterizer."""
+ from tools import vision_tools as vt
+ _reload(monkeypatch, tmp_path / "hermes")
+ heic = tmp_path / "photo.heic"
+ heic.write_bytes(HEIC_HEADER)
+
+ import builtins
+ real_import = builtins.__import__
+
+ def _no_heif(name, *args, **kwargs):
+ if name == "pillow_heif":
+ raise ImportError("pillow_heif not installed")
+ return real_import(name, *args, **kwargs)
+
+ with patch.object(builtins, "__import__", side_effect=_no_heif):
+ path, mime, err = vt._normalize_to_supported_image(heic, "image/heic")
+ assert path is None
+ assert "pillow-heif" in err
diff --git a/tools/vision_tools_image_prep.py b/tools/vision_tools_image_prep.py
index 908c1ef1851..dac11878c6b 100644
--- a/tools/vision_tools_image_prep.py
+++ b/tools/vision_tools_image_prep.py
@@ -64,6 +64,30 @@ def _detect_image_mime_type_from_bytes(data: bytes) -> Optional[str]:
return mime
if len(header) >= 12 and header[:4] == b"RIFF" and header[8:12] == b"WEBP":
return "image/webp"
+ # HEIF/HEIC/AVIF — ISO-BMFF container: bytes 0-4 are the box size, 4-8 the box type 'ftyp',
+ # 8-12 the major brand, and every 4 bytes from 16 a compatible brand. iPhone photos are HEIC
+ # (often mislabeled .jpg by upload pipelines); vision providers don't ingest HEIF, but
+ # _normalize_to_supported_image re-encodes it to PNG via pillow-heif (same soft-dependency
+ # pattern as SVG). The major brand alone can't tell AVIF from HEIC: AVIF files routinely carry
+ # generic 'mif1' as major and identify the codec only in the compatible-brand list.
+ if len(header) >= 12 and header[4:8] == b"ftyp":
+ major = header[8:12]
+ # Bound the brand scan by the declared box size so brands are never read out of a FOLLOWING
+ # box. A malformed size fails CLOSED (no compatible brands scanned) — falling back to the
+ # whole sniff window would widen the scan exactly when an attacker controls the size field.
+ # A size >= 16 overrunning the sniffed window is merely a truncated read: clamp it.
+ box_size = int.from_bytes(header[:4], "big")
+ limit = 16 if box_size < 16 else min(box_size, len(header))
+ brands = {major} | {header[i:i + 4] for i in range(16, limit - 3, 4)}
+ # AV1-coded brands win over the generic HEIF ones when both appear.
+ if brands & {b"avif", b"avis", b"av01"}:
+ return "image/avif"
+ if brands & {
+ b"heic", b"heix", b"heim", b"heis", # HEVC-coded HEIF still/sequence
+ b"hevc", b"hevx",
+ b"mif1", b"msf1", # generic HEIF image / sequence
+ }:
+ return "image/heic"
return None
@@ -137,6 +161,18 @@ def _normalize_to_supported_image(
"inkscape). Convert the SVG to PNG first — e.g. open it in a browser "
"and screenshot it, or install a rasterizer "
"(`pip install cairosvg`) — then re-run vision_analyze on the PNG.")
+ # HEIF/AVIF need a codec Pillow's core doesn't always carry, served by DIFFERENT optional
+ # backends that must not be gated on one another: HEIC/HEIF (HEVC) needs the pillow-heif
+ # plugin registered; AVIF (AV1) is native in Pillow >= 11.3 while pillow-heif wheels are
+ # frequently built with NO AV1 codec at all. Register whatever backend is available, let the
+ # decode attempt be the arbiter, and only emit a codec-specific error if it really fails —
+ # same soft-dependency posture as the SVG branch.
+ if detected_mime in ("image/heic", "image/avif"):
+ try:
+ import pillow_heif # type: ignore
+ pillow_heif.register_heif_opener()
+ except Exception:
+ logger.debug("pillow-heif unavailable; relying on Pillow for %s", detected_mime)
try:
from PIL import Image as _PILImage
with _PILImage.open(image_path) as _img:
@@ -147,6 +183,20 @@ def _normalize_to_supported_image(
return out_path, "image/png", None
except Exception as _exc:
logger.warning("Failed to normalize %s image to PNG: %s", detected_mime, _exc)
+ # Codec-specific guidance: name the backend that actually serves this format.
+ if detected_mime == "image/heic":
+ return None, None, (
+ "This is a HEIC/HEIF image (common for iPhone photos), which "
+ "vision models cannot read directly, and no HEIF decoder is "
+ "available. Install one (`pip install pillow-heif`) and re-run "
+ "vision_analyze, or convert the image to PNG/JPEG first.")
+ if detected_mime == "image/avif":
+ return None, None, (
+ "This is an AVIF image, which vision models cannot read "
+ "directly, and no AV1 decoder is available. Upgrade Pillow "
+ "(>= 11.3 bundles AVIF support) or install a pillow-heif build "
+ "with an AV1 codec, then re-run vision_analyze — or convert the "
+ "image to PNG/JPEG first.")
return None, None, (
f"Image format {detected_mime!r} is not supported by the vision API "
f"and could not be converted to PNG (install Pillow for raster "