The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(discord): preserve links in truncated tool previews
Coffee☕️df9e039d2da8
diff --git a/agent/display.py b/agent/display.pyindex 3da6e2f24ec..03e4bfe6278 100644--- a/agent/display.py+++ b/agent/display.py@@ -14,6 +14,7 @@ from dataclasses import dataclass, fieldfrom difflib import unified_difffrom pathlib import Pathfrom typing import Any+from urllib.parse import urlsplitfrom utils import safe_json_loadsfrom agent.redact import redact_sensitive_text@@ -556,6 +557,32 @@ def build_tool_preview(tool_name: str, args: dict, max_len: int | None = None) -return preview+def get_tool_preview_url(+ tool_name: str,+ args: dict | None,+ *,+ fallback: str | None = None,+) -> str | None:+ """Return the uncapped HTTP(S) URL represented by a tool preview.++ Rebuild the preview from the tool's primary display argument so callers+ can recover information lost to an earlier display-length cap. ``fallback``+ covers callback paths that carry a preview but no argument dictionary.+ """+ expanded = build_tool_preview(tool_name, args, max_len=0)+ for value in (expanded, fallback):+ candidate = _display_url(value)+ if not candidate:+ continue+ try:+ parsed = urlsplit(candidate)+ except ValueError:+ continue+ if parsed.scheme.lower() in {"http", "https"} and parsed.netloc:+ return candidate+ return None++# =========================================================================# Friendly tool labels (human-phrased verbs for built-in tools)#@@ -1507,4 +1534,3 @@ def get_cute_tool_message(# Honcho session line (one-liner with clickable OSC 8 hyperlink)# =========================================================================-diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex de60322718b..9b88e7c1c67 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -3095,12 +3095,38 @@ class BasePlatformAdapter(ABC):# progress bubbles compact — they persist as permanent messages).preview = event.previewif preview:+ full_preview = previewcap = preview_max_len if preview_max_len > 0 else 40if len(preview) > cap:preview = preview[:cap - 3] + "..."+ preview = self.format_tool_preview(+ preview,+ full_preview=full_preview,+ tool_name=event.tool_name,+ args=event.args,+ )return f"{emoji} {event.tool_name}: \"{preview}\""return f"{emoji} {event.tool_name}..."+ def format_tool_preview(+ self,+ preview: str,+ *,+ full_preview: Optional[str] = None,+ tool_name: Optional[str] = None,+ args: Optional[Dict[str, Any]] = None,+ ) -> str:+ """Apply platform-native formatting to a compact tool preview.++ The gateway calls this after imposing its display-length cap, while+ still supplying the original preview and tool arguments. Most+ platforms should preserve the compact text unchanged. Markdown+ adapters may use the extra context to retain information that would+ otherwise be lost during truncation (for example, Discord keeps a+ truncated URL label linked to its full destination).+ """+ return preview+@propertydef has_fatal_error(self) -> bool:return self._fatal_error_message is not Nonediff --git a/gateway/run.py b/gateway/run.pyindex 9e6b76ceb2c..15e1ffad6fd 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -3782,8 +3782,16 @@ class TurnRunner:)_pl = get_tool_preview_max_len()_cap = _pl if _pl > 0 else 40+ _full_preview = previewif len(preview) > _cap:preview = preview[:_cap - 3] + "..."+ if _progress_adapter is not None:+ preview = _progress_adapter.format_tool_preview(+ preview,+ full_preview=_full_preview,+ tool_name=tool_name,+ args=args,+ )# Friendly labels: render a human-phrased line for built-in# tools ("🔍 Searching the web for ...") by prefixing the verb# onto the preview the callback already computed (so thediff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.pyindex 99e0f9a2f57..f044d192720 100644--- a/plugins/platforms/discord/adapter.py+++ b/plugins/platforms/discord/adapter.py@@ -26,11 +26,12 @@ import timefrom collections import defaultdictfrom contextlib import suppressfrom typing import Callable, Dict, List, Optional, Any, Tuple-from urllib.parse import urljoin+from urllib.parse import quote, urljoinfrom agent.async_utils import (consume_detached_task_result as _consume_background_task_result,)+from agent.display import get_tool_preview_urllogger = logging.getLogger(__name__)@@ -97,7 +98,6 @@ _DISCORD_NONCONVERSATIONAL_HISTORY_MESSAGE_PATTERNS = (),re.compile(r"^\s*♻️?\s+Gateway\s+(?:restarted successfully|online\b)[\s\S]*$", re.IGNORECASE),)-try:import discordfrom discord import Message as DiscordMessage, Intents@@ -977,6 +977,42 @@ class DiscordAdapter(BasePlatformAdapter):PLAYBACK_TIMEOUT = 120PLAYBACK_TIMEOUT_PADDING = 30+ def format_tool_preview(+ self,+ preview: str,+ *,+ full_preview: Optional[str] = None,+ tool_name: Optional[str] = None,+ args: Optional[Dict[str, Any]] = None,+ ) -> str:+ """Keep a truncated URL preview clickable in Discord markdown."""+ if preview.endswith("..."):+ visible_prefix = preview[:-3]+ elif preview.endswith(_DISCORD_ELLIPSIS):+ visible_prefix = preview[:-1]+ else:+ return preview++ destination = get_tool_preview_url(+ tool_name or "",+ args,+ fallback=full_preview,+ )+ if (+ not destination+ or destination == preview+ or not destination.startswith(visible_prefix)+ ):+ return preview++ # Escape the label's link delimiters and URL-encode characters that+ # can prematurely terminate Discord's markdown destination.+ label = (+ preview.replace("\\", "\\\\").replace("[", "\\[").replace("]", "\\]")+ )+ href = quote(destination, safe=":/?#[]@!$&'*+,;=%")+ return f"[{label}]({href})"+def __init__(self, config: PlatformConfig):super().__init__(config, Platform.DISCORD)self._client: Optional[commands.Bot] = Nonediff --git a/tests/agent/test_display.py b/tests/agent/test_display.pyindex dfb839d6132..4896108d56d 100644--- a/tests/agent/test_display.py+++ b/tests/agent/test_display.py@@ -10,6 +10,7 @@ from agent.display import (capture_local_edit_snapshot,extract_edit_diff,get_cute_tool_message,+ get_tool_preview_url,redact_tool_args_for_display,set_tool_preview_max_len,_render_inline_unified_diff,@@ -106,6 +107,25 @@ class TestBuildToolPreview:assert build_tool_preview("terminal", []) is None+class TestGetToolPreviewUrl:+ def test_recovers_uncapped_web_extract_url(self):+ url = "https://example.com/a/very/long/path/to/a/page"+ set_tool_preview_max_len(20)++ assert get_tool_preview_url("web_extract", {"urls": [url]}) == url++ def test_uses_callback_preview_when_args_are_missing(self):+ url = "https://example.com/page"++ assert get_tool_preview_url("browser_navigate", None, fallback=url) == url++ def test_rejects_non_url_preview(self):+ assert get_tool_preview_url(+ "web_search",+ {"query": "how to parse a URL"},+ ) is None++class TestCuteToolMessagePreviewLength:@@ -275,4 +295,3 @@ class TestBuildStatusPhrase:assert build_status_phrase("terminal", {"command": "ls"}) is Nonefinally:set_friendly_tool_labels(True)-diff --git a/tests/gateway/test_discord_format.py b/tests/gateway/test_discord_format.pyindex 112678d0c76..fbeb2ed1b27 100644--- a/tests/gateway/test_discord_format.py+++ b/tests/gateway/test_discord_format.py@@ -44,3 +44,73 @@ class TestDiscordFormatMessage:assert "|---" not in out+class TestDiscordToolPreviewFormatting:+ def test_truncated_url_keeps_full_click_target(self):+ adapter = _make_discord_adapter()+ url = "https://hermes-agent.nousresearch.com/docs/gateway/discord/tool-progress"+ visible = "https://hermes-agent.nousresearch..."++ out = adapter.format_tool_preview(+ visible,+ full_preview=url,+ tool_name="web_extract",+ args={"urls": [url]},+ )++ assert out == f"[{visible}]({url})"++ def test_structured_tool_event_uses_clickable_truncated_url(self):+ from gateway.stream_events import ToolCallChunk++ adapter = _make_discord_adapter()+ url = "https://hermes-agent.nousresearch.com/docs/gateway/discord/tool-progress"+ visible = url[:37] + "..."++ out = adapter.format_tool_event(+ ToolCallChunk("web_extract", preview=url, args={"urls": [url]}),+ mode="all",+ preview_max_len=40,+ )++ assert out is not None+ assert f"[{visible}]({url})" in out++ def test_url_already_shortened_upstream_uses_full_url_from_args(self):+ adapter = _make_discord_adapter()+ url = "https://example.com/a/very/long/path/to/a/page"+ visible = "https://example.com/a/very..."++ out = adapter.format_tool_preview(+ visible,+ full_preview=visible,+ tool_name="browser_navigate",+ args={"url": url},+ )++ assert out == f"[{visible}]({url})"++ def test_untruncated_url_remains_plain(self):+ adapter = _make_discord_adapter()+ url = "https://example.com/page"++ out = adapter.format_tool_preview(+ url,+ full_preview=url,+ tool_name="browser_navigate",+ args={"url": url},+ )++ assert out == url++ def test_truncated_non_url_remains_plain(self):+ adapter = _make_discord_adapter()+ visible = "a long search query that was trunc..."++ out = adapter.format_tool_preview(+ visible,+ full_preview="a long search query that was truncated for display",+ tool_name="web_search",+ args={"query": "a long search query that was truncated for display"},+ )++ assert out == visiblediff --git a/tests/gateway/test_run_progress_topics.py b/tests/gateway/test_run_progress_topics.pyindex 1cd5da9e88c..f26a2d1187d 100644--- a/tests/gateway/test_run_progress_topics.py+++ b/tests/gateway/test_run_progress_topics.py@@ -59,6 +59,18 @@ class ProgressCaptureAdapter(BasePlatformAdapter):return {"id": chat_id}+class DiscordProgressCaptureAdapter(ProgressCaptureAdapter):+ """Capture sends while exercising Discord's real preview formatter."""++ def __init__(self):+ super().__init__(platform=Platform.DISCORD)++ def format_tool_preview(self, preview, **kwargs):+ from plugins.platforms.discord.adapter import DiscordAdapter++ return DiscordAdapter.format_tool_preview(self, preview, **kwargs)++class SmallLimitProgressAdapter(ProgressCaptureAdapter):"""Adapter with a tiny platform limit to exercise progress rollover."""@@ -239,6 +251,28 @@ class LongPreviewAgent:}+class UrlPreviewAgent:+ URL = "https://hermes-agent.nousresearch.com/docs/gateway/discord/tool-progress"++ def __init__(self, **kwargs):+ self.tool_progress_callback = kwargs.get("tool_progress_callback")+ self.tools = []++ def run_conversation(self, message, conversation_history=None, task_id=None):+ self.tool_progress_callback(+ "tool.started",+ "web_extract",+ self.URL,+ {"urls": [self.URL]},+ )+ time.sleep(0.35)+ return {+ "final_response": "done",+ "messages": [],+ "api_calls": 1,+ }++class DelayedProgressAgent:def __init__(self, **kwargs):self.tool_progress_callback = kwargs.get("tool_progress_callback")@@ -493,6 +527,58 @@ def test_all_mode_respects_custom_preview_length(monkeypatch, tmp_path):assert len(preview_text) <= 120, f"Preview too long ({len(preview_text)}): {preview_text}"+def test_discord_truncated_tool_url_links_to_full_destination(monkeypatch, tmp_path):+ """The real gateway path must retain the URL beyond its visible cap."""+ import yaml++ monkeypatch.setenv("HERMES_TOOL_PROGRESS_MODE", "all")++ fake_dotenv = types.ModuleType("dotenv")+ fake_dotenv.load_dotenv = lambda *args, **kwargs: None+ monkeypatch.setitem(sys.modules, "dotenv", fake_dotenv)++ fake_run_agent = types.ModuleType("run_agent")+ fake_run_agent.AIAgent = UrlPreviewAgent+ monkeypatch.setitem(sys.modules, "run_agent", fake_run_agent)++ (tmp_path / "config.yaml").write_text(+ yaml.dump({"display": {"tool_preview_length": 0}}),+ encoding="utf-8",+ )++ adapter = DiscordProgressCaptureAdapter()+ runner = _make_runner(adapter)+ gateway_run = importlib.import_module("gateway.run")+ monkeypatch.setattr(gateway_run, "_hermes_home", tmp_path)+ monkeypatch.setattr(+ gateway_run,+ "_resolve_runtime_agent_kwargs",+ lambda: {"api_key": "***"},+ )++ source = SessionSource(+ platform=Platform.DISCORD,+ chat_id="12345",+ chat_type="dm",+ thread_id=None,+ )+ result = asyncio.get_event_loop().run_until_complete(+ runner._run_agent(+ message="hello",+ context_prompt="",+ history=[],+ source=source,+ session_id="sess-discord-url",+ session_key="agent:main:discord:dm:12345",+ )+ )++ assert result["final_response"] == "done"+ assert adapter.sent+ visible = UrlPreviewAgent.URL[:37] + "..."+ assert f"[{visible}]({UrlPreviewAgent.URL})" in adapter.sent[0]["content"]++class CommentaryAgent:def __init__(self, **kwargs):self.tool_progress_callback = kwargs.get("tool_progress_callback")@@ -1316,5 +1402,3 @@ class TestSlackReplyInThreadProgressRouting:event_message_id="1700000000.000100",reply_in_thread=False,) is None--