Skip to content
35 changes: 31 additions & 4 deletions openhands-sdk/openhands/sdk/agent/acp_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
from openhands.sdk.secret import SecretSource
from openhands.sdk.tool import Tool # noqa: TC002
from openhands.sdk.tool.builtins.finish import FinishAction, FinishObservation
from openhands.sdk.utils import maybe_truncate


logger = get_logger(__name__)
Expand Down Expand Up @@ -97,6 +98,10 @@
# upstream model 500s, and transient infrastructure errors.
_RETRIABLE_SERVER_ERROR_CODES: frozenset[int] = frozenset({-32603})

# Maximum characters for ACP tool call content — matches MAX_CMD_OUTPUT_SIZE
# used by the terminal tool and the default max_message_chars in LLM config.
MAX_ACP_CONTENT_CHARS: int = 30_000

# Limit for asyncio.StreamReader buffers used by the ACP subprocess pipes.
# The default (64 KiB) is too small for session_update notifications that
# carry large tool-call outputs (e.g. file contents, test results). When
Expand Down Expand Up @@ -276,9 +281,26 @@ def _serialize_tool_content(content: list[Any] | None) -> list[dict[str, Any]] |
"""Serialize ACP tool call content blocks to plain dicts for JSON storage."""
if not content:
return None
return [
c.model_dump(mode="json") if hasattr(c, "model_dump") else c for c in content
]
result = []
for content_block in content:
block_dict = (
content_block.model_dump(mode="json")
if hasattr(content_block, "model_dump")
else content_block
)
if (
isinstance(block_dict, dict)
and block_dict.get("type") == "text"
and isinstance(block_dict.get("text"), str)
):
block_dict = {
**block_dict,
"text": maybe_truncate(
block_dict["text"], truncate_after=MAX_ACP_CONTENT_CHARS
),
}
result.append(block_dict)
return result


async def _filter_jsonrpc_lines(source: Any, dest: Any) -> None:
Expand Down Expand Up @@ -503,13 +525,18 @@ def _emit_tool_call_event(self, tc: dict[str, Any]) -> None:
if self.on_event is None:
return
try:
raw_output = tc.get("raw_output")
if isinstance(raw_output, str):
raw_output = maybe_truncate(
raw_output, truncate_after=MAX_ACP_CONTENT_CHARS
)
event = ACPToolCallEvent(
tool_call_id=tc["tool_call_id"],
title=tc["title"],
status=tc.get("status"),
tool_kind=tc.get("tool_kind"),
raw_input=tc.get("raw_input"),
raw_output=tc.get("raw_output"),
raw_output=raw_output,
content=tc.get("content"),
is_error=tc.get("status") == "failed",
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
ConversationVisualizerBase,
DefaultConversationVisualizer,
)
from openhands.sdk.event.acp_tool_call import ACPToolCallEvent
from openhands.sdk.event.base import Event
from openhands.sdk.event.conversation_error import ConversationErrorEvent
from openhands.sdk.event.conversation_state import (
Expand Down Expand Up @@ -259,6 +260,7 @@ def __init__(
self._events_base_path = events_base_path
self._cached_events: list[Event] = []
self._cached_event_ids: set[str] = set()
self._acp_tool_call_id_to_event_id: dict[str, str] = {}
self._lock = threading.RLock()
# Initial fetch to sync existing events
self._do_full_sync()
Expand Down Expand Up @@ -350,6 +352,37 @@ def reconcile(self) -> int:

def _add_event_unsafe(self, event: Event) -> None:
"""Add event to cache without acquiring lock (caller must hold lock)."""
# ACP streaming emits one ACPToolCallEvent per ToolCallProgress, each
# carrying the full cumulative stdout so far — O(n²) memory growth.
# Deduplicate by tool_call_id: replace the existing entry in-place so
# only the latest (most complete) snapshot is kept.
if isinstance(event, ACPToolCallEvent):
existing_id = self._acp_tool_call_id_to_event_id.get(event.tool_call_id)
if existing_id is not None:
for i, e in enumerate(self._cached_events):
if e.id == existing_id:
self._cached_events[i] = event
self._cached_event_ids.discard(existing_id)
self._cached_event_ids.add(event.id)
Comment thread
simonrosenberg marked this conversation as resolved.
Resolved
self._acp_tool_call_id_to_event_id[event.tool_call_id] = (
event.id
)
logger.debug(
f"Replaced ACP tool call event {existing_id} -> {event.id} "
f"(tool_call_id={event.tool_call_id})"
)
return
Comment thread
simonrosenberg marked this conversation as resolved.
Resolved
Comment thread
simonrosenberg marked this conversation as resolved.
Resolved
# Index pointed to an event that is no longer in _cached_events;
# clean up the stale entry so we don't carry it forward.
logger.warning(
"Stale ACP tool-call index entry: "
f"tool_call_id={event.tool_call_id} "
f"pointed to event {existing_id} "
"not found in _cached_events; removing stale entry."
)
self._cached_event_ids.discard(existing_id)
del self._acp_tool_call_id_to_event_id[event.tool_call_id]

# Use bisect with key function for O(log N) insertion
# This ensures events are always ordered correctly even if
# WebSocket delivers them out of order
Expand All @@ -358,6 +391,8 @@ def _add_event_unsafe(self, event: Event) -> None:
)
self._cached_events.insert(insert_pos, event)
self._cached_event_ids.add(event.id)
if isinstance(event, ACPToolCallEvent):
self._acp_tool_call_id_to_event_id[event.tool_call_id] = event.id
logger.debug(f"Added event {event.id} to local cache at position {insert_pos}")

def add_event(self, event: Event) -> None:
Expand Down
Empty file.
189 changes: 189 additions & 0 deletions openhands-sdk/openhands/sdk/tests/test_acp_dedup_and_truncation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
"""Regression tests for ACP tool call deduplication and content truncation.

Covers:
- RemoteEventsList._add_event_unsafe deduplicates ACPToolCallEvent by tool_call_id
- _serialize_tool_content truncates text blocks to MAX_ACP_CONTENT_CHARS
- _emit_tool_call_event (via _serialize_tool_content) preserves non-text blocks
- Stale index entry is cleaned up and a warning is logged
"""

from __future__ import annotations

import logging
import threading
import unittest
from unittest.mock import MagicMock, patch

from openhands.sdk.agent.acp_agent import MAX_ACP_CONTENT_CHARS, _serialize_tool_content
from openhands.sdk.conversation.impl.remote_conversation import RemoteEventsList
from openhands.sdk.event.acp_tool_call import ACPToolCallEvent


def _make_tool_call_event(tool_call_id: str, raw_output: str = "") -> ACPToolCallEvent:
return ACPToolCallEvent(
tool_call_id=tool_call_id,
title="test tool",
raw_output=raw_output,
)


def _make_events_list() -> RemoteEventsList:
"""Return a RemoteEventsList with _do_full_sync stubbed out."""
with patch.object(RemoteEventsList, "_do_full_sync"):
client = MagicMock()
return RemoteEventsList(client=client, conversation_id="conv-1")


class TestACPToolCallDeduplication(unittest.TestCase):
def setUp(self) -> None:
self.events = _make_events_list()

def _add(self, event: ACPToolCallEvent) -> None:
with self.events._lock:
self.events._add_event_unsafe(event)

def test_first_event_is_added(self) -> None:
ev = _make_tool_call_event("tc-1", "output-1")
self._add(ev)
self.assertEqual(len(self.events._cached_events), 1)
self.assertIn(ev.id, self.events._cached_event_ids)

def test_subsequent_events_replace_not_append(self) -> None:
ev1 = _make_tool_call_event("tc-1", "output-1")
ev2 = _make_tool_call_event("tc-1", "output-1-updated")
ev3 = _make_tool_call_event("tc-1", "output-1-final")
self._add(ev1)
self._add(ev2)
self._add(ev3)

self.assertEqual(len(self.events._cached_events), 1)
last = self.events._cached_events[0]
assert isinstance(last, ACPToolCallEvent)
self.assertEqual(last.raw_output, "output-1-final")
self.assertNotIn(ev1.id, self.events._cached_event_ids)
self.assertNotIn(ev2.id, self.events._cached_event_ids)
self.assertIn(ev3.id, self.events._cached_event_ids)

def test_different_tool_call_ids_are_kept_separately(self) -> None:
ev_a = _make_tool_call_event("tc-a", "a-output")
ev_b = _make_tool_call_event("tc-b", "b-output")
self._add(ev_a)
self._add(ev_b)

self.assertEqual(len(self.events._cached_events), 2)
ids = {
e.tool_call_id
for e in self.events._cached_events
if isinstance(e, ACPToolCallEvent)
}
self.assertEqual(ids, {"tc-a", "tc-b"})

def test_index_stays_consistent_after_replacement(self) -> None:
ev1 = _make_tool_call_event("tc-1", "v1")
ev2 = _make_tool_call_event("tc-1", "v2")
self._add(ev1)
self._add(ev2)

self.assertEqual(self.events._acp_tool_call_id_to_event_id["tc-1"], ev2.id)

def test_stale_index_entry_is_cleaned_up_with_warning(self) -> None:
ev1 = _make_tool_call_event("tc-1", "v1")
self._add(ev1)

# Manually corrupt state: remove ev1 from _cached_events but leave index intact
self.events._cached_events.clear()
self.events._cached_event_ids.discard(ev1.id)

ev2 = _make_tool_call_event("tc-1", "v2")
with self.assertLogs("openhands.sdk", level=logging.WARNING) as log_ctx:
self._add(ev2)

self.assertTrue(
any("Stale" in line for line in log_ctx.output),
"Expected a stale-index warning to be logged",
)
# ev2 should be inserted normally after cleanup
self.assertEqual(len(self.events._cached_events), 1)
self.assertEqual(self.events._cached_events[0].id, ev2.id)
self.assertEqual(self.events._acp_tool_call_id_to_event_id["tc-1"], ev2.id)

def test_thread_safety_concurrent_updates(self) -> None:
"""Concurrent updates to the same tool_call_id must not corrupt state."""
errors: list[Exception] = []

def updater(i: int) -> None:
try:
ev = _make_tool_call_event("tc-shared", f"output-{i}")
self._add(ev)
except Exception as exc:
errors.append(exc)

threads = [threading.Thread(target=updater, args=(i,)) for i in range(20)]
for t in threads:
t.start()
for t in threads:
t.join()

self.assertEqual(errors, [])
# Only one event per tool_call_id should survive
tc_events = [
e
for e in self.events._cached_events
if isinstance(e, ACPToolCallEvent) and e.tool_call_id == "tc-shared"
]
self.assertEqual(len(tc_events), 1)


class TestSerializeToolContentTruncation(unittest.TestCase):
def test_short_text_is_not_truncated(self) -> None:
content = [{"type": "text", "text": "short"}]
result = _serialize_tool_content(content)
assert result is not None
self.assertEqual(result[0]["text"], "short")

def test_long_text_is_truncated_to_max(self) -> None:
long_text = "x" * (MAX_ACP_CONTENT_CHARS + 5_000)
content = [{"type": "text", "text": long_text}]
result = _serialize_tool_content(content)
assert result is not None
self.assertLessEqual(len(result[0]["text"]), MAX_ACP_CONTENT_CHARS + 200)

def test_non_text_blocks_are_not_modified(self) -> None:
big_data = "y" * (MAX_ACP_CONTENT_CHARS + 1_000)
content = [{"type": "image_url", "url": big_data}]
result = _serialize_tool_content(content)
assert result is not None
self.assertEqual(result[0]["url"], big_data)

def test_none_content_returns_none(self) -> None:
self.assertIsNone(_serialize_tool_content(None))

def test_empty_content_returns_none(self) -> None:
self.assertIsNone(_serialize_tool_content([]))

def test_mixed_blocks_only_truncates_text(self) -> None:
long_text = "a" * (MAX_ACP_CONTENT_CHARS + 1_000)
big_url = "b" * (MAX_ACP_CONTENT_CHARS + 1_000)
content = [
{"type": "text", "text": long_text},
{"type": "image_url", "url": big_url},
]
result = _serialize_tool_content(content)
assert result is not None
self.assertLessEqual(len(result[0]["text"]), MAX_ACP_CONTENT_CHARS + 200)
self.assertEqual(len(result[1]["url"]), MAX_ACP_CONTENT_CHARS + 1_000)

def test_pydantic_model_content_is_serialized(self) -> None:
"""Blocks with model_dump() are serialized before the truncation check."""

class FakeBlock:
def model_dump(self, **_kwargs: object) -> dict:
return {"type": "text", "text": "hello"}

result = _serialize_tool_content([FakeBlock()])
assert result is not None
self.assertEqual(result[0]["text"], "hello")


if __name__ == "__main__":
unittest.main()
Loading