Skip to content

The agent that grows with you

fix(desktop): stop blocking the image submit path on vision pre-analysis

Teknium56e5385e96c2
diff --git a/tests/tui_gateway/test_image_ref_message.py b/tests/tui_gateway/test_image_ref_message.py
new file mode 100644
index 00000000000..4a1cf95d812
--- /dev/null
+++ b/tests/tui_gateway/test_image_ref_message.py
@@ -0,0 +1,78 @@
+"""Desktop image submit path must never block on vision calls (#83291).
+
+The old ``_enrich_with_attached_images`` pre-analyzed every attached image
+with the auxiliary vision model *before* the turn was dispatched — serial
+blocking calls of 60-90s per large photo, silent failure swallowing, and an
+interrupt window that killed the turn with zero API calls. The replacement
+``_build_image_ref_message`` only references the image paths so the agent
+analyzes them in-loop with ``vision_analyze`` (the same shape as the
+``@folder:`` path, which was always fast).
+"""
+
+import time
+from unittest.mock import patch
+
+import pytest
+
+from tui_gateway.server import _build_image_ref_message
+
+
+def img(tmp_path):
+ p = tmp_path / "photo.jpg"
+ p.write_bytes(b"\xff\xd8\xff fake jpeg")
+ return p
+
+
+def test_never_calls_vision_on_submit_path(img):
+ """The whole point of the fix: zero vision traffic before dispatch."""
+
+ def _boom(*a, **k): # pragma: no cover - must never run
+ raise AssertionError("submit path called the vision tool")
+
+ with patch("tools.vision_tools.vision_analyze_tool", _boom):
+ out = _build_image_ref_message("what is this?", [str(img)])
+
+ assert "what is this?" in out
+ assert str(img) in out
+ assert "vision_analyze" in out
+
+
+def test_returns_instantly_for_many_images(tmp_path):
+ """No per-image network round-trips: 20 images in well under a second."""
+ paths = []
+ for i in range(20):
+ p = tmp_path / f"img{i}.png"
+ p.write_bytes(b"\x89PNG\r\n\x1a\n fake")
+ paths.append(str(p))
+
+ start = time.monotonic()
+ out = _build_image_ref_message("caption", paths)
+ elapsed = time.monotonic() - start
+
+ assert elapsed < 1.0
+ for p in paths:
+ assert p in out
+
+
+def test_missing_paths_skipped(tmp_path, img):
+ gone = tmp_path / "nope.png"
+ out = _build_image_ref_message("hi", [str(gone), str(img)])
+ assert str(gone) not in out
+ assert str(img) in out
+
+
+def test_text_preserved_and_trails_refs(img):
+ out = _build_image_ref_message("my caption", [str(img)])
+ assert out.index("vision_analyze") < out.index("my caption")
+
+
+def test_no_text_defaults_to_question_when_no_valid_images(tmp_path):
+ out = _build_image_ref_message("", [str(tmp_path / "missing.png")])
+ assert out == "What do you see in this image?"
+
+
+def test_no_text_with_image_yields_refs_only(img):
+ out = _build_image_ref_message("", [str(img)])
+ assert str(img) in out
+ assert out.strip().startswith("[The user attached an image")
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 5f86003dade..23b52665216 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -7049,35 +7049,33 @@ def _active_image_routing_identity(agent: Any) -> tuple[str, str]:
)
-def _enrich_with_attached_images(user_text: str, image_paths: list[str]) -> str:
- """Pre-analyze attached images via vision and prepend descriptions to user text."""
- import asyncio, json as _json
- from tools.vision_tools import vision_analyze_tool
-
- prompt = (
- "Describe everything visible in this image in thorough detail. "
- "Include any text, code, data, objects, people, layout, colors, "
- "and any other notable visual information."
- )
-
+def _build_image_ref_message(user_text: str, image_paths: list[str]) -> str:
+ """Reference attached images by path so the agent analyzes them in-loop.
+
+ This used to pre-analyze every image with the auxiliary vision model
+ *before* the turn was dispatched (``_enrich_with_attached_images``):
+ serial blocking calls on the submit path — 60-90s per large photo —
+ with failures silently swallowed and an interrupt during the window
+ killing the turn with zero API calls (#83291). It also prepended the
+ vision description to the first user message, poisoning session
+ auto-titles (#82339). The CLI never gates turn dispatch on vision
+ like this, which is why the same message was seconds there and
+ minutes on desktop.
+
+ Now the turn starts immediately. The agent examines each image itself
+ with ``vision_analyze`` — its own retries, visible tool progress —
+ exactly how the ``@folder:`` reference path already behaves, which
+ responds in seconds for the same images.
+ """
parts: list[str] = []
for path in image_paths:
p = Path(path)
if not p.exists():
continue
- hint = f"[You can examine it with vision_analyze using image_url: {p}]"
- try:
- r = _json.loads(
- asyncio.run(vision_analyze_tool(image_url=str(p), user_prompt=prompt))
- )
- desc = r.get("analysis", "") if r.get("success") else None
- parts.append(
- f"[The user attached an image:\n{desc}]\n{hint}"
- if desc
- else f"[The user attached an image but analysis failed.]\n{hint}"
- )
- except Exception:
- parts.append(f"[The user attached an image but analysis failed.]\n{hint}")
+ parts.append(
+ f"[The user attached an image: {p.name}]\n"
+ f"[Examine it with the vision_analyze tool using image_url: {p}]"
+ )
text = user_text or ""
prefix = "\n\n".join(parts)
@@ -7091,8 +7089,8 @@ def _build_persist_message_with_image_refs(user_text: str, image_paths: list[str
persisting to session history. Uses ``@image:<path>`` directives — the
format the desktop client (directive-text.tsx / HERMES_DIRECTIVE_RE)
actually parses and renders as an image — unlike
- ``_enrich_with_attached_images``, which embeds a vision description and
- an ``image_url:`` hint meant only for the model and must never be
+ ``_build_image_ref_message``, which embeds an
+ ``image_url:`` hint meant only for the model and must never be
persisted as-is (it silently breaks image rendering after a full
restart, and reorders image/text on live session-switch reconciliation).
@@ -10440,7 +10438,9 @@ def _run_prompt_submit(
# Decide image routing per-turn based on active provider/model.
# "native" → pass pixels to the main model as OpenAI-style content
# parts (adapters translate for Anthropic/Gemini/Bedrock/etc.).
- # "text" → pre-analyze with vision_analyze and prepend the text.
+ # "text" → reference the image paths in the message so the agent
+ # analyzes them in-loop with vision_analyze (never
+ # blocking the submit path on vision calls — #83291).
# See agent/image_routing.py for the full decision table.
run_message: Any = prompt
if images:
@@ -10484,15 +10484,15 @@ def _run_prompt_submit(
if any(p.get("type") == "image_url" for p in _parts):
run_message = _parts
else:
- run_message = _enrich_with_attached_images(prompt, images)
+ run_message = _build_image_ref_message(prompt, images)
except Exception as _img_exc:
print(
f"[tui_gateway] native attach failed, falling back to text: {_img_exc}",
file=sys.stderr,
)
- run_message = _enrich_with_attached_images(prompt, images)
+ run_message = _build_image_ref_message(prompt, images)
else:
- run_message = _enrich_with_attached_images(prompt, images)
+ run_message = _build_image_ref_message(prompt, images)
# Streaming TTS: voice-mode replies are spoken sentence-by-sentence
# as tokens arrive (CLI parity) instead of after the full turn.