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
23 changes: 3 additions & 20 deletions openhands-agent-server/openhands/agent_server/event_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,26 +381,9 @@ async def send_message(self, message: Message, run: bool = False):
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, self._conversation.send_message, message)
if run:
run = (
await self._get_execution_status()
!= ConversationExecutionStatus.RUNNING
)
if run:
conversation = self._conversation

async def _run_with_error_handling():
try:
await loop.run_in_executor(None, conversation.run)
except Exception:
logger.exception("Error during conversation run from send_message")

# Fire-and-forget: This task is intentionally not tracked because
# send_message() is designed to return immediately after queuing the
# message. The conversation run happens in the background and any
# errors are logged. Unlike the run() method which is explicitly
# awaited, this pattern allows clients to send messages without
# blocking on the full conversation execution.
loop.create_task(_run_with_error_handling())
# Already running or inactive — message was sent, skip run.
with suppress(ValueError):
await self.run()

async def subscribe_to_events(self, subscriber: Subscriber[Event]) -> UUID:
subscriber_id = self._pub_sub.subscribe(subscriber)
Expand Down
40 changes: 22 additions & 18 deletions tests/agent_server/test_event_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import shutil
import threading
import time
from contextlib import suppress
from datetime import UTC, datetime
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
Expand Down Expand Up @@ -697,18 +698,24 @@ async def test_send_message_with_run_true_agent_already_running(
conversation.run = MagicMock()

event_service._conversation = conversation
event_service._get_execution_status = AsyncMock(
return_value=ConversationExecutionStatus.RUNNING
)
# Simulate conversation already running to test the ValueError path
event_service._run_task = asyncio.create_task(asyncio.sleep(10))
message = Message(role="user", content=[])
Comment thread
csmith49 marked this conversation as resolved.
Resolved

# Call send_message with run=True
# Call send_message with run=True — should silently skip run
await event_service.send_message(message, run=True)

conversation.send_message.assert_called_once_with(message)
event_service._get_execution_status.assert_awaited_once()
# run() delegates to self.run() which checks status under lock
# and raises ValueError (caught by send_message) — so
# conversation.run is never invoked.
conversation.run.assert_not_called()

# Clean up the simulated running task
event_service._run_task.cancel()
with suppress(asyncio.CancelledError):
Comment thread
csmith49 marked this conversation as resolved.
Resolved
await event_service._run_task

@pytest.mark.asyncio
async def test_send_message_with_run_true_agent_idle(self, event_service):
"""Test send_message with run=True and agent idle triggers run."""
Expand All @@ -724,6 +731,7 @@ async def test_send_message_with_run_true_agent_idle(self, event_service):
conversation.run = MagicMock()

event_service._conversation = conversation
event_service._publish_state_update = AsyncMock()
message = Message(role="user", content=[])

# Call send_message with run=True
Expand All @@ -732,12 +740,9 @@ async def test_send_message_with_run_true_agent_idle(self, event_service):
# Verify send_message was called
conversation.send_message.assert_called_once_with(message)

# Wait for the background task to call run with a timeout
async def wait_for_run_called():
while not conversation.run.called:
await asyncio.sleep(0.001)

await asyncio.wait_for(wait_for_run_called(), timeout=1.0)
# send_message delegates to self.run() which creates a background task
assert event_service._run_task is not None
await event_service._run_task

# Verify run was called since agent was idle
conversation.run.assert_called_once()
Expand All @@ -757,23 +762,22 @@ async def test_send_message_with_run_true_logs_exception(self, event_service):
conversation.run = MagicMock(side_effect=RuntimeError("Test error"))

event_service._conversation = conversation
event_service._publish_state_update = AsyncMock()
message = Message(role="user", content=[])

# Patch the logger to verify exception logging
with patch("openhands.agent_server.event_service.logger") as mock_logger:
# Call send_message with run=True
await event_service.send_message(message, run=True)

# Wait for the background task to complete with a timeout
async def wait_for_exception_logged():
while not mock_logger.exception.called:
await asyncio.sleep(0.001)

await asyncio.wait_for(wait_for_exception_logged(), timeout=1.0)
# Wait for the background task to complete
assert event_service._run_task is not None
await event_service._run_task

# Verify the exception was logged via logger.exception()
# (logged by run()'s _run_and_publish handler)
mock_logger.exception.assert_called_once_with(
"Error during conversation run from send_message"
"Error during conversation run"
)

# Verify send_message was still called
Expand Down
Loading