The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: vision_analyze does not re-embed an image already attached natively to the current turn
teknium1503d818ddf07
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 79303c09110..21c3c493e08 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -1614,22 +1614,26 @@ def run_conversation(addresses, after every history rewrite including post-turn micro-compaction."""from agent.turn_context import export_current_turn_boundary-- result = _run_conversation_turn(- agent,- user_message,- system_message=system_message,- conversation_history=conversation_history,- task_id=task_id,- stream_callback=stream_callback,- persist_user_message=persist_user_message,- persist_user_timestamp=persist_user_timestamp,- persist_user_display_kind=persist_user_display_kind,- persist_user_display_metadata=persist_user_display_metadata,- persist_user_platform_id=persist_user_platform_id,- moa_config=moa_config,- turn_author=turn_author,- )+ from tools.vision_tools_history_budget import native_turn_images++ # Images attached natively to this user turn stay visible to vision_analyze for the turn, so+ # it does not embed the same pixels a second time into the same request (#76411).+ with native_turn_images(user_message):+ result = _run_conversation_turn(+ agent,+ user_message,+ system_message=system_message,+ conversation_history=conversation_history,+ task_id=task_id,+ stream_callback=stream_callback,+ persist_user_message=persist_user_message,+ persist_user_timestamp=persist_user_timestamp,+ persist_user_display_kind=persist_user_display_kind,+ persist_user_display_metadata=persist_user_display_metadata,+ persist_user_platform_id=persist_user_platform_id,+ moa_config=moa_config,+ turn_author=turn_author,+ )result = export_current_turn_boundary(agent, result, user_message)_close_durable_failed_turn(agent, result)return resultdiff --git a/tests/tools/test_vision_history_budget.py b/tests/tools/test_vision_history_budget.pyindex 64197ee1da4..c942ae970fe 100644--- a/tests/tools/test_vision_history_budget.py+++ b/tests/tools/test_vision_history_budget.py@@ -135,3 +135,32 @@ class TestEmbedTargetBytes:def test_bad_or_extreme_values_are_clamped_to_the_safe_range(self, raw, expected):_write_config(f"vision:\n embed_target_bytes: {raw}\n")assert budget.resolve_embed_target_bytes() == expected+++class TestNativeTurnDedupe:+ """An image the surface already attached natively to the active user turn must not be embedded+ a second time by ``vision_analyze`` in the same request (#76411)."""++ def test_same_image_in_active_turn_returns_text_not_a_second_embed(self, tmp_path):+ from agent.image_routing import build_native_content_parts+ same, other = _png(tmp_path / "same.png"), _png(tmp_path / "other.png", noisy=True)+ parts, skipped = build_native_content_parts("look", [same])+ assert not skipped+ with budget.native_turn_images(parts):+ result = _load(same)+ assert not _embedded(result)+ assert json.loads(result)["already_in_context"] is True+ # New detail (a crop) and a different file still embed.+ assert _embedded(_load(same, region=[0, 0, 8, 8]))+ assert _embedded(_load(other))++ def test_scope_ends_with_the_turn(self, tmp_path):+ from agent.image_routing import build_native_content_parts+ same = _png(tmp_path / "same.png")+ parts, _ = build_native_content_parts("look", [same])+ with budget.native_turn_images(parts):+ pass+ assert _embedded(_load(same))+ # A plain-text turn (no native parts) scopes nothing.+ with budget.native_turn_images("look at " + same):+ assert _embedded(_load(same))diff --git a/tools/vision_tools.py b/tools/vision_tools.pyindex 24f8302c51d..861a5f689d3 100644--- a/tools/vision_tools.py+++ b/tools/vision_tools.py@@ -37,6 +37,7 @@ from hermes_constants import get_hermes_dirfrom tools.debug_helpers import DebugSessionfrom tools.website_policy import check_website_accessfrom tools.vision_tools_history_budget import (+ native_turn_duplicate as _native_turn_duplicate,record_embed as _record_embed,release_embed as _release_embed,repeat_refusal as _repeat_refusal,@@ -591,6 +592,9 @@ async def _vision_analyze_native(or a JSON error string (the normal tool-result contract) on failure."""if not isinstance(image_url, str) or not image_url.strip():return tool_error("image_url is required", success=False)+ already_native = _native_turn_duplicate(image_url, region)+ if already_native is not None:+ return already_native# A cap > 0 RESERVES the slot here (atomic check-and-count); released below if no embed happens.refusal = _repeat_refusal(image_url)if refusal is not None:diff --git a/tools/vision_tools_history_budget.py b/tools/vision_tools_history_budget.pyindex 4bc64ac05e8..564ed530900 100644--- a/tools/vision_tools_history_budget.py+++ b/tools/vision_tools_history_budget.py@@ -8,11 +8,15 @@ may be embedded per session). See #112095: a delegated subagent re-loaded five s"""from __future__ import annotations+import contextlibimport hashlib+import jsonimport os+import reimport threading+from contextvars import ContextVarfrom pathlib import Path-from typing import Optional+from typing import Any, Iterator, Optionalfrom tools.registry import tool_error@@ -131,3 +135,46 @@ def release_embed(image_url: str) -> None:_repeat_counts[key] = count - 1else:_repeat_counts.pop(key, None)+++# Images already riding the ACTIVE user turn as native content parts (#76411). Every surface that+# attaches natively (gateway, CLI, TUI, delegated children) goes through+# ``image_routing.build_native_content_parts``, which writes one ``[Image attached at: <path>]`` /+# ``[Image attached: <url>]`` handle per image into the text part; ``conversation_loop.run_conversation``+# scopes those handles here for the turn and the tool inherits them through contextvars.+_NATIVE_HANDLE_RE = re.compile(r"^\[Image attached(?: at)?: (.+?)\]\s*$", re.MULTILINE)+_native_turn_images: ContextVar[frozenset[str]] = ContextVar("vision_native_turn_images", default=frozenset())+++def _native_turn_keys(user_message: Any) -> frozenset[str]:+ if not isinstance(user_message, list) or not any(+ isinstance(p, dict) and p.get("type") == "image_url" for p in user_message+ ):+ return frozenset()+ text = "\n".join(p.get("text", "") for p in user_message if isinstance(p, dict) and p.get("type") == "text")+ return frozenset(_image_key(m.strip()) for m in _NATIVE_HANDLE_RE.findall(text) if m.strip())+++def native_turn_images(user_message: Any) -> Iterator[None]:+ """Scope the images natively attached to ``user_message`` to the running turn."""+ token = _native_turn_images.set(_native_turn_keys(user_message))+ try:+ yield+ finally:+ _native_turn_images.reset(token)+++def native_turn_duplicate(image_url: str, region: Optional[list]) -> Optional[str]:+ """Text tool result when ``image_url`` already rides the active user turn natively, else+ ``None``. A native re-embed would put the identical pixels into the same request twice+ (the Telegram case in #76411); a ``region`` crop still embeds because it returns new detail."""+ if region is not None or _image_key(image_url) not in _native_turn_images.get():+ return None+ return json.dumps({+ "success": True,+ "already_in_context": True,+ "message": (+ "This image is already attached natively to the current user message — you can see it "+ "now. Answer with your built-in vision; pass a `region` to zoom into part of it."),+ })