Skip to content

The agent that grows with you

fix(gateway): widen computer-use media path repair to sibling surfaces

kshitijk4poorbb0d5503c2bf
diff --git a/cron/scheduler.py b/cron/scheduler.py
index e4498ad34fd..909954130cb 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -6270,6 +6270,25 @@ def run_job(
)
final_response = result.get("final_response", "") or ""
+ # Recover model-mangled computer_use screenshot paths before delivery
+ # media extraction (same repair as the gateway turn/background paths).
+ # Cron runs start a fresh conversation, so history_offset=0.
+ if final_response and "MEDIA:" in final_response:
+ try:
+ from gateway.media_repair import (
+ repair_explicit_computer_use_media_paths,
+ )
+
+ final_response = repair_explicit_computer_use_media_paths(
+ final_response,
+ result.get("messages", []),
+ )
+ except Exception:
+ logger.debug(
+ "Job '%s': computer_use media path repair failed",
+ job_name,
+ exc_info=True,
+ )
# Strip leaked placeholder text that upstream may inject on empty completions.
if final_response.strip() == "(No response generated)":
final_response = ""
diff --git a/gateway/media_repair.py b/gateway/media_repair.py
new file mode 100644
index 00000000000..a58389b946e
--- /dev/null
+++ b/gateway/media_repair.py
@@ -0,0 +1,189 @@
+"""Repair model-mangled ``computer_use`` screenshot paths in final responses.
+
+``computer_use`` persists a bounded screenshot into the Hermes image cache and
+tells the model its absolute path. Some models rewrite a Windows path into a
+POSIX-looking one (``C:\\Users\\Alice\\...`` -> ``/Users/Alice/...``) when
+emitting an explicit ``MEDIA:`` directive, so delivery-path validation rejects
+the nonexistent path and the attachment is dropped.
+
+The repair is deliberately narrow: it only rewrites paths inside a response
+that *already* carries an explicit ``MEDIA:`` directive, and only when the
+directive's generated ``computer_use_<uuid>`` basename exactly matches a
+canonical screenshot path returned by ``computer_use`` in the current turn.
+It never auto-attaches captures, and normal media path validation still runs
+after the repair.
+
+This lives in its own module (mirroring ``gateway/media_policy.py``) so every
+delivery surface — the messaging gateway's main turn path, gateway background
+tasks, and cron job delivery — shares one implementation.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from typing import Any, Dict, Iterator, List
+
+# Absolute-path prefix accepted for canonical capture paths: Windows drive
+# letter, POSIX root, or UNC share. Kept as a pattern string so the summary
+# regex below and the compiled prefix check stay in sync.
+_ABS_PATH_PREFIX_PATTERN = r"(?:[A-Za-z]:[/\\]|/|\\\\)"
+_ABS_PATH_PREFIX_RE = re.compile(r"^" + _ABS_PATH_PREFIX_PATTERN)
+
+_COMPUTER_USE_CAPTURE_BASENAME_RE = re.compile(
+ r"^computer_use_[0-9a-f]{32}\.(?:png|jpe?g)$",
+ re.IGNORECASE,
+)
+_COMPUTER_USE_CAPTURE_SUMMARY_RE = re.compile(
+ r"\(shareable screenshot saved to "
+ r"(?P<path>" + _ABS_PATH_PREFIX_PATTERN + r"[^\r\n]*?"
+ r"computer_use_[0-9a-f]{32}\.(?:png|jpe?g))\)",
+ re.IGNORECASE,
+)
+
+
+def tool_name_by_call_id(messages: List[Dict[str, Any]]) -> Dict[str, str]:
+ """Map assistant tool-call ids to tool names for the given messages."""
+ mapping: Dict[str, str] = {}
+ for msg in messages:
+ if msg.get("role") != "assistant":
+ continue
+ for call in msg.get("tool_calls") or []:
+ call_id = call.get("id") or call.get("call_id")
+ fn = call.get("function") or {}
+ name = str(fn.get("name") or call.get("name") or "")
+ if call_id and name:
+ mapping[str(call_id)] = name
+ return mapping
+
+
+def _computer_use_capture_basename(path: Any) -> str:
+ """Return a canonical capture basename for either path separator style."""
+ value = str(path or "").strip().strip("`\"'")
+ basename = re.split(r"[/\\]", value)[-1]
+ if _COMPUTER_USE_CAPTURE_BASENAME_RE.fullmatch(basename):
+ return basename.lower()
+ return ""
+
+
+def _iter_computer_use_capture_paths(content: Any) -> Iterator[str]:
+ """Yield persisted screenshot paths from computer_use result content.
+
+ The tool can return JSON, a multimodal content list, or a text fallback.
+ The latter two retain the canonical path in the human-readable summary
+ even though the multimodal envelope's ``meta`` dictionary is not stored in
+ the tool message.
+ """
+ if isinstance(content, str):
+ stripped = content.strip()
+ if stripped.startswith(("{", "[")):
+ # JSON-looking content: parse first, never regex-scan the raw
+ # text. JSON escaping doubles backslashes, so a summary-regex hit
+ # on the raw string would yield ``C:\\\\Users\\\\...`` — a path
+ # that exists nowhere. Fail closed on unparseable JSON (tool
+ # output truncation) rather than repair to a corrupted path.
+ try:
+ payload = json.loads(stripped)
+ except Exception:
+ return
+ if isinstance(payload, (dict, list)):
+ yield from _iter_computer_use_capture_paths(payload)
+ return
+ for match in _COMPUTER_USE_CAPTURE_SUMMARY_RE.finditer(content):
+ yield match.group("path").strip()
+ return
+
+ if isinstance(content, list):
+ for part in content:
+ yield from _iter_computer_use_capture_paths(part)
+ return
+
+ if not isinstance(content, dict):
+ return
+
+ screenshot_path = content.get("screenshot_path")
+ if isinstance(screenshot_path, str):
+ yield screenshot_path
+ meta = content.get("meta")
+ if isinstance(meta, dict) and isinstance(meta.get("screenshot_path"), str):
+ yield meta["screenshot_path"]
+ # Producer shapes (tools/computer_use/tool.py::_capture_response):
+ # "content"/"text" — multimodal envelope parts; "text_summary"/"summary" —
+ # the human-readable summary carrying the "(shareable screenshot saved
+ # to ...)" line.
+ for field in ("content", "text", "text_summary", "summary"):
+ nested = content.get(field)
+ if isinstance(nested, (str, dict, list)):
+ yield from _iter_computer_use_capture_paths(nested)
+
+
+def repair_explicit_computer_use_media_paths(
+ response: str,
+ messages: List[Dict[str, Any]],
+ history_offset: int = 0,
+) -> str:
+ """Recover model-mangled paths for explicitly requested screenshots.
+
+ Repair only an already-explicit ``MEDIA:`` directive whose unique
+ generated basename matches a canonical screenshot path from this turn.
+ This does not auto-attach ordinary computer-use captures, and normal
+ media path validation still runs after the repair.
+ """
+ if "MEDIA:" not in response:
+ return response
+
+ if history_offset and len(messages) >= history_offset:
+ turn_messages = messages[history_offset:]
+ elif history_offset:
+ # Compression can invalidate the original slice boundary. Recover the
+ # current turn from its last user message; fail closed if none
+ # remains. (Deliberately narrower than the scan-everything fallback
+ # in gateway/run.py::_collect_auto_append_media_tags — that helper
+ # decides whether to ATTACH, this one only rewrites paths the model
+ # already explicitly emitted.)
+ last_user = next(
+ (
+ index
+ for index in range(len(messages) - 1, -1, -1)
+ if messages[index].get("role") == "user"
+ ),
+ None,
+ )
+ turn_messages = messages[last_user:] if last_user is not None else []
+ else:
+ turn_messages = messages
+
+ call_id_names = tool_name_by_call_id(turn_messages)
+
+ canonical_by_basename: Dict[str, str] = {}
+ for msg in turn_messages:
+ if msg.get("role") not in {"tool", "function"}:
+ continue
+ call_id = str(msg.get("tool_call_id") or msg.get("call_id") or "")
+ tool_name = str(
+ msg.get("name")
+ or msg.get("tool_name")
+ or call_id_names.get(call_id)
+ or ""
+ )
+ if tool_name != "computer_use":
+ continue
+ for path in _iter_computer_use_capture_paths(msg.get("content")):
+ basename = _computer_use_capture_basename(path)
+ if basename and _ABS_PATH_PREFIX_RE.match(path):
+ canonical_by_basename[basename] = path
+
+ if not canonical_by_basename:
+ return response
+
+ from gateway.platforms.base import BasePlatformAdapter
+
+ media_files, _ = BasePlatformAdapter.extract_media(response)
+ repaired = response
+ for emitted_path, _is_voice in media_files:
+ canonical = canonical_by_basename.get(
+ _computer_use_capture_basename(emitted_path)
+ )
+ if canonical and emitted_path != canonical:
+ repaired = repaired.replace(emitted_path, canonical)
+ return repaired
diff --git a/gateway/run.py b/gateway/run.py
index c9bb0f75361..f3fb48bbccf 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -1823,146 +1823,15 @@ _TOOL_MEDIA_RE = re.compile(
)
-_COMPUTER_USE_CAPTURE_BASENAME_RE = re.compile(
- r"^computer_use_[0-9a-f]{32}\.(?:png|jpe?g)$",
- re.IGNORECASE,
-)
-_COMPUTER_USE_CAPTURE_SUMMARY_RE = re.compile(
- r"\(shareable screenshot saved to "
- r"(?P<path>(?:[A-Za-z]:[/\\]|/|\\\\)[^\r\n]*?"
- r"computer_use_[0-9a-f]{32}\.(?:png|jpe?g))\)",
- re.IGNORECASE,
+# Shared with cron delivery and gateway background tasks — the repair must
+# run on every surface that feeds a final response into media extraction.
+# Re-exported under the historical private name for tests and callers.
+from gateway.media_repair import ( # noqa: E402
+ repair_explicit_computer_use_media_paths as _repair_explicit_computer_use_media_paths,
+ tool_name_by_call_id as _tool_name_by_call_id,
)
-def _computer_use_capture_basename(path: Any) -> str:
- """Return a canonical capture basename for either path separator style."""
- value = str(path or "").strip().strip("`\"'")
- basename = re.split(r"[/\\]", value)[-1]
- if _COMPUTER_USE_CAPTURE_BASENAME_RE.fullmatch(basename):
- return basename.lower()
- return ""
-
-
-def _iter_computer_use_capture_paths(content: Any):
- """Yield persisted screenshot paths from computer_use result content.
-
- The tool can return JSON, a multimodal content list, or a text fallback.
- The latter two retain the canonical path in the human-readable summary
- even though the multimodal envelope's ``meta`` dictionary is not stored in
- the tool message.
- """
- if isinstance(content, str):
- for match in _COMPUTER_USE_CAPTURE_SUMMARY_RE.finditer(content):
- yield match.group("path").strip()
- stripped = content.strip()
- if stripped.startswith(("{", "[")):
- try:
- payload = json.loads(stripped)
- except Exception:
- payload = None
- if isinstance(payload, (dict, list)):
- yield from _iter_computer_use_capture_paths(payload)
- return
-
- if isinstance(content, list):
- for part in content:
- yield from _iter_computer_use_capture_paths(part)
- return
-
- if not isinstance(content, dict):
- return
-
- screenshot_path = content.get("screenshot_path")
- if isinstance(screenshot_path, str):
- yield screenshot_path
- meta = content.get("meta")
- if isinstance(meta, dict) and isinstance(meta.get("screenshot_path"), str):
- yield meta["screenshot_path"]
- for field in ("content", "text", "text_summary", "summary"):
- nested = content.get(field)
- if isinstance(nested, (str, dict, list)):
- yield from _iter_computer_use_capture_paths(nested)
-
-
-def _repair_explicit_computer_use_media_paths(
- response: str,
- messages: List[Dict[str, Any]],
- history_offset: int = 0,
-) -> str:
- """Recover model-mangled paths for explicitly requested screenshots.
-
- ``computer_use`` persists a bounded screenshot and gives its absolute path
- to the model. Some models rewrite a Windows path into a POSIX-looking path
- before emitting ``MEDIA:``, which makes the gateway reject the nonexistent
- path. Repair only an already-explicit directive whose unique generated
- basename matches a canonical screenshot path from this turn. This does not
- auto-attach ordinary computer-use captures, and normal media path
- validation still runs after the repair.
- """
- if "MEDIA:" not in response:
- return response
-
- if history_offset and len(messages) >= history_offset:
- turn_messages = messages[history_offset:]
- elif history_offset:
- # Compression can invalidate the original slice boundary. Recover the
- # current turn from its last user message; fail closed if none remains.
- last_user = next(
- (
- index
- for index in range(len(messages) - 1, -1, -1)
- if messages[index].get("role") == "user"
- ),
- None,
- )
- turn_messages = messages[last_user:] if last_user is not None else []
- else:
- turn_messages = messages
-
- tool_name_by_call_id: Dict[str, str] = {}
- for msg in turn_messages:
- if msg.get("role") != "assistant":
- continue
- for call in msg.get("tool_calls") or []:
- call_id = call.get("id") or call.get("call_id")
- fn = call.get("function") or {}
- name = str(fn.get("name") or call.get("name") or "")
- if call_id and name:
- tool_name_by_call_id[str(call_id)] = name
-
- canonical_by_basename: Dict[str, str] = {}
- for msg in turn_messages:
- if msg.get("role") not in {"tool", "function"}:
- continue
- call_id = str(msg.get("tool_call_id") or msg.get("call_id") or "")
- tool_name = str(
- msg.get("name")
- or msg.get("tool_name")
- or tool_name_by_call_id.get(call_id)
- or ""
- )
- if tool_name != "computer_use":
- continue
- for path in _iter_computer_use_capture_paths(msg.get("content")):
- basename = _computer_use_capture_basename(path)
- if basename and re.match(r"^(?:[A-Za-z]:[/\\]|/|\\\\)", path):
- canonical_by_basename[basename] = path
-
- if not canonical_by_basename:
- return response
-
- media_files, _ = BasePlatformAdapter.extract_media(response)
- repaired = response
- for emitted_path, _is_voice in media_files:
- canonical = canonical_by_basename.get(
- _computer_use_capture_basename(emitted_path)
- )
- if canonical and emitted_path != canonical:
- repaired = repaired.replace(emitted_path, canonical)
- return repaired
-
-
def _collect_auto_append_media_tags(
messages: List[Dict[str, Any]],
history_offset: int = 0,
@@ -1994,16 +1863,7 @@ def _collect_auto_append_media_tags(
else:
new_messages = messages
- tool_name_by_call_id: Dict[str, str] = {}
- for msg in new_messages:
- if msg.get("role") != "assistant":
- continue
- for call in msg.get("tool_calls") or []:
- call_id = call.get("id") or call.get("call_id")
- fn = call.get("function") or {}
- name = str(fn.get("name") or call.get("name") or "")
- if call_id and name:
- tool_name_by_call_id[str(call_id)] = name
+ tool_name_by_call_id = _tool_name_by_call_id(new_messages)
media_tags: List[str] = []
has_voice_directive = False
@@ -2058,7 +1918,7 @@ def _collect_history_media_paths(agent_history: List[Dict[str, Any]]) -> set:
shape caused repeated delivery when the model echoed a previous MEDIA tag.
"""
paths: set = set()
- tool_name_by_call_id: Dict[str, str] = {}
+ tool_name_by_call_id = _tool_name_by_call_id(agent_history)
def _add_text_media_paths(content: str) -> None:
for match in _TOOL_MEDIA_RE.finditer(content):
@@ -2072,14 +1932,6 @@ def _collect_history_media_paths(agent_history: List[Dict[str, Any]]) -> set:
media_files, _ = BasePlatformAdapter.extract_media(content)
paths.update(path for path, _is_voice in media_files)
- for msg in agent_history:
- if msg.get("role") == "assistant":
- for call in msg.get("tool_calls") or []:
- cid = call.get("id") or call.get("call_id")
- fn = call.get("function") or {}
- name = str(fn.get("name") or call.get("name") or "")
- if cid and name:
- tool_name_by_call_id[str(cid)] = name
for msg in agent_history:
role = msg.get("role")
if role == "assistant":
@@ -22934,6 +22786,15 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
if not response and result and result.get("error"):
response = f"Error: {result['error']}"
+ # Background tasks start a fresh conversation (no prior history),
+ # so history_offset=0: every message in the run belongs to this
+ # turn. Mirrors the repair on the main turn path.
+ if response and result:
+ response = _repair_explicit_computer_use_media_paths(
+ response,
+ result.get("messages", []),
+ )
+
# Extract media files from the response
if response:
media_files, response = adapter.extract_media(response)
diff --git a/tests/gateway/test_media_extraction.py b/tests/gateway/test_media_extraction.py
index b651d4ebe60..6a50965718e 100644
--- a/tests/gateway/test_media_extraction.py
+++ b/tests/gateway/test_media_extraction.py
@@ -214,6 +214,73 @@ class TestMediaExtraction:
assert repaired == response
+ def test_malformed_json_result_fails_closed(self):
+ """Truncated JSON must not repair to a doubled-backslash artifact.
+
+ JSON escaping doubles backslashes; regex-scanning the raw string
+ would yield ``C:\\\\Users\\\\...`` — a path that exists nowhere. When
+ json.loads fails, the helper must yield nothing rather than rewrite
+ the response to a corrupted path.
+ """
+ import json as _json
+
+ from gateway.run import _repair_explicit_computer_use_media_paths
+
+ capture_name = "computer_use_dddddddddddddddddddddddddddddddd.png"
+ canonical = rf"C:\Users\Alice\AppData\Local\hermes\cache\images\{capture_name}"
+ payload = _json.dumps(
+ {
+ "summary": f"capture\n (shareable screenshot saved to {canonical})",
+ "screenshot_path": canonical,
+ }
+ )
+ truncated = payload[:-5] # starts with '{' but no longer parses
+ response = f"MEDIA:/Users/Alice/AppData/Local/hermes/cache/images/{capture_name}"
+ messages = [
+ {"role": "tool", "name": "computer_use", "content": truncated},
+ ]
+
+ assert (
+ _repair_explicit_computer_use_media_paths(response, messages)
+ == response
+ )
+
+ def test_compression_fallback_slices_from_last_user_message(self):
+ """When compression shrinks messages below history_offset, the repair
+ recovers the current turn from the last user message — and fails
+ closed (no rewrite) when no user message remains."""
+ import json as _json
+
+ from gateway.run import _repair_explicit_computer_use_media_paths
+
+ capture_name = "computer_use_eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee.png"
+ canonical = rf"C:\cache\images\{capture_name}"
+ response = f"MEDIA:/cache/images/{capture_name}"
+ current_turn = [
+ {"role": "user", "content": "Send the screenshot."},
+ {
+ "role": "tool",
+ "name": "computer_use",
+ "content": _json.dumps({"screenshot_path": canonical}),
+ },
+ ]
+
+ # history_offset larger than the (compressed) message list forces the
+ # fallback branch; the last-user slice still finds this turn's result.
+ repaired = _repair_explicit_computer_use_media_paths(
+ response, current_turn, history_offset=10
+ )
+ assert repaired == f"MEDIA:{canonical}"
+
+ # No user message at all -> fail closed, nothing rewritten.
+ no_user = [current_turn[1]]
+ assert (
+ _repair_explicit_computer_use_media_paths(
+ response, no_user, history_offset=10
+ )
+ == response
+ )
+
def test_gateway_auto_append_ignores_media_examples_in_skill_docs(self):
"""Skill/documentation examples must not be appended as real attachments."""
from gateway.run import _collect_auto_append_media_tags