Skip to content

Agent Zero AI framework

Task 1: Preserve Sanitized WebSocket Attachment Names in Replay Metadata

TerminallyLazy921a390c1418
diff --git a/plugins/_a0_connector/AGENTS.md b/plugins/_a0_connector/AGENTS.md
index 26404965d..a2d4cca8a 100644
--- a/plugins/_a0_connector/AGENTS.md
+++ b/plugins/_a0_connector/AGENTS.md
@@ -59,6 +59,7 @@
- The protected v1 `agents_list` response uses the shared agent presentation
catalog rather than applying connector-specific visibility rules.
- Computer Use receipts describe transport success unless the connector returns explicit effect evidence. Linux target-bound typing requires a verified active/focused `window_id`; window activation uses focus, never a press action on an application or window node. Do not retry an identical failed Computer Use call.
+- Accepted WebSocket user-message replay metadata may include attachment basenames only; strip paths, query strings, fragments, and bytes before logging them in `kvps`.
## Work Guidance
diff --git a/plugins/_a0_connector/api/ws_connector.py b/plugins/_a0_connector/api/ws_connector.py
index 148ef5ef1..5c3a16925 100644
--- a/plugins/_a0_connector/api/ws_connector.py
+++ b/plugins/_a0_connector/api/ws_connector.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING, Any, ClassVar
+from urllib.parse import urlsplit
from helpers.print_style import PrintStyle
from helpers.ws import WsHandler
@@ -75,6 +76,22 @@ _TAIL_HISTORY_PAGE_SIZE = 100
_LIVE_STREAM_PAGE_SIZE = 100
+def _attachment_log_metadata(attachments: list[str]) -> dict[str, list[str]]:
+ names: list[str] = []
+ for attachment in attachments:
+ normalized = str(attachment or "").strip().replace("\\", "/")
+ if not normalized:
+ continue
+ parsed = urlsplit(normalized)
+ path = parsed.path if parsed.scheme else normalized.split("?", 1)[0].split("#", 1)[0]
+ if path.endswith("/"):
+ continue
+ name = path.rstrip("/").rsplit("/", 1)[-1]
+ if name and name not in {".", ".."}:
+ names.append(name)
+ return {"attachments": names} if names else {}
+
+
class WsConnector(WsHandler):
_streaming_tasks: ClassVar[dict[tuple[str, str], asyncio.Task[None]]] = {}
@@ -468,7 +485,7 @@ class WsConnector(WsHandler):
type="user",
heading="",
content=message,
- kvps={},
+ kvps=_attachment_log_metadata(attachments),
id=message_id,
)
diff --git a/tests/test_a0_connector_attachment_metadata.py b/tests/test_a0_connector_attachment_metadata.py
new file mode 100644
index 000000000..73a628fcc
--- /dev/null
+++ b/tests/test_a0_connector_attachment_metadata.py
@@ -0,0 +1,165 @@
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from helpers.ws_manager import WsResult
+from plugins._a0_connector.api import ws_connector as ws_module
+from plugins._a0_connector.api.ws_connector import (
+ WsConnector,
+ _attachment_log_metadata,
+)
+from plugins._a0_connector.helpers.event_bridge import log_entry_to_connector_event
+
+
+def test_attachment_log_metadata_keeps_only_safe_basenames() -> None:
+ assert _attachment_log_metadata(
+ [
+ "/a0/usr/uploads/scan.png",
+ r"C:\\Users\\person\\result.jpg",
+ "https://agent.test/api/image_get?path=/a0/usr/uploads/chart.webp&token=secret#view",
+ "/a0/usr/uploads/",
+ "",
+ ]
+ ) == {
+ "attachments": ["scan.png", "result.jpg", "image_get"]
+ }
+
+
+def test_attachment_log_metadata_omits_empty_metadata() -> None:
+ assert _attachment_log_metadata([]) == {}
+ assert _attachment_log_metadata(["", "/"]) == {}
+
+
+class RecordingLog:
+ def __init__(self) -> None:
+ self.calls: list[dict[str, object]] = []
+
+ def log(self, **kwargs: object) -> None:
+ self.calls.append(dict(kwargs))
+
+
+async def test_websocket_attachment_names_reach_replayed_user_event(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ log = RecordingLog()
+ context = SimpleNamespace(log=log)
+ handler = WsConnector(None, None)
+ monkeypatch.setattr(
+ handler,
+ "_resolve_context",
+ AsyncMock(return_value=(context, "ctx-1")),
+ )
+ monkeypatch.setattr(
+ ws_module,
+ "subscribed_contexts_for_sid",
+ lambda sid: {"ctx-1"} if sid == "sid-cli" else set(),
+ )
+
+ scheduled: list[bool] = []
+
+ def close_scheduled(coroutine: object) -> SimpleNamespace:
+ close = getattr(coroutine, "close")
+ close()
+ scheduled.append(True)
+ return SimpleNamespace()
+
+ monkeypatch.setattr(asyncio, "create_task", close_scheduled)
+
+ result = await handler._handle_send_message(
+ {
+ "context_id": "ctx-1",
+ "message": "Review these",
+ "attachments": [
+ "/a0/usr/uploads/scan.png",
+ "/a0/usr/uploads/result.jpg",
+ ],
+ "client_message_id": "client-1",
+ },
+ "sid-cli",
+ )
+
+ assert result == {
+ "context_id": "ctx-1",
+ "status": "accepted",
+ "client_message_id": "client-1",
+ }
+ assert scheduled == [True]
+ assert log.calls == [
+ {
+ "type": "user",
+ "heading": "",
+ "content": "Review these",
+ "kvps": {"attachments": ["scan.png", "result.jpg"]},
+ "id": "client-1",
+ }
+ ]
+
+ replayed = log_entry_to_connector_event(
+ {"no": 0, **log.calls[0]},
+ "ctx-1",
+ )
+ assert replayed["event"] == "user_message"
+ assert replayed["data"]["meta"] == {
+ "attachments": ["scan.png", "result.jpg"]
+ }
+
+
+async def test_websocket_text_only_message_keeps_empty_kvps(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ log = RecordingLog()
+ context = SimpleNamespace(log=log)
+ handler = WsConnector(None, None)
+ monkeypatch.setattr(
+ handler,
+ "_resolve_context",
+ AsyncMock(return_value=(context, "ctx-1")),
+ )
+ monkeypatch.setattr(
+ ws_module,
+ "subscribed_contexts_for_sid",
+ lambda sid: {"ctx-1"} if sid == "sid-cli" else set(),
+ )
+
+ def close_scheduled(coroutine: object) -> SimpleNamespace:
+ getattr(coroutine, "close")()
+ return SimpleNamespace()
+
+ monkeypatch.setattr(asyncio, "create_task", close_scheduled)
+ await handler._handle_send_message(
+ {"context_id": "ctx-1", "message": "Text only"},
+ "sid-cli",
+ )
+ assert log.calls[0]["kvps"] == {}
+
+
+ ("payload", "code"),
+ [
+ (
+ {
+ "message": "image",
+ "attachments": [{"path": "data:image/png;base64,AAAA"}],
+ },
+ "INVALID_ATTACHMENTS",
+ ),
+ ({"message": "", "attachments": []}, "MISSING_MESSAGE"),
+ ],
+)
+async def test_websocket_rejected_attachments_do_not_reach_context(
+ payload: dict[str, object],
+ code: str,
+) -> None:
+ handler = WsConnector(None, None)
+ result = await handler.process("connector_send_message", payload, "sid-cli")
+ assert isinstance(result, WsResult)
+ rendered = result.as_result(handler_id="test", fallback_correlation_id=None)
+ assert rendered["ok"] is False
+ assert rendered["error"]["code"] == code