Skip to content

The agent that grows with you

fix: a corrupt-image rejection must not blind the model for the session

kshitijk4poorb5dacdb12569
diff --git a/agent/message_sanitization.py b/agent/message_sanitization.py
index 336021cf5a5..5511a6dc696 100644
--- a/agent/message_sanitization.py
+++ b/agent/message_sanitization.py
@@ -378,9 +378,8 @@ _IMAGE_REJECTION_PHRASES = (
# Some OpenAI-compatible endpoints (e.g. (issue #57948)
"unexpected item type in content",
# ChatGPT-account Codex backend rejects data:image URLs in input_image; keyed on the
- # field-path apostrophe so other URL errors don't false-trip. Second: its wording for
- # corrupt/unsupported native image payloads.
- "image_url'. expected", "image data you provided does not represent a valid image",
+ # field-path apostrophe so other URL errors don't false-trip.
+ "image_url'. expected",
# DeepSeek's text-only request-body variant error.
"unknown variant `image_url`, expected `text`", "unknown variant image_url, expected text",
# OpenRouter HTTP 404 when no upstream endpoint accepts image input (passes the 4xx
@@ -389,6 +388,16 @@ _IMAGE_REJECTION_PHRASES = (
# request until exhaustion, and the gateway leaves every subsequent message queued behind the stuck turn
# — the P1 in issue #21160.
"no endpoints found that support image input",
+)
+
+# Provider error bodies meaning "this particular image payload is bad" — the model CAN see, it
+# just could not decode what it was sent. Matched by ``_looks_like_image_content_rejection`` too
+# (the turn recovers the same way: strip and retry), but the recovery must NOT remember the
+# model as image-rejecting for the session on their account: the next request with a good image
+# would be needlessly stripped for the rest of the session.
+_IMAGE_CORRUPT_PHRASES = (
+ # ChatGPT-account Codex backend's wording for corrupt/unsupported native image payloads.
+ "image data you provided does not represent a valid image",
# Kimi/Moonshot et al. reject truncated/corrupt image bytes baked into history.
# Kimi / Moonshot / other OpenAI-compatible Chinese providers reject truncated or corrupt image bytes
# with HTTP 400 "Invalid request: prepare image failed ... failed to decode image: invalid or
@@ -399,6 +408,8 @@ _IMAGE_REJECTION_PHRASES = (
"failed to decode image",
)
+_IMAGE_REJECTION_PHRASES = _IMAGE_REJECTION_PHRASES + _IMAGE_CORRUPT_PHRASES
+
def image_model_key(agent: Any) -> tuple:
"""``(provider, model)`` the agent is currently talking to — the key image rejections are
@@ -427,6 +438,12 @@ def _looks_like_image_content_rejection(error_body: str) -> bool:
return any(phrase in body for phrase in _IMAGE_REJECTION_PHRASES)
+def _looks_like_corrupt_image_rejection(error_body: str) -> bool:
+ """Return True when the rejection is about a bad image payload, not the model's capability."""
+ body = str(error_body or "").lower()
+ return any(phrase in body for phrase in _IMAGE_CORRUPT_PHRASES)
+
+
__all__ = [
"_SURROGATE_RE", "close_interrupted_tool_sequence",
"_sanitize_surrogates", "_sanitize_structure_surrogates", "_sanitize_messages_surrogates",
diff --git a/agent/turn_recovery.py b/agent/turn_recovery.py
index 5c137c0533b..5220ffe5c20 100644
--- a/agent/turn_recovery.py
+++ b/agent/turn_recovery.py
@@ -22,7 +22,7 @@ from agent.model_metadata import is_output_cap_error, parse_available_output_tok
from agent.retry_utils import is_zai_coding_overload_error, zai_coding_overload_retry_ceiling
from agent.error_classifier import FailoverReason, classify_api_error
from agent.message_sanitization import (
- _looks_like_image_content_rejection, _sanitize_messages_non_ascii,
+ _looks_like_corrupt_image_rejection, _looks_like_image_content_rejection, _sanitize_messages_non_ascii,
_sanitize_messages_surrogates, _sanitize_structure_non_ascii, _sanitize_structure_surrogates,
_strip_images_from_messages, _strip_non_ascii, image_model_key,
close_interrupted_tool_sequence,
@@ -254,17 +254,26 @@ def recover_before_classification(
# Send-path only. A rejection says what THIS model accepts, not what the conversation
# holds: stripping ``messages`` (canonical history) and forcing a flush deleted every
# image — and every image-only message — from state.db for good, so a later switch to a
- # vision model found them gone. Same failure as the ASCII strip in #117802. Record the
- # model; build_api_request strips images from each request to it instead.
- _rejected.add(_model_key)
- if isinstance(api_messages, list):
- _strip_images_from_messages(api_messages)
- _vlines(
- agent,
- "⚠️ Server rejected image content — sending text only to this model; "
- "images stay in the session history.",
- )
- return True, active_system_prompt
+ # vision model found them gone. Same failure as the ASCII strip in #117802.
+ if _looks_like_corrupt_image_rejection(_err_body):
+ # A bad payload says nothing about the model's capability: strip this attempt only
+ # (like the image_corrupt branch below) and leave the model unmarked so a later good
+ # image still reaches it. Retry only if something was stripped, or a text-only
+ # request would loop on the same error.
+ if isinstance(api_messages, list) and _strip_images_from_messages(api_messages):
+ _vlines(agent, "⚠️ Provider rejected a corrupted image — stripped images from the retry payload and retrying...")
+ return True, active_system_prompt
+ else:
+ # Record the model; build_api_request strips images from each request to it instead.
+ _rejected.add(_model_key)
+ if isinstance(api_messages, list):
+ _strip_images_from_messages(api_messages)
+ _vlines(
+ agent,
+ "⚠️ Server rejected image content — sending text only to this model; "
+ "images stay in the session history.",
+ )
+ return True, active_system_prompt
# AnthropicBedrock SDK raises "Unexpected event order" when Bedrock errors before
# message_start; fall back to native Converse for this session.
diff --git a/tests/agent/test_image_rejection_fallback.py b/tests/agent/test_image_rejection_fallback.py
index 49d98053c84..d10a0cec8b8 100644
--- a/tests/agent/test_image_rejection_fallback.py
+++ b/tests/agent/test_image_rejection_fallback.py
@@ -411,6 +411,36 @@ class TestRejectionNeverReachesPersistedHistory:
assert strip_images_for_rejecting_model(agent, api_messages) is False
assert str(api_messages).count("data:image/png") == 2
+ def test_a_corrupt_image_does_not_mark_the_model_image_rejecting(self):
+ """'failed to decode image' says the PAYLOAD is bad, not that the model is text-only.
+ The attempt is stripped and retried, but the model stays unmarked so a later request
+ with a good image still reaches it — otherwise one bad screenshot blinds the model for
+ the rest of the session."""
+ import copy
+
+ from agent.message_sanitization import strip_images_for_rejecting_model
+
+ class _CorruptErr(Exception):
+ status_code = 400
+ body = "Invalid request: prepare image failed: failed to decode image: invalid or unsupported image format"
+
+ from agent.turn_recovery import recover_before_classification
+
+ agent, history = self._agent(), self._history()
+ before, wire = copy.deepcopy(history), copy.deepcopy(history)
+ retry, _ = recover_before_classification(
+ agent, _CorruptErr(), messages=history, api_messages=wire,
+ api_kwargs={}, active_system_prompt="sys",
+ )
+
+ assert retry is True
+ assert "image_url" not in str(wire), "the retry payload should be text-only"
+ assert history == before
+ assert agent._image_rejecting_models == set()
+ api_messages = self._history()
+ assert strip_images_for_rejecting_model(agent, api_messages) is False
+ assert str(api_messages).count("data:image/png") == 2
+
def test_a_repeat_rejection_from_the_same_model_does_not_loop(self):
"""The per-model guard still stops re-entry: a second rejection from a model already
known to reject images falls through to normal error handling instead of retrying forever."""