Skip to content

The agent that grows with you

fix(anthropic): walk sibling tool_result blocks newest-first when evicting screenshots

teknium1406602bec7ed
diff --git a/agent/anthropic_message_convert.py b/agent/anthropic_message_convert.py
index c6928330d76..f8b94d4318e 100644
--- a/agent/anthropic_message_convert.py
+++ b/agent/anthropic_message_convert.py
@@ -619,10 +619,13 @@ def _evict_old_screenshots(result: List[Dict[str, Any]]) -> None:
for block in (msg.get("content") if isinstance(msg.get("content"), list) else [])
if _block_type(block) == "image"
)
+ # Parallel tool calls land as sibling tool_result blocks inside ONE user message
+ # (oldest first), so the inner walk must also run newest -> oldest or a batch that
+ # ends mid-message retires the newest frames instead of the oldest (#103217).
carriers = [
(block, sum(1 for b in block["content"] if b.get("type") == "image"))
for msg in reversed(result)
- for block in (msg.get("content") if isinstance(msg.get("content"), list) else [])
+ for block in reversed(msg.get("content") if isinstance(msg.get("content"), list) else [])
if _block_type(block) == "tool_result"
and isinstance(block.get("content"), list)
and _has_block_type(block["content"], {"image"})
diff --git a/tests/tools/test_computer_use.py b/tests/tools/test_computer_use.py
index d61732740d9..f81dcd9d4f2 100644
--- a/tests/tools/test_computer_use.py
+++ b/tests/tools/test_computer_use.py
@@ -517,6 +517,31 @@ class TestAnthropicAdapterMultimodal:
assert len(placeholders) == _SCREENSHOT_EVICTION_BATCH
assert len(with_images) == total - _SCREENSHOT_EVICTION_BATCH
+ def test_parallel_batch_retires_the_oldest_siblings_first(self):
+ """Sibling tool_results in one user message are oldest-first; eviction must not
+ retire the newest of them (#103217)."""
+ from agent.anthropic_message_convert import (
+ _OUTBOUND_IMAGE_LIMIT,
+ _SCREENSHOT_EVICTION_BATCH,
+ _evict_old_screenshots,
+ )
+
+ img = {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "A"}}
+ n = _OUTBOUND_IMAGE_LIMIT + 1
+ result = [{
+ "role": "user",
+ "content": [
+ {"type": "tool_result", "tool_use_id": f"t{i}", "content": [dict(img)]}
+ for i in range(n)
+ ],
+ }]
+ _evict_old_screenshots(result)
+ survivors = [
+ b["tool_use_id"] for b in result[0]["content"]
+ if any(x.get("type") == "image" for x in b["content"])
+ ]
+ assert survivors == [f"t{i}" for i in range(_SCREENSHOT_EVICTION_BATCH, n)]
+
def test_eviction_frontier_holds_between_batch_advances(self):
"""Screenshot eviction must not rewrite a new block on every capture.