π OpenHands: AI-Driven Development
Reduced thrash on sandbox service (#13610)
Tim O'Farrelleba1f60c1d34
diff --git a/openhands/server/routes/conversation.py b/openhands/server/routes/conversation.pyindex 9f126251bc..a44a3ca221 100644--- a/openhands/server/routes/conversation.py+++ b/openhands/server/routes/conversation.py@@ -12,10 +12,13 @@ from fastapi import APIRouter, Depends, HTTPException, Request, statusfrom fastapi.responses import JSONResponsefrom pydantic import BaseModel-from openhands.app_server.app_conversation.app_conversation_service import (- AppConversationService,+from openhands.app_server.app_conversation.app_conversation_info_service import (+ AppConversationInfoService,)-from openhands.app_server.config import depends_app_conversation_service+from openhands.app_server.app_conversation.app_conversation_models import (+ AppConversationInfo,+)+from openhands.app_server.config import depends_app_conversation_info_servicefrom openhands.core.logger import openhands_logger as loggerfrom openhands.events.action.message import MessageActionfrom openhands.events.event_filter import EventFilter@@ -36,59 +39,27 @@ app = APIRouter()# Dependency for app conversation service-app_conversation_service_dependency = depends_app_conversation_service()-+app_conversation_info_service_dependency = depends_app_conversation_info_service()-async def _is_v1_conversation(- conversation_id: str, app_conversation_service: AppConversationService-) -> bool:- """Check if the given conversation_id corresponds to a V1 conversation.-- Args:- conversation_id: The conversation ID to check- app_conversation_service: Service to query V1 conversations- Returns:- True if this is a V1 conversation, False otherwise- """+async def _get_v1_conversation_info(+ conversation_id: str, app_conversation_info_service: AppConversationInfoService+) -> AppConversationInfo | None:try:conversation_uuid = uuid.UUID(conversation_id)- app_conversation = await app_conversation_service.get_app_conversation(- conversation_uuid+ app_conversation_info = (+ await app_conversation_info_service.get_app_conversation_info(+ conversation_uuid+ ))- return app_conversation is not None+ return app_conversation_infoexcept (ValueError, TypeError):# Not a valid UUID, so it's not a V1 conversation- return False- except Exception:+ return None+ except Exception as e:# Service error, assume it's not a V1 conversation- return False---async def _get_v1_conversation_config(- conversation_id: str, app_conversation_service: AppConversationService-) -> dict[str, str | None]:- """Get configuration for a V1 conversation.-- Args:- conversation_id: The conversation ID- app_conversation_service: Service to query V1 conversations-- Returns:- Dictionary with runtime_id (sandbox_id) and session_id (conversation_id)- """- conversation_uuid = uuid.UUID(conversation_id)- app_conversation = await app_conversation_service.get_app_conversation(- conversation_uuid- )-- if app_conversation is None:- raise ValueError(f'V1 conversation {conversation_id} not found')-- return {- 'runtime_id': app_conversation.sandbox_id,- 'session_id': conversation_id,- }+ logger.debug(f'Failed to fetch V1 conversation {conversation_id}: {e}')+ return Nonedef _get_v0_conversation_config(@@ -115,7 +86,7 @@ def _get_v0_conversation_config(@app.get('/config')async def get_remote_runtime_config(conversation_id: str,- app_conversation_service: AppConversationService = app_conversation_service_dependency,+ app_conversation_info_service: AppConversationInfoService = app_conversation_info_service_dependency,user_id: str | None = Depends(get_user_id),) -> JSONResponse:"""Retrieve the runtime configuration.@@ -124,10 +95,17 @@ async def get_remote_runtime_config(For V1 conversations: returns sandbox_id as runtime_id and conversation_id as session_id."""# Check if this is a V1 conversation first- if await _is_v1_conversation(conversation_id, app_conversation_service):+ v1_conversation_info = await _get_v1_conversation_info(+ conversation_id, app_conversation_info_service+ )+ if v1_conversation_info:# This is a V1 conversation- config = await _get_v1_conversation_config(- conversation_id, app_conversation_service+ return JSONResponse(+ content={+ 'runtime_id': v1_conversation_info.sandbox_id,+ 'session_id': conversation_id,+ },+ status_code=200,)else:# V0 conversation - get the conversation and use the existing logicdiff --git a/tests/unit/server/routes/test_conversation_routes.py b/tests/unit/server/routes/test_conversation_routes.pyindex 9b1e08bc7e..7a5a250cca 100644--- a/tests/unit/server/routes/test_conversation_routes.py+++ b/tests/unit/server/routes/test_conversation_routes.py@@ -38,6 +38,7 @@ from openhands.server.routes.conversation import (AddMessageRequest,add_message,get_microagents,+ get_remote_runtime_config,)from openhands.server.routes.manage_conversations import (_RESUME_GRACE_PERIOD,@@ -1686,3 +1687,208 @@ async def test_get_conversation_info_returns_all_fields():assert result.pr_number == [123]assert result.sandbox_id is None # V0 should have null sandbox_idassert result.conversation_version == 'V0'+++# Tests for get_remote_runtime_config endpoint (/config)+++async def test_get_remote_runtime_config_v1_conversation():+ """Test get_remote_runtime_config returns correct config for V1 conversations."""+ from uuid import UUID++ conversation_id = str(uuid4())+ test_sandbox_id = 'test-sandbox-v1-123'++ # Create mock AppConversationInfo+ mock_info = AppConversationInfo(+ id=UUID(conversation_id),+ created_by_user_id='test_user',+ sandbox_id=test_sandbox_id,+ created_at=datetime.now(timezone.utc),+ updated_at=datetime.now(timezone.utc),+ )++ # Mock the AppConversationInfoService - use AsyncMock for the method+ mock_info_service = AsyncMock(spec=AppConversationInfoService)+ mock_info_service.get_app_conversation_info = AsyncMock(return_value=mock_info)++ # Call the function directly+ result = await get_remote_runtime_config(+ conversation_id=conversation_id,+ app_conversation_info_service=mock_info_service,+ )++ # Verify the response - V1 returns a JSONResponse+ assert isinstance(result, JSONResponse)+ content = json.loads(result.body)+ assert isinstance(content, dict)+ assert content['runtime_id'] == test_sandbox_id+ assert content['session_id'] == conversation_id++ # Verify the service was called with correct UUID+ mock_info_service.get_app_conversation_info.assert_called_once_with(+ UUID(conversation_id)+ )+++async def test_get_remote_runtime_config_v0_conversation():+ """Test get_remote_runtime_config returns correct config for V0 conversations."""+ from openhands.runtime.base import Runtime+ from openhands.server.session.conversation import ServerConversation++ conversation_id = 'test-conversation-v0'+ test_runtime_id = 'test-runtime-456'+ test_session_id = 'test-sid-789'++ # Create mock Runtime with runtime_id and sid+ mock_runtime = MagicMock(spec=Runtime)+ mock_runtime.runtime_id = test_runtime_id+ mock_runtime.sid = test_session_id++ # Create mock ServerConversation+ mock_conversation = MagicMock(spec=ServerConversation)+ mock_conversation.runtime = mock_runtime++ # Mock the conversation_manager - use AsyncMock for attach_to_conversation+ with patch(+ 'openhands.server.routes.conversation.conversation_manager'+ ) as mock_manager:+ mock_manager.attach_to_conversation = AsyncMock(return_value=mock_conversation)+ mock_manager.detach_from_conversation = AsyncMock()++ # Mock the AppConversationInfoService to return None (not V1)+ mock_info_service = AsyncMock(spec=AppConversationInfoService)+ mock_info_service.get_app_conversation_info = AsyncMock(return_value=None)++ # Call the function directly+ result = await get_remote_runtime_config(+ conversation_id=conversation_id,+ app_conversation_info_service=mock_info_service,+ )++ # Verify the response+ assert isinstance(result, JSONResponse)+ assert result.status_code == 200+ content = json.loads(result.body)+ assert content['runtime_id'] == test_runtime_id+ assert content['session_id'] == test_session_id+++async def test_get_remote_runtime_config_v1_not_found_falls_back_to_v0():+ """Test get_remote_runtime_config falls back to V0 when V1 conversation not found."""+ from openhands.runtime.base import Runtime+ from openhands.server.session.conversation import ServerConversation++ conversation_id = 'test-conversation-v0'+ test_runtime_id = 'test-runtime-abc'+ test_session_id = 'test-sid-xyz'++ # Create mock Runtime+ mock_runtime = MagicMock(spec=Runtime)+ mock_runtime.runtime_id = test_runtime_id+ mock_runtime.sid = test_session_id++ # Create mock ServerConversation+ mock_conversation = MagicMock(spec=ServerConversation)+ mock_conversation.runtime = mock_runtime++ # Mock the conversation_manager - use AsyncMock+ with patch(+ 'openhands.server.routes.conversation.conversation_manager'+ ) as mock_manager:+ mock_manager.attach_to_conversation = AsyncMock(return_value=mock_conversation)+ mock_manager.detach_from_conversation = AsyncMock()++ # Mock the AppConversationInfoService to return None (not found)+ mock_info_service = AsyncMock(spec=AppConversationInfoService)+ mock_info_service.get_app_conversation_info = AsyncMock(return_value=None)++ # Call the function directly+ result = await get_remote_runtime_config(+ conversation_id=conversation_id,+ app_conversation_info_service=mock_info_service,+ )++ # Verify the response - should fall back to V0 config+ assert isinstance(result, JSONResponse)+ assert result.status_code == 200+ content = json.loads(result.body)+ assert content['runtime_id'] == test_runtime_id+ assert content['session_id'] == test_session_id+++async def test_get_remote_runtime_config_invalid_uuid_falls_back_to_v0():+ """Test get_remote_runtime_config falls back to V0 for invalid UUID."""+ from openhands.runtime.base import Runtime+ from openhands.server.session.conversation import ServerConversation++ conversation_id = 'not-a-valid-uuid'+ test_runtime_id = 'test-runtime-def'+ test_session_id = 'test-sid-ghi'++ # Create mock Runtime+ mock_runtime = MagicMock(spec=Runtime)+ mock_runtime.runtime_id = test_runtime_id+ mock_runtime.sid = test_session_id++ # Create mock ServerConversation+ mock_conversation = MagicMock(spec=ServerConversation)+ mock_conversation.runtime = mock_runtime++ # Mock the conversation_manager - use AsyncMock+ with patch(+ 'openhands.server.routes.conversation.conversation_manager'+ ) as mock_manager:+ mock_manager.attach_to_conversation = AsyncMock(return_value=mock_conversation)+ mock_manager.detach_from_conversation = AsyncMock()++ # Mock the AppConversationInfoService - use AsyncMock for the method+ mock_info_service = AsyncMock(spec=AppConversationInfoService)+ mock_info_service.get_app_conversation_info = AsyncMock(+ side_effect=ValueError('Invalid UUID')+ )++ # Call the function directly+ result = await get_remote_runtime_config(+ conversation_id=conversation_id,+ app_conversation_info_service=mock_info_service,+ )++ # Verify the response - should fall back to V0 config+ assert isinstance(result, JSONResponse)+ assert result.status_code == 200+ content = json.loads(result.body)+ assert content['runtime_id'] == test_runtime_id+ assert content['session_id'] == test_session_id+++async def test_get_remote_runtime_config_v0_not_found():+ """Test get_remote_runtime_config returns 404 when V0 conversation not found."""+ from fastapi import HTTPException++ conversation_id = 'test-conversation-v0'++ # Mock the conversation_manager - use AsyncMock+ with patch(+ 'openhands.server.routes.conversation.conversation_manager'+ ) as mock_manager:+ mock_manager.attach_to_conversation = AsyncMock(return_value=None)++ # Mock the AppConversationInfoService to return None (not V1)+ mock_info_service = AsyncMock(spec=AppConversationInfoService)+ mock_info_service.get_app_conversation_info = AsyncMock(return_value=None)++ # Call the function and expect HTTPException+ with pytest.raises(HTTPException) as exc_info:+ await get_remote_runtime_config(+ conversation_id=conversation_id,+ app_conversation_info_service=mock_info_service,+ )++ assert exc_info.value.status_code == status.HTTP_404_NOT_FOUND+ assert f'Conversation {conversation_id} not found' in str(exc_info.value.detail)