Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 52 additions & 6 deletions openhands-sdk/openhands/sdk/agent/acp_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -640,13 +640,22 @@ async def session_update(
}
self.accumulated_tool_calls.append(entry)
logger.debug("ACP tool call start: %s", update.tool_call_id)
# Emit one early "started" event — the action half of the
# action->observation pair. (If the server reports a terminal
# status on the very first notification, this single event is
# also the observation; the matching terminal-transition guard
# below then suppresses any redundant re-emission.)
self._emit_tool_call_event(entry)
self._maybe_signal_activity()
elif isinstance(update, ToolCallProgress):
# Find the existing tool call entry and merge updates
# Find the existing tool call entry and merge updates. Track the
# status seen *before* this frame so we can detect the single
# transition into a terminal state.
target: dict[str, Any] | None = None
prev_status: str | None = None
for tc in self.accumulated_tool_calls:
if tc["tool_call_id"] == update.tool_call_id:
prev_status = tc.get("status")
if update.title is not None:
tc["title"] = update.title
if update.kind is not None:
Expand All @@ -662,7 +671,19 @@ async def session_update(
target = tc
break
logger.debug("ACP tool call progress: %s", update.tool_call_id)
if target is not None:
# Persist exactly one terminal event per tool call. Intermediate
# progress frames each carry the *full cumulative* output; emitting
# one per frame is O(n^2) storage + WebSocket relay (the bug this
# method fixes). We accumulate them into ``target`` silently and
# emit only on the first transition into a terminal status, so the
# terminal event still carries the complete final output. This is
# the observation half of the action->observation pair.
became_terminal = (
target is not None
and target.get("status") in _TERMINAL_TOOL_CALL_STATUSES
and prev_status not in _TERMINAL_TOOL_CALL_STATUSES
)
if target is not None and became_terminal:
self._emit_tool_call_event(target)
Comment on lines +681 to 687

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Suggestion: became_terminal already includes target is not None as its first conjunct, so the outer guard on line 686 is always true when became_terminal is true and always false when it's false — the two conditions are redundant. Simplifying to if became_terminal: makes the intent clearer and removes the implicit claim that the two checks are independent.

Suggested change
became_terminal = (
target is not None
and target.get("status") in _TERMINAL_TOOL_CALL_STATUSES
and prev_status not in _TERMINAL_TOOL_CALL_STATUSES
)
if target is not None and became_terminal:
self._emit_tool_call_event(target)
became_terminal = (
target is not None
and target.get("status") in _TERMINAL_TOOL_CALL_STATUSES
and prev_status not in _TERMINAL_TOOL_CALL_STATUSES
)
if became_terminal:
self._emit_tool_call_event(target)

self._maybe_signal_activity()
else:
Expand Down Expand Up @@ -1658,6 +1679,28 @@ def _cancel_inflight_tool_calls(self) -> None:
exc_info=True,
)

def _flush_inflight_tool_calls_as_completed(self) -> None:
"""Emit a terminal ``completed`` ACPToolCallEvent for every accumulated
tool call still sitting at a non-terminal status.

The prompt returned successfully, so a tool card the server opened but
never closed (it sent ``ToolCallStart`` but no terminal
``ToolCallProgress``) is treated as completed. Since we now persist
exactly one early ``started`` event and one terminal event per call,
this guarantees the action->observation pairing holds for *every*
call — without it, a server that omits the closing frame would leave
the early ``started`` event as the last word, and the relaxed canvas
render gate would show that card spinning forever. Reuses
``_emit_tool_call_event`` so truncation and error-swallowing match the
live terminal path. No-op once every call is already terminal (the
common case, since ``conn.prompt`` only returns after its tools run).
"""
for tc in self._client.accumulated_tool_calls:
if tc.get("status") in _TERMINAL_TOOL_CALL_STATUSES:
continue
tc["status"] = "completed"
self._client._emit_tool_call_event(tc)

async def _arequest_session_cancel(self) -> None:
"""Async variant of _request_session_cancel that waits for cancel send."""
if self._conn is None or self._executor is None or self._session_id is None:
Expand Down Expand Up @@ -1895,10 +1938,13 @@ def _finalize_successful_turn(
usage_update=usage_update,
)

# ACPToolCallEvents were already emitted live from
# _OpenHandsACPBridge.session_update as each ToolCallStart /
# ToolCallProgress notification arrived — no end-of-turn fan-out
# here. FinishAction closes out the turn below.
# Tool cards were already streamed live from
# _OpenHandsACPBridge.session_update: one early ``started`` event per
# ToolCallStart and one terminal event per call. Close out any card the
# server opened but never terminated so every ``started`` has its
# matching terminal observation before the turn's FinishAction lands.
self._flush_inflight_tool_calls_as_completed()

response_text = "".join(self._client.accumulated_text)
thought_text = "".join(self._client.accumulated_thoughts)
if not response_text:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -346,10 +346,14 @@ 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.
# ACP emits two ACPToolCallEvents per call — an early ``started`` event
# and one terminal (``completed`` / ``failed``) event — the
# action->observation pair for a tool call. Merge by tool_call_id:
# replace the ``started`` entry in-place with the terminal one so a
# single card updates from running to its result, mirroring how an
# ObservationEvent supersedes its ActionEvent. (The source no longer
# fans out one frame per cumulative-output ToolCallProgress, so this is
# an O(1) two-event merge, not an O(n²) dedup.)
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:
Expand Down
10 changes: 7 additions & 3 deletions openhands-sdk/openhands/sdk/event/resume_transcript.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,9 +211,13 @@ def _render_tool_event(event: ACPToolCallEvent, max_chars: int) -> str | None:
def _terminal_tool_indices(events: Sequence[Event]) -> set[int]:
"""Indices of the terminal ACPToolCallEvent for each *streaming sequence*.

ACP streams ``pending → … → completed`` events for a single tool call
consecutively; only the last event in that run carries the final I/O.
We keep that last event and drop the earlier intermediates.
ACP emits an early ``started`` event and one terminal
(``completed`` / ``failed``) event for a single tool call consecutively;
only the terminal event carries the final I/O. We keep that terminal event
and drop the earlier ``started`` one. (This also tolerates legacy logs
persisted before the source collapse, where a ``pending → … → completed``
run held several intermediates — keeping the last still picks the
terminal frame.)

Critically, dedup is scoped to **contiguous runs separated by
MessageEvents**, not to the entire history. ACP providers (e.g. Codex)
Expand Down
204 changes: 204 additions & 0 deletions tests/sdk/agent/test_acp_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -847,6 +847,210 @@ async def test_ext_notification_is_noop(self):
await client.ext_notification("test", {}) # Should not raise


# ---------------------------------------------------------------------------
# Tool-call event emission (started + terminal, no per-progress fan-out)
# ---------------------------------------------------------------------------


def _mk_tool_start(
tool_call_id: str = "tc-1",
*,
title: str = "git status",
kind: str = "execute",
status: str = "in_progress",
raw_input: Any | None = None,
raw_output: Any | None = None,
content: Any | None = None,
) -> Any:
from acp.schema import ToolCallStart

start = MagicMock(spec=ToolCallStart)
start.tool_call_id = tool_call_id
start.title = title
start.kind = kind
start.status = status
start.raw_input = raw_input
start.raw_output = raw_output
start.content = content
return start


def _mk_tool_progress(
tool_call_id: str = "tc-1",
*,
title: str | None = None,
kind: str | None = None,
status: str | None = None,
raw_input: Any | None = None,
raw_output: Any | None = None,
content: Any | None = None,
) -> Any:
from acp.schema import ToolCallProgress

progress = MagicMock(spec=ToolCallProgress)
progress.tool_call_id = tool_call_id
progress.title = title
progress.kind = kind
progress.status = status
progress.raw_input = raw_input
progress.raw_output = raw_output
progress.content = content
return progress


class TestACPToolCallProgressCollapse:
"""The bridge persists exactly one ``started`` + one terminal event.

Each ``ToolCallProgress`` carries the *full cumulative* output, so emitting
one event per frame is O(n^2) storage + WebSocket relay. The bridge instead
streams one early ``started`` event and one terminal (``completed`` /
``failed``) event per ``tool_call_id`` — the action->observation pair —
while silently accumulating the intermediate frames so the terminal event
still carries the final output.
"""

@pytest.mark.asyncio
async def test_tool_call_start_emits_started_event(self) -> None:
client = _OpenHandsACPBridge()
events: list[Any] = []
client.on_event = events.append

await client.session_update("s1", _mk_tool_start(status="in_progress"))

assert len(events) == 1
assert isinstance(events[0], ACPToolCallEvent)
assert events[0].tool_call_id == "tc-1"
assert events[0].status == "in_progress"
assert events[0].is_error is False

@pytest.mark.asyncio
async def test_intermediate_progress_frames_are_not_emitted(self) -> None:
client = _OpenHandsACPBridge()
events: list[Any] = []
client.on_event = events.append

await client.session_update("s1", _mk_tool_start(status="in_progress"))
# Several non-terminal progress frames with growing cumulative output.
for chunk in ("a", "ab", "abc"):
await client.session_update(
"s1", _mk_tool_progress(status="in_progress", raw_output=chunk)
)

# Only the started event was persisted — the intermediate frames are
# accumulated silently (this is the O(n^2)->O(1) collapse).
assert len(events) == 1
assert events[0].status == "in_progress"

@pytest.mark.asyncio
async def test_full_lifecycle_emits_exactly_two_events(self) -> None:
client = _OpenHandsACPBridge()
events: list[Any] = []
client.on_event = events.append

await client.session_update("s1", _mk_tool_start(status="pending"))
await client.session_update(
"s1", _mk_tool_progress(status="in_progress", raw_output="partial")
)
await client.session_update(
"s1", _mk_tool_progress(status="completed", raw_output="partial-final")
)

assert len(events) == 2
started, terminal = events
assert started.status == "pending"
assert terminal.status == "completed"
# Terminal event carries the final cumulative output.
assert terminal.raw_output == "partial-final"
assert terminal.is_error is False

@pytest.mark.asyncio
async def test_failed_terminal_sets_is_error(self) -> None:
client = _OpenHandsACPBridge()
events: list[Any] = []
client.on_event = events.append

await client.session_update("s1", _mk_tool_start(status="in_progress"))
await client.session_update(
"s1", _mk_tool_progress(status="failed", raw_output="boom")
)

assert len(events) == 2
assert events[-1].status == "failed"
assert events[-1].is_error is True

@pytest.mark.asyncio
async def test_single_shot_completed_start_emits_once(self) -> None:
"""A ToolCallStart that is already terminal is the only event."""
client = _OpenHandsACPBridge()
events: list[Any] = []
client.on_event = events.append

await client.session_update(
"s1", _mk_tool_start(status="completed", raw_output="done")
)

assert len(events) == 1
assert events[0].status == "completed"

@pytest.mark.asyncio
async def test_redundant_terminal_progress_does_not_double_emit(self) -> None:
"""Only the first transition into a terminal status emits."""
client = _OpenHandsACPBridge()
events: list[Any] = []
client.on_event = events.append

await client.session_update("s1", _mk_tool_start(status="in_progress"))
await client.session_update("s1", _mk_tool_progress(status="completed"))
# A trailing duplicate terminal frame must not produce a third event.
await client.session_update("s1", _mk_tool_progress(status="completed"))

assert len(events) == 2
assert [e.status for e in events] == ["in_progress", "completed"]

def test_finalize_flush_completes_orphaned_tool_calls(self) -> None:
"""A card the server opened but never closed is flushed to completed."""
agent = _make_agent()
client = _OpenHandsACPBridge()
events: list[Any] = []
client.on_event = events.append
agent._client = client

# One still-running call and one already-terminal call.
client.accumulated_tool_calls.append(
{
"tool_call_id": "live-1",
"title": "long task",
"tool_kind": "execute",
"status": "in_progress",
"raw_input": None,
"raw_output": "partial output",
"content": None,
}
)
client.accumulated_tool_calls.append(
{
"tool_call_id": "done-1",
"title": "quick task",
"tool_kind": "read",
"status": "completed",
"raw_input": None,
"raw_output": "ok",
"content": None,
}
)

agent._flush_inflight_tool_calls_as_completed()

# Only the non-terminal call is flushed (the terminal one is untouched).
assert len(events) == 1
assert events[0].tool_call_id == "live-1"
assert events[0].status == "completed"
assert events[0].is_error is False
assert events[0].raw_output == "partial output"
# The accumulator entry is now terminal so it won't be flushed again.
assert client.accumulated_tool_calls[0]["status"] == "completed"


# ---------------------------------------------------------------------------
# Activity heartbeat
# ---------------------------------------------------------------------------
Expand Down
18 changes: 18 additions & 0 deletions tests/sdk/event/test_resume_transcript.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,24 @@ def test_deduplicates_tool_events_by_id(self) -> None:
assert "(completed)" in out
assert "ok" in out

def test_started_then_terminal_renders_only_terminal(self) -> None:
# The source now persists exactly two events per call: an early
# ``started`` (in_progress) event and one terminal event. The transcript
# must keep only the terminal one — it carries the final I/O.
started = _tool("tc-1", title="bash", status="in_progress", raw_input={"c": 1})
terminal = _tool(
"tc-1",
title="bash",
status="completed",
raw_input={"c": 1},
raw_output="final output",
)
out = render_resume_transcript([started, terminal])
assert out is not None
assert out.count("[TOOL USE: bash]") == 1
assert "(completed)" in out
assert "final output" in out

def test_cross_session_same_id_both_render(self) -> None:
# ACP providers like Codex reset tool_call_id counters each session.
# A user message between two events with the same id means they come
Expand Down
Loading