The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(delegate): forward inline data-URL images to vision children; trim tests to invariants
teknium1230ca004a7c4
diff --git a/tests/tools/test_delegate_images.py b/tests/tools/test_delegate_images.pyindex c403419b129..a80090e5613 100644--- a/tests/tools/test_delegate_images.py+++ b/tests/tools/test_delegate_images.py@@ -1,23 +1,15 @@-"""Per-task image forwarding on delegate_task.--Port of RooCodeInc/Roomote#1796 / #1767 (Fast → coding-task attachment-forwarding): a task may carry an ``images`` list (local paths or http(s)-URLs). Vision-capable children receive the pixels as native ``image_url``-content parts on their goal turn; non-vision children get-``[Image attached at: …]`` hint lines they can feed to ``vision_analyze``.-Forwarding is best-effort — any failure degrades to the text-only goal.-"""+"""Per-task image forwarding on delegate_task: a task's ``images`` (local paths, http(s) or data: URLs) reach a+vision-capable child as native ``image_url`` content parts on its goal turn; non-vision children get+``[Image attached …]`` hints for ``vision_analyze``; any failure degrades to the text-only goal."""import base64from unittest.mock import patch-import pytest+from tools.delegate_tool import DELEGATE_TASK_SCHEMA, _MAX_TASK_IMAGES, _build_child_goal_message, _normalize_task_images+from tools.delegate_tool_child_run import _ChildRun-from tools.delegate_tool import (- DELEGATE_TASK_SCHEMA,- _MAX_TASK_IMAGES,- _build_child_goal_message,- _normalize_task_images,+_PNG = base64.b64decode(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==")@@ -26,148 +18,81 @@ class _FakeChild:model = "some/vision-model"-# ----------------------------------------------------------------------------# _normalize_task_images-# ------------------------------------------------------------------------------class TestNormalizeTaskImages:- def test_absent_is_none(self):- cleaned, err = _normalize_task_images({"goal": "g"}, 0)- assert cleaned is None- assert err is None-- def test_list_passes_through_stripped(self):- cleaned, err = _normalize_task_images(- {"images": [" /tmp/a.png ", "https://x.test/b.jpg"]}, 0- )- assert err is None- assert cleaned == ["/tmp/a.png", "https://x.test/b.jpg"]-- def test_bare_string_wrapped(self):- cleaned, err = _normalize_task_images({"images": "/tmp/a.png"}, 0)- assert err is None- assert cleaned == ["/tmp/a.png"]-- def test_non_list_rejected(self):- cleaned, err = _normalize_task_images({"images": {"path": "x"}}, 2)- assert cleaned is None- assert err and "Task 2" in err-- def test_non_string_entry_rejected(self):- cleaned, err = _normalize_task_images({"images": ["/tmp/a.png", 42]}, 0)- assert cleaned is None- assert err-- def test_empty_string_entry_rejected(self):- cleaned, err = _normalize_task_images({"images": [" "]}, 0)- assert cleaned is None- assert err-- def test_over_limit_rejected(self):- many = [f"/tmp/img{i}.png" for i in range(_MAX_TASK_IMAGES + 1)]- cleaned, err = _normalize_task_images({"images": many}, 1)- assert cleaned is None- assert err and str(_MAX_TASK_IMAGES) in err-- def test_empty_list_normalizes_to_none(self):- cleaned, err = _normalize_task_images({"images": []}, 0)- assert cleaned is None- assert err is None---# ----------------------------------------------------------------------------# _build_child_goal_message-# ------------------------------------------------------------------------------def _make_png(tmp_path, name="shot.png"):- # 1x1 transparent PNG- png = base64.b64decode(- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYGBg"- "AAAABQABh6FO1AAAAABJRU5ErkJggg=="- )+def _png(tmp_path, name="shot.png"):p = tmp_path / name- p.write_bytes(png)+ p.write_bytes(_PNG)return str(p)-class TestBuildChildGoalMessage:- def test_native_mode_builds_content_parts(self, tmp_path):- path = _make_png(tmp_path)- with patch(- "agent.image_routing.decide_image_input_mode", return_value="native"- ):- msg = _build_child_goal_message("Inspect the mock", [path], _FakeChild())- assert isinstance(msg, list)- types = [p.get("type") for p in msg]- assert types[0] == "text"- assert "image_url" in types- assert "Inspect the mock" in msg[0]["text"]- # local file embedded as data URL- img = next(p for p in msg if p.get("type") == "image_url")- assert img["image_url"]["url"].startswith("data:image/")-- def test_native_mode_passes_urls_verbatim(self):- url = "https://example.test/mock.png"- with patch(- "agent.image_routing.decide_image_input_mode", return_value="native"- ):- msg = _build_child_goal_message("Look", [url], _FakeChild())- assert isinstance(msg, list)- img = next(p for p in msg if p.get("type") == "image_url")- assert img["image_url"]["url"] == url-- def test_native_mode_all_unreadable_falls_back_to_text(self, tmp_path):- missing = str(tmp_path / "nope.png")- with patch(- "agent.image_routing.decide_image_input_mode", return_value="native"- ):- msg = _build_child_goal_message("Goal text", [missing], _FakeChild())- assert msg == "Goal text"-- def test_text_mode_appends_hints(self, tmp_path):- path = _make_png(tmp_path)- url = "https://example.test/a.png"- with patch(- "agent.image_routing.decide_image_input_mode", return_value="text"- ):- msg = _build_child_goal_message("Goal", [path, url], _FakeChild())- assert isinstance(msg, str)- assert f"[Image attached at: {path}]" in msg- assert f"[Image attached: {url}]" in msg- assert "vision_analyze" in msg-- def test_text_mode_missing_path_dropped(self, tmp_path):- missing = str(tmp_path / "gone.png")- with patch(- "agent.image_routing.decide_image_input_mode", return_value="text"- ):- msg = _build_child_goal_message("Goal", [missing], _FakeChild())- assert msg == "Goal"-- def test_any_exception_degrades_to_plain_goal(self):- with patch(- "agent.image_routing.decide_image_input_mode",- side_effect=RuntimeError("boom"),- ):- msg = _build_child_goal_message("Plain goal", ["/tmp/x.png"], _FakeChild())- assert msg == "Plain goal"---# ----------------------------------------------------------------------------# Tool-schema surface-# ------------------------------------------------------------------------------class TestToolSchemaSurface:- def test_images_on_task_items(self):- item = DELEGATE_TASK_SCHEMA["parameters"]["properties"]["tasks"]["items"]- assert "images" in item["properties"]- assert item["properties"]["images"]["type"] == "array"- assert "images" not in item["required"]-- def test_images_not_a_top_level_schema_param(self):- # Handler accepts top-level `images` for the legacy single-goal shape,- # but only the per-task field is advertised.- assert "images" not in DELEGATE_TASK_SCHEMA["parameters"]["properties"]+def test_normalize_task_images_shapes_and_limit():+ assert _normalize_task_images({"goal": "g"}, 0) == (None, None)+ assert _normalize_task_images({"images": []}, 0) == (None, None)+ assert _normalize_task_images({"images": "/tmp/a.png"}, 0) == (["/tmp/a.png"], None)+ assert _normalize_task_images({"images": [" /tmp/a.png ", "https://x.test/b.jpg"]}, 0) == (+ ["/tmp/a.png", "https://x.test/b.jpg"], None,+ )+ for bad in ({"path": "x"}, ["/tmp/a.png", 42], [" "]):+ cleaned, err = _normalize_task_images({"images": bad}, 2)+ assert cleaned is None and "Task 2" in err+ cleaned, err = _normalize_task_images({"images": [f"/tmp/{i}.png" for i in range(_MAX_TASK_IMAGES + 1)]}, 1)+ assert cleaned is None and str(_MAX_TASK_IMAGES) in err+++def test_native_mode_builds_image_parts_for_every_source_kind(tmp_path):+ path = _png(tmp_path)+ url = "https://example.test/mock.png"+ data_url = "data:image/png;base64," + base64.b64encode(_PNG).decode()+ with patch("agent.image_routing.decide_image_input_mode", return_value="native"):+ msg = _build_child_goal_message("Inspect the mock", [path, url, data_url], _FakeChild())+ assert msg[0]["type"] == "text" and "Inspect the mock" in msg[0]["text"]+ images = [p["image_url"]["url"] for p in msg if p.get("type") == "image_url"]+ assert len(images) == 3 and url in images+ assert images.count(data_url) == 2 # local file embedded as a data URL + the inline data URL passed verbatim+ assert data_url not in msg[0]["text"] # inline base64 never leaks into the text part+ # every source unreadable → plain goal, no empty multimodal envelope+ with patch("agent.image_routing.decide_image_input_mode", return_value="native"):+ assert _build_child_goal_message("Goal text", [str(tmp_path / "nope.png")], _FakeChild()) == "Goal text"+++def test_text_mode_hints_and_failure_degrade(tmp_path):+ path = _png(tmp_path)+ url = "https://example.test/a.png"+ with patch("agent.image_routing.decide_image_input_mode", return_value="text"):+ msg = _build_child_goal_message("Goal", [path, url, str(tmp_path / "gone.png")], _FakeChild())+ assert isinstance(msg, str)+ assert f"[Image attached at: {path}]" in msg and f"[Image attached: {url}]" in msg and "vision_analyze" in msg+ assert "gone.png" not in msg+ with patch("agent.image_routing.decide_image_input_mode", side_effect=RuntimeError("boom")):+ assert _build_child_goal_message("Plain goal", ["/tmp/x.png"], _FakeChild()) == "Plain goal"+++def test_child_run_sends_multimodal_goal_turn(tmp_path):+ """The attached images reach ``run_conversation`` as the FIRST user turn's content list."""+ seen = {}++ class _Child(_FakeChild):+ _delegate_images = [_png(tmp_path)]++ def run_conversation(self, user_message, **kw):+ seen["user_message"] = user_message+ return {"final_response": "ok", "completed": True}++ class _Parent:+ _current_task_id = None++ run = _ChildRun(_Child(), _Parent(), 0, "Describe it", None, None)+ with patch("tools.delegate_tool_child_run._create_isolated_worktree", return_value=None), \+ patch("agent.image_routing.decide_image_input_mode", return_value="native"):+ run.seed_workspace()+ result, failure, _ = run.await_child()+ assert failure is None and result["final_response"] == "ok"+ content = seen["user_message"]+ assert isinstance(content, list) and content[0]["type"] == "text"+ assert [p["type"] for p in content].count("image_url") == 1+ assert content[1]["image_url"]["url"].startswith("data:image/png;base64,")+++def test_images_advertised_per_task_only():+ item = DELEGATE_TASK_SCHEMA["parameters"]["properties"]["tasks"]["items"]+ assert item["properties"]["images"]["type"] == "array" and "images" not in item["required"]+ assert "images" not in DELEGATE_TASK_SCHEMA["parameters"]["properties"]diff --git a/tools/delegate_tool_child_run.py b/tools/delegate_tool_child_run.pyindex 0b5c6f92489..4870e9ad1e5 100644--- a/tools/delegate_tool_child_run.py+++ b/tools/delegate_tool_child_run.py@@ -566,7 +566,9 @@ def _build_child_goal_message(goal: str, images: List[str], child) -> Any:spawn — logged at warning since the caller asked for the images."""try:- urls = [s for s in images if _is_image_url(s)]+ # data: URLs ride as image parts only — their base64 never goes into the text hint or a text-mode goal.+ data_urls = [s for s in images if s.startswith("data:image/")]+ urls = [s for s in images if _is_image_url(s) and s not in data_urls]paths = [s for s in images if not _is_image_url(s)]from agent.image_routing import build_native_content_parts, decide_image_input_modecfg = None@@ -581,7 +583,11 @@ def _build_child_goal_message(goal: str, images: List[str], child) -> Any:parts, skipped = build_native_content_parts(goal, paths, urls)if skipped:logger.warning("delegate_task: skipped %d unreadable image(s) for subagent: %s", len(skipped), ", ".join(skipped[:3]))+ if data_urls:+ parts = (parts or [{"type": "text", "text": goal}]) + [{"type": "image_url", "image_url": {"url": u}} for u in data_urls]return parts if any(p.get("type") == "image_url" for p in parts) else goal+ if data_urls:+ logger.warning("delegate_task: %d inline data-URL image(s) dropped for a non-vision subagent", len(data_urls))hints: List[str] = []for p in paths:if os.path.isfile(p):diff --git a/website/docs/user-guide/features/delegation.md b/website/docs/user-guide/features/delegation.mdindex 0feb62d928a..51f7bb1121e 100644--- a/website/docs/user-guide/features/delegation.md+++ b/website/docs/user-guide/features/delegation.md@@ -104,7 +104,7 @@ The subagent receives a focused system prompt built from your goal and context,### Forwarding Images to a Subagent-Text context is not enough when the task is inherently visual — a screenshot the user sent, a design mock, a rendered chart. Each task accepts an optional `images` list (up to 8 entries; local file paths or `http(s)` URLs):+Text context is not enough when the task is inherently visual — a screenshot the user sent, a design mock, a rendered chart. Each task accepts an optional `images` list (up to 8 entries; local file paths, `http(s)` URLs or `data:image/...` URLs):```pythondelegate_task(tasks=[{@@ -117,7 +117,7 @@ delegate_task(tasks=[{Delivery follows the same routing as user-attached images (`agent.image_input_mode`):-- **Vision-capable child model** — the images arrive as native multimodal content on the child's first turn: local files are embedded as data URLs, remote URLs pass through for the provider to fetch. The child sees the actual pixels.+- **Vision-capable child model** — the images arrive as native multimodal content on the child's first turn: local files are embedded as data URLs (subject to the same read guard as every other file read), remote and `data:` URLs pass through verbatim. The child sees the actual pixels.- **Non-vision child model** — the goal gains `[Image attached at: <path>]` hint lines and the child is told to inspect them with `vision_analyze`.Forwarding is best-effort: unreadable paths are skipped with a log line, and any failure in the image plumbing falls back to the plain text goal — it can never break a spawn. Images are for things the child must *see*; put text file paths in `context` as usual.