Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat: Add REST endpoint to send follow-up messages to conversations (#14182)

Rohit Malhotraea50ade6ec14
diff --git a/openhands/app_server/app_conversation/app_conversation_models.py b/openhands/app_server/app_conversation/app_conversation_models.py
index 2d0ac85b6e..88cc1f3699 100644
--- a/openhands/app_server/app_conversation/app_conversation_models.py
+++ b/openhands/app_server/app_conversation/app_conversation_models.py
@@ -5,7 +5,12 @@ from uuid import UUID, uuid4
from pydantic import BaseModel, Field, SecretStr
-from openhands.agent_server.models import OpenHandsModel, SendMessageRequest
+from openhands.agent_server.models import (
+ ImageContent,
+ OpenHandsModel,
+ SendMessageRequest,
+ TextContent,
+)
from openhands.agent_server.utils import OpenHandsUUID, utc_now
from openhands.app_server.event_callback.event_callback_models import (
EventCallbackProcessor,
@@ -301,3 +306,40 @@ class GetHooksResponse(BaseModel):
"""Response model for hooks endpoint."""
hooks: list[HookEventResponse] = []
+
+
+class AppSendMessageRequest(BaseModel):
+ """Request to send a follow-up message to a conversation.
+
+ This is used to send messages to an existing conversation via REST API,
+ as an alternative to WebSocket communication.
+ """
+
+ role: Literal['user'] = Field(
+ default='user',
+ description='The role of the message sender. Currently only "user" is supported.',
+ )
+ content: list[TextContent | ImageContent] = Field(
+ ...,
+ min_length=1,
+ description='The message content as a list of text and/or image content blocks.',
+ )
+ run: bool = Field(
+ default=True,
+ description='Whether to automatically run the agent after sending the message.',
+ )
+
+
+class AppSendMessageResponse(BaseModel):
+ """Response from sending a message to a conversation."""
+
+ success: bool = Field(
+ description='Whether the message was successfully sent to the agent.',
+ )
+ sandbox_status: SandboxStatus = Field(
+ description='The current status of the sandbox after the operation.',
+ )
+ message: str | None = Field(
+ default=None,
+ description='Optional message with additional details (e.g., if sandbox was resumed).',
+ )
diff --git a/openhands/app_server/app_conversation/app_conversation_router.py b/openhands/app_server/app_conversation/app_conversation_router.py
index 2af606250f..3777c56f24 100644
--- a/openhands/app_server/app_conversation/app_conversation_router.py
+++ b/openhands/app_server/app_conversation/app_conversation_router.py
@@ -28,6 +28,8 @@ from openhands.app_server.app_conversation.app_conversation_models import (
AppConversationStartTaskPage,
AppConversationStartTaskSortOrder,
AppConversationUpdateRequest,
+ AppSendMessageRequest,
+ AppSendMessageResponse,
GetHooksResponse,
HookDefinitionResponse,
HookEventResponse,
@@ -388,6 +390,170 @@ async def update_app_conversation(
return info
+ '/{conversation_id}/send-message',
+ responses={
+ 404: {'description': 'Conversation or sandbox not found'},
+ 409: {
+ 'description': 'Sandbox is not running. Resume it first via POST /sandboxes/{id}/resume'
+ },
+ 410: {'description': 'Conversation is archived (sandbox no longer exists)'},
+ 503: {'description': 'Sandbox is in error state or agent server unavailable'},
+ },
+)
+async def send_message_to_conversation(
+ conversation_id: UUID,
+ request: AppSendMessageRequest,
+ app_conversation_service: AppConversationService = (
+ app_conversation_service_dependency
+ ),
+ sandbox_service: SandboxService = sandbox_service_dependency,
+ httpx_client: httpx.AsyncClient = httpx_client_dependency,
+) -> AppSendMessageResponse:
+ """Send a follow-up message to an existing conversation.
+
+ This REST endpoint provides a simplified way to send messages to a running
+ conversation without requiring a WebSocket connection.
+
+ **Alternative Approaches:**
+
+ This endpoint is a convenience wrapper. You can also interact with the agent
+ server directly using:
+
+ 1. **WebSocket**: Connect to the agent server's WebSocket endpoint for
+ real-time bidirectional communication
+ 2. **Agent Server REST API**: Call the agent server's REST endpoints directly
+ using the `conversation_url` from `GET /api/v1/app-conversations/{id}`
+
+ **Design Note:**
+
+ This endpoint is intentionally a thin proxy that forwards messages to the
+ agent server without additional processing logic. Any custom processing
+ (validation, transformation, side effects) should be implemented via
+ webhook callbacks, not in this endpoint. This ensures that direct agent
+ server invocation and this convenience endpoint remain functionally equivalent.
+
+ **Prerequisites:**
+
+ - The sandbox must be in RUNNING state
+ - If the sandbox is PAUSED, call `POST /api/v1/sandboxes/{sandbox_id}/resume` first
+ - If the sandbox is STARTING, wait for it to reach RUNNING state
+
+ **Error responses:**
+
+ - 404: Conversation or sandbox not found
+ - 409: Sandbox exists but is not running (PAUSED, STARTING, STOPPING)
+ - 410: Conversation is archived (sandbox no longer exists)
+ - 503: Sandbox is in ERROR state or agent server is unavailable
+
+ Args:
+ conversation_id: The UUID of the conversation to send the message to
+ request: The message content and options
+
+ Returns:
+ AppSendMessageResponse with success status and sandbox state
+ """
+ # Get conversation info
+ conversation = await app_conversation_service.get_app_conversation(conversation_id)
+ if not conversation:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f'Conversation {conversation_id} not found',
+ )
+
+ # Get sandbox info
+ sandbox = await sandbox_service.get_sandbox(conversation.sandbox_id)
+ if not sandbox:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f'Sandbox not found for conversation {conversation_id}',
+ )
+
+ # Check sandbox status - require RUNNING state
+ if sandbox.status == SandboxStatus.MISSING:
+ raise HTTPException(
+ status_code=status.HTTP_410_GONE,
+ detail='Conversation is archived. The sandbox no longer exists.',
+ )
+
+ if sandbox.status == SandboxStatus.ERROR:
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail='Sandbox is in an error state and cannot accept messages.',
+ )
+
+ if sandbox.status != SandboxStatus.RUNNING:
+ # Sandbox exists but is not running (PAUSED, STARTING, STOPPING, etc.)
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail=(
+ f'Sandbox is {sandbox.status.value}. '
+ f'Use POST /api/v1/sandboxes/{sandbox.id}/resume to resume it first.'
+ ),
+ )
+
+ # Get agent server URL from sandbox
+ if not sandbox.exposed_urls:
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail='No agent server URL found for sandbox.',
+ )
+
+ agent_server_url = None
+ for exposed_url in sandbox.exposed_urls:
+ if exposed_url.name == AGENT_SERVER:
+ agent_server_url = exposed_url.url
+ break
+
+ if not agent_server_url:
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail='Agent server URL not found in sandbox.',
+ )
+
+ agent_server_url = replace_localhost_hostname_for_docker(agent_server_url)
+
+ # Send message to agent server
+ try:
+ content_json = [item.model_dump() for item in request.content]
+ response = await httpx_client.post(
+ f'{agent_server_url}/api/conversations/{conversation_id}/events',
+ json={
+ 'role': request.role,
+ 'content': content_json,
+ 'run': request.run,
+ },
+ headers=(
+ {'X-Session-API-Key': sandbox.session_api_key}
+ if sandbox.session_api_key
+ else {}
+ ),
+ timeout=30.0,
+ )
+ response.raise_for_status()
+ except httpx.HTTPStatusError as e:
+ logger.error(
+ f'Agent server returned error when sending message: '
+ f'{e.response.status_code} - {e.response.text}'
+ )
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail=f'Agent server error: {e.response.status_code}',
+ )
+ except httpx.RequestError as e:
+ logger.error(f'Failed to reach agent server: {e}')
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail='Failed to reach agent server.',
+ )
+
+ return AppSendMessageResponse(
+ success=True,
+ sandbox_status=sandbox.status,
+ message=None,
+ )
+
+
async def _finalize_sandbox_delete(
sandbox_service: SandboxService,
app_conversation_info_service: AppConversationInfoService,
diff --git a/tests/unit/app_server/test_send_message_endpoint.py b/tests/unit/app_server/test_send_message_endpoint.py
new file mode 100644
index 0000000000..342a455b00
--- /dev/null
+++ b/tests/unit/app_server/test_send_message_endpoint.py
@@ -0,0 +1,535 @@
+"""Unit tests for the send_message_to_conversation endpoint.
+
+This module tests the send-message endpoint, focusing on:
+- Sandbox status handling (RUNNING, PAUSED, MISSING, ERROR)
+- Requiring sandbox to be in RUNNING state
+- Agent server communication
+- Error handling
+"""
+
+from unittest.mock import AsyncMock, MagicMock
+from uuid import uuid4
+
+import httpx
+import pytest
+from fastapi import HTTPException, status
+
+from openhands.agent_server.models import TextContent
+from openhands.app_server.app_conversation.app_conversation_models import (
+ AppConversation,
+ AppSendMessageRequest,
+)
+from openhands.app_server.app_conversation.app_conversation_router import (
+ send_message_to_conversation,
+)
+from openhands.app_server.sandbox.sandbox_models import (
+ AGENT_SERVER,
+ ExposedUrl,
+ SandboxInfo,
+ SandboxStatus,
+)
+
+
+def _make_mock_conversation(conversation_id=None, user_id='test-user', sandbox_id=None):
+ """Create a mock AppConversation for testing."""
+ if conversation_id is None:
+ conversation_id = uuid4()
+ if sandbox_id is None:
+ sandbox_id = str(uuid4())
+ return AppConversation(
+ id=conversation_id,
+ created_by_user_id=user_id,
+ sandbox_id=sandbox_id,
+ sandbox_status=SandboxStatus.RUNNING,
+ )
+
+
+def _make_mock_sandbox(
+ sandbox_id=None,
+ sandbox_status=SandboxStatus.RUNNING,
+ session_api_key='test-api-key',
+ agent_server_url='http://localhost:3000',
+):
+ """Create a mock SandboxInfo for testing."""
+ if sandbox_id is None:
+ sandbox_id = str(uuid4())
+ return SandboxInfo(
+ id=sandbox_id,
+ sandbox_spec_id='spec-1',
+ created_by_user_id='test-user',
+ status=sandbox_status,
+ session_api_key=session_api_key,
+ exposed_urls=[ExposedUrl(name=AGENT_SERVER, url=agent_server_url, port=3000)],
+ )
+
+
+def _make_mock_request(text='Hello, agent!', run=True):
+ """Create a mock AppSendMessageRequest for testing."""
+ return AppSendMessageRequest(
+ content=[TextContent(text=text)],
+ run=run,
+ )
+
+
+def _make_mock_conversation_service(conversation=None):
+ """Create a mock AppConversationService for testing."""
+ service = MagicMock()
+ service.get_app_conversation = AsyncMock(return_value=conversation)
+ return service
+
+
+def _make_mock_sandbox_service(sandbox=None):
+ """Create a mock SandboxService for testing."""
+ service = MagicMock()
+ service.get_sandbox = AsyncMock(return_value=sandbox)
+ return service
+
+
+def _make_mock_httpx_client(status_code=200, raise_error=None):
+ """Create a mock httpx.AsyncClient for testing."""
+ client = MagicMock()
+ response = MagicMock()
+ response.status_code = status_code
+ response.text = 'OK'
+
+ if raise_error:
+ client.post = AsyncMock(side_effect=raise_error)
+ else:
+ client.post = AsyncMock(return_value=response)
+
+ return client
+
+
+class TestSendMessageToConversation:
+ """Test suite for send_message_to_conversation endpoint."""
+
+ async def test_sends_message_to_running_conversation(self):
+ """Test sending a message to a running conversation.
+
+ Arrange: Create running conversation and sandbox
+ Act: Call send_message_to_conversation
+ Assert: Message is sent to agent server and success response returned
+ """
+ # Arrange
+ conversation_id = uuid4()
+ sandbox_id = str(uuid4())
+ conversation = _make_mock_conversation(
+ conversation_id=conversation_id, sandbox_id=sandbox_id
+ )
+ sandbox = _make_mock_sandbox(sandbox_id=sandbox_id)
+ request = _make_mock_request()
+
+ mock_conversation_service = _make_mock_conversation_service(conversation)
+ mock_sandbox_service = _make_mock_sandbox_service(sandbox)
+ mock_httpx_client = _make_mock_httpx_client()
+
+ # Act
+ result = await send_message_to_conversation(
+ conversation_id=conversation_id,
+ request=request,
+ app_conversation_service=mock_conversation_service,
+ sandbox_service=mock_sandbox_service,
+ httpx_client=mock_httpx_client,
+ )
+
+ # Assert
+ assert result.success is True
+ assert result.sandbox_status == SandboxStatus.RUNNING
+ assert result.message is None
+ mock_httpx_client.post.assert_called_once()
+ call_kwargs = mock_httpx_client.post.call_args
+ assert f'/api/conversations/{conversation_id}/events' in call_kwargs[0][0]
+
+ async def test_returns_404_for_nonexistent_conversation(self):
+ """Test that 404 is returned when conversation doesn't exist.
+
+ Arrange: Mock service to return None for conversation
+ Act: Call send_message_to_conversation
+ Assert: HTTPException with 404 is raised
+ """
+ # Arrange
+ conversation_id = uuid4()
+ mock_conversation_service = _make_mock_conversation_service(conversation=None)
+
+ # Act & Assert
+ with pytest.raises(HTTPException) as exc_info:
+ await send_message_to_conversation(
+ conversation_id=conversation_id,
+ request=_make_mock_request(),
+ app_conversation_service=mock_conversation_service,
+ sandbox_service=MagicMock(),
+ httpx_client=MagicMock(),
+ )
+
+ assert exc_info.value.status_code == status.HTTP_404_NOT_FOUND
+ assert 'not found' in exc_info.value.detail.lower()
+
+ async def test_returns_404_for_nonexistent_sandbox(self):
+ """Test that 404 is returned when sandbox doesn't exist.
+
+ Arrange: Create conversation but mock sandbox service to return None
+ Act: Call send_message_to_conversation
+ Assert: HTTPException with 404 is raised
+ """
+ # Arrange
+ conversation_id = uuid4()
+ conversation = _make_mock_conversation(conversation_id=conversation_id)
+ mock_conversation_service = _make_mock_conversation_service(conversation)
+ mock_sandbox_service = _make_mock_sandbox_service(sandbox=None)
+
+ # Act & Assert
+ with pytest.raises(HTTPException) as exc_info:
+ await send_message_to_conversation(
+ conversation_id=conversation_id,
+ request=_make_mock_request(),
+ app_conversation_service=mock_conversation_service,
+ sandbox_service=mock_sandbox_service,
+ httpx_client=MagicMock(),
+ )
+
+ assert exc_info.value.status_code == status.HTTP_404_NOT_FOUND
+ assert 'sandbox not found' in exc_info.value.detail.lower()
+
+ async def test_returns_410_for_archived_conversation(self):
+ """Test that 410 is returned when sandbox is MISSING (archived).
+
+ Arrange: Create conversation with MISSING sandbox
+ Act: Call send_message_to_conversation
+ Assert: HTTPException with 410 is raised
+ """
+ # Arrange
+ conversation_id = uuid4()
+ sandbox_id = str(uuid4())
+ conversation = _make_mock_conversation(
+ conversation_id=conversation_id, sandbox_id=sandbox_id
+ )
+ sandbox = _make_mock_sandbox(
+ sandbox_id=sandbox_id, sandbox_status=SandboxStatus.MISSING
+ )
+
+ mock_conversation_service = _make_mock_conversation_service(conversation)
+ mock_sandbox_service = _make_mock_sandbox_service(sandbox)
+
+ # Act & Assert
+ with pytest.raises(HTTPException) as exc_info:
+ await send_message_to_conversation(
+ conversation_id=conversation_id,
+ request=_make_mock_request(),
+ app_conversation_service=mock_conversation_service,
+ sandbox_service=mock_sandbox_service,
+ httpx_client=MagicMock(),
+ )
+
+ assert exc_info.value.status_code == status.HTTP_410_GONE
+ assert 'archived' in exc_info.value.detail.lower()
+
+ async def test_returns_503_for_sandbox_in_error_state(self):
+ """Test that 503 is returned when sandbox is in ERROR state.
+
+ Arrange: Create conversation with ERROR sandbox
+ Act: Call send_message_to_conversation
+ Assert: HTTPException with 503 is raised
+ """
+ # Arrange
+ conversation_id = uuid4()
+ sandbox_id = str(uuid4())
+ conversation = _make_mock_conversation(
+ conversation_id=conversation_id, sandbox_id=sandbox_id
+ )
+ sandbox = _make_mock_sandbox(
+ sandbox_id=sandbox_id, sandbox_status=SandboxStatus.ERROR
+ )
+
+ mock_conversation_service = _make_mock_conversation_service(conversation)
+ mock_sandbox_service = _make_mock_sandbox_service(sandbox)
+
+ # Act & Assert
+ with pytest.raises(HTTPException) as exc_info:
+ await send_message_to_conversation(
+ conversation_id=conversation_id,
+ request=_make_mock_request(),
+ app_conversation_service=mock_conversation_service,
+ sandbox_service=mock_sandbox_service,
+ httpx_client=MagicMock(),
+ )
+
+ assert exc_info.value.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+ assert 'error state' in exc_info.value.detail.lower()
+
+ async def test_returns_409_for_paused_sandbox(self):
+ """Test that 409 is returned when sandbox is PAUSED.
+
+ The endpoint does not auto-resume sandboxes. Callers must resume
+ the sandbox first via POST /api/v1/sandboxes/{id}/resume.
+
+ Arrange: Create conversation with PAUSED sandbox
+ Act: Call send_message_to_conversation
+ Assert: HTTPException with 409 is raised
+ """
+ # Arrange
+ conversation_id = uuid4()
+ sandbox_id = str(uuid4())
+ conversation = _make_mock_conversation(
+ conversation_id=conversation_id, sandbox_id=sandbox_id
+ )
+ sandbox = _make_mock_sandbox(
+ sandbox_id=sandbox_id, sandbox_status=SandboxStatus.PAUSED
+ )
+
+ mock_conversation_service = _make_mock_conversation_service(conversation)
+ mock_sandbox_service = _make_mock_sandbox_service(sandbox)
+
+ # Act & Assert
+ with pytest.raises(HTTPException) as exc_info:
+ await send_message_to_conversation(
+ conversation_id=conversation_id,
+ request=_make_mock_request(),
+ app_conversation_service=mock_conversation_service,
+ sandbox_service=mock_sandbox_service,
+ httpx_client=MagicMock(),
+ )
+
+ assert exc_info.value.status_code == status.HTTP_409_CONFLICT
+ assert 'paused' in exc_info.value.detail.lower()
+ assert '/resume' in exc_info.value.detail.lower()
+
+ async def test_returns_409_for_starting_sandbox(self):
+ """Test that 409 is returned when sandbox is STARTING.
+
+ Callers must wait for sandbox to reach RUNNING state before sending messages.
+
+ Arrange: Create conversation with STARTING sandbox
+ Act: Call send_message_to_conversation
+ Assert: HTTPException with 409 is raised
+ """
+ # Arrange
+ conversation_id = uuid4()
+ sandbox_id = str(uuid4())
+ conversation = _make_mock_conversation(
+ conversation_id=conversation_id, sandbox_id=sandbox_id
+ )
+ sandbox = _make_mock_sandbox(
+ sandbox_id=sandbox_id, sandbox_status=SandboxStatus.STARTING
+ )
+
+ mock_conversation_service = _make_mock_conversation_service(conversation)
+ mock_sandbox_service = _make_mock_sandbox_service(sandbox)
+
+ # Act & Assert
+ with pytest.raises(HTTPException) as exc_info:
+ await send_message_to_conversation(
+ conversation_id=conversation_id,
+ request=_make_mock_request(),
+ app_conversation_service=mock_conversation_service,
+ sandbox_service=mock_sandbox_service,
+ httpx_client=MagicMock(),
+ )
+
+ assert exc_info.value.status_code == status.HTTP_409_CONFLICT
+ assert 'starting' in exc_info.value.detail.lower()
+
+ async def test_returns_502_on_agent_server_http_error(self):
+ """Test that 502 is returned when agent server returns HTTP error.
+
+ Arrange: Create running conversation but mock agent server to return 500
+ Act: Call send_message_to_conversation
+ Assert: HTTPException with 502 is raised
+ """
+ # Arrange
+ conversation_id = uuid4()
+ sandbox_id = str(uuid4())
+ conversation = _make_mock_conversation(
+ conversation_id=conversation_id, sandbox_id=sandbox_id
+ )
+ sandbox = _make_mock_sandbox(sandbox_id=sandbox_id)
+
+ mock_conversation_service = _make_mock_conversation_service(conversation)
+ mock_sandbox_service = _make_mock_sandbox_service(sandbox)
+
+ # Create a mock response that will raise HTTPStatusError
+ mock_response = MagicMock()
+ mock_response.status_code = 500
+ mock_response.text = 'Internal Server Error'
+ error = httpx.HTTPStatusError(
+ 'Server error', request=MagicMock(), response=mock_response
+ )
+ mock_httpx_client = _make_mock_httpx_client(raise_error=error)
+
+ # Act & Assert
+ with pytest.raises(HTTPException) as exc_info:
+ await send_message_to_conversation(
+ conversation_id=conversation_id,
+ request=_make_mock_request(),
+ app_conversation_service=mock_conversation_service,
+ sandbox_service=mock_sandbox_service,
+ httpx_client=mock_httpx_client,
+ )
+
+ assert exc_info.value.status_code == status.HTTP_502_BAD_GATEWAY
+ assert 'agent server error' in exc_info.value.detail.lower()
+
+ async def test_returns_502_on_connection_error(self):
+ """Test that 502 is returned when can't connect to agent server.
+
+ Arrange: Create running conversation but mock connection failure
+ Act: Call send_message_to_conversation
+ Assert: HTTPException with 502 is raised
+ """
+ # Arrange
+ conversation_id = uuid4()
+ sandbox_id = str(uuid4())
+ conversation = _make_mock_conversation(
+ conversation_id=conversation_id, sandbox_id=sandbox_id
+ )
+ sandbox = _make_mock_sandbox(sandbox_id=sandbox_id)
+
+ mock_conversation_service = _make_mock_conversation_service(conversation)
+ mock_sandbox_service = _make_mock_sandbox_service(sandbox)
+
+ error = httpx.ConnectError('Connection refused')
+ mock_httpx_client = _make_mock_httpx_client(raise_error=error)
+
+ # Act & Assert
+ with pytest.raises(HTTPException) as exc_info:
+ await send_message_to_conversation(
+ conversation_id=conversation_id,
+ request=_make_mock_request(),
+ app_conversation_service=mock_conversation_service,
+ sandbox_service=mock_sandbox_service,
+ httpx_client=mock_httpx_client,
+ )
+
+ assert exc_info.value.status_code == status.HTTP_502_BAD_GATEWAY
+ assert 'failed to reach agent server' in exc_info.value.detail.lower()
+
+ async def test_sends_correct_headers_and_payload(self):
+ """Test that correct headers and payload are sent to agent server.
+
+ Arrange: Create running conversation
+ Act: Call send_message_to_conversation with specific content
+ Assert: Correct headers and payload are sent
+ """
+ # Arrange
+ conversation_id = uuid4()
+ sandbox_id = str(uuid4())
+ session_api_key = 'my-session-key'
+ conversation = _make_mock_conversation(
+ conversation_id=conversation_id, sandbox_id=sandbox_id
+ )
+ sandbox = _make_mock_sandbox(
+ sandbox_id=sandbox_id, session_api_key=session_api_key
+ )
+ request = AppSendMessageRequest(
+ content=[TextContent(text='Test message')],
+ run=False,
+ )
+
+ mock_conversation_service = _make_mock_conversation_service(conversation)
+ mock_sandbox_service = _make_mock_sandbox_service(sandbox)
+ mock_httpx_client = _make_mock_httpx_client()
+
+ # Act
+ await send_message_to_conversation(
+ conversation_id=conversation_id,
+ request=request,
+ app_conversation_service=mock_conversation_service,
+ sandbox_service=mock_sandbox_service,
+ httpx_client=mock_httpx_client,
+ )
+
+ # Assert
+ call_kwargs = mock_httpx_client.post.call_args
+ assert call_kwargs.kwargs['headers'] == {'X-Session-API-Key': session_api_key}
+ json_payload = call_kwargs.kwargs['json']
+ assert json_payload['role'] == 'user'
+ assert json_payload['run'] is False
+ assert len(json_payload['content']) == 1
+ assert json_payload['content'][0]['text'] == 'Test message'
+
+ async def test_returns_503_when_no_agent_server_url(self):
+ """Test that 503 is returned when sandbox has no agent server URL.
+
+ Arrange: Create sandbox without exposed URLs
+ Act: Call send_message_to_conversation
+ Assert: HTTPException with 503 is raised
+ """
+ # Arrange
+ conversation_id = uuid4()
+ sandbox_id = str(uuid4())
+ conversation = _make_mock_conversation(
+ conversation_id=conversation_id, sandbox_id=sandbox_id
+ )
+ sandbox = SandboxInfo(
+ id=sandbox_id,
+ sandbox_spec_id='spec-1',
+ created_by_user_id='test-user',
+ status=SandboxStatus.RUNNING,
+ session_api_key='test-key',
+ exposed_urls=[], # No exposed URLs
+ )
+
+ mock_conversation_service = _make_mock_conversation_service(conversation)
+ mock_sandbox_service = _make_mock_sandbox_service(sandbox)
+
+ # Act & Assert
+ with pytest.raises(HTTPException) as exc_info:
+ await send_message_to_conversation(
+ conversation_id=conversation_id,
+ request=_make_mock_request(),
+ app_conversation_service=mock_conversation_service,
+ sandbox_service=mock_sandbox_service,
+ httpx_client=MagicMock(),
+ )
+
+ assert exc_info.value.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+ assert 'agent server url' in exc_info.value.detail.lower()
+
+
+class TestAppSendMessageRequestValidation:
+ """Test suite for AppSendMessageRequest model validation."""
+
+ def test_content_must_not_be_empty(self):
+ """Test that content field rejects empty lists.
+
+ Arrange: Attempt to create request with empty content
+ Act: Create AppSendMessageRequest with content=[]
+ Assert: Validation error is raised
+ """
+ import pytest
+ from pydantic import ValidationError
+
+ with pytest.raises(ValidationError) as exc_info:
+ AppSendMessageRequest(content=[])
+
+ # Check that the validation error is about min_length
+ errors = exc_info.value.errors()
+ assert len(errors) == 1
+ assert errors[0]['loc'] == ('content',)
+ assert 'at least 1' in errors[0]['msg'].lower()
+
+ def test_content_accepts_single_item(self):
+ """Test that content field accepts a list with one item.
+
+ Arrange: Create request with single content item
+ Act: Instantiate AppSendMessageRequest
+ Assert: Request is created successfully
+ """
+ request = AppSendMessageRequest(content=[TextContent(text='Hello')])
+ assert len(request.content) == 1
+ assert request.content[0].text == 'Hello'
+
+ def test_content_accepts_multiple_items(self):
+ """Test that content field accepts a list with multiple items.
+
+ Arrange: Create request with multiple content items
+ Act: Instantiate AppSendMessageRequest
+ Assert: Request is created successfully
+ """
+ request = AppSendMessageRequest(
+ content=[
+ TextContent(text='Hello'),
+ TextContent(text='World'),
+ ]
+ )
+ assert len(request.content) == 2