π OpenHands: AI-Driven Development
Add AwsSharedEventService for shared conversations (#13141)
chuckbutkus922e3a243101
diff --git a/enterprise/server/sharing/aws_shared_event_service.py b/enterprise/server/sharing/aws_shared_event_service.pynew file mode 100644index 0000000000..9608f82ba7--- /dev/null+++ b/enterprise/server/sharing/aws_shared_event_service.py@@ -0,0 +1,171 @@+"""Implementation of SharedEventService for AWS S3.++This implementation provides read-only access to events from shared conversations:+- Validates that the conversation is shared before returning events+- Uses existing EventService for actual event retrieval+- Uses SharedConversationInfoService for shared conversation validation++Uses role-based authentication (no credentials needed).+"""++from __future__ import annotations++import logging+import os+from dataclasses import dataclass+from datetime import datetime+from pathlib import Path+from typing import Any, AsyncGenerator+from uuid import UUID++import boto3+from fastapi import Request+from pydantic import Field+from server.sharing.shared_conversation_info_service import (+ SharedConversationInfoService,+)+from server.sharing.shared_event_service import (+ SharedEventService,+ SharedEventServiceInjector,+)+from server.sharing.sql_shared_conversation_info_service import (+ SQLSharedConversationInfoService,+)++from openhands.agent_server.models import EventPage, EventSortOrder+from openhands.app_server.event.aws_event_service import AwsEventService+from openhands.app_server.event.event_service import EventService+from openhands.app_server.event_callback.event_callback_models import EventKind+from openhands.app_server.services.injector import InjectorState+from openhands.sdk import Event++logger = logging.getLogger(__name__)+++@dataclass+class AwsSharedEventService(SharedEventService):+ """Implementation of SharedEventService for AWS S3 that validates shared access.++ Uses role-based authentication (no credentials needed).+ """++ shared_conversation_info_service: SharedConversationInfoService+ s3_client: Any+ bucket_name: str++ async def get_event_service(self, conversation_id: UUID) -> EventService | None:+ shared_conversation_info = (+ await self.shared_conversation_info_service.get_shared_conversation_info(+ conversation_id+ )+ )+ if shared_conversation_info is None:+ return None++ return AwsEventService(+ s3_client=self.s3_client,+ bucket_name=self.bucket_name,+ prefix=Path('users'),+ user_id=shared_conversation_info.created_by_user_id,+ app_conversation_info_service=None,+ app_conversation_info_load_tasks={},+ )++ async def get_shared_event(+ self, conversation_id: UUID, event_id: UUID+ ) -> Event | None:+ """Given a conversation_id and event_id, retrieve an event if the conversation is shared."""+ # First check if the conversation is shared+ event_service = await self.get_event_service(conversation_id)+ if event_service is None:+ return None++ # If conversation is shared, get the event+ return await event_service.get_event(conversation_id, event_id)++ async def search_shared_events(+ self,+ conversation_id: UUID,+ kind__eq: EventKind | None = None,+ timestamp__gte: datetime | None = None,+ timestamp__lt: datetime | None = None,+ sort_order: EventSortOrder = EventSortOrder.TIMESTAMP,+ page_id: str | None = None,+ limit: int = 100,+ ) -> EventPage:+ """Search events for a specific shared conversation."""+ # First check if the conversation is shared+ event_service = await self.get_event_service(conversation_id)+ if event_service is None:+ # Return empty page if conversation is not shared+ return EventPage(items=[], next_page_id=None)++ # If conversation is shared, search events for this conversation+ return await event_service.search_events(+ conversation_id=conversation_id,+ kind__eq=kind__eq,+ timestamp__gte=timestamp__gte,+ timestamp__lt=timestamp__lt,+ sort_order=sort_order,+ page_id=page_id,+ limit=limit,+ )++ async def count_shared_events(+ self,+ conversation_id: UUID,+ kind__eq: EventKind | None = None,+ timestamp__gte: datetime | None = None,+ timestamp__lt: datetime | None = None,+ ) -> int:+ """Count events for a specific shared conversation."""+ # First check if the conversation is shared+ event_service = await self.get_event_service(conversation_id)+ if event_service is None:+ # Return empty page if conversation is not shared+ return 0++ # If conversation is shared, count events for this conversation+ return await event_service.count_events(+ conversation_id=conversation_id,+ kind__eq=kind__eq,+ timestamp__gte=timestamp__gte,+ timestamp__lt=timestamp__lt,+ )+++class AwsSharedEventServiceInjector(SharedEventServiceInjector):+ bucket_name: str | None = Field(+ default_factory=lambda: os.environ.get('FILE_STORE_PATH')+ )++ async def inject(+ self, state: InjectorState, request: Request | None = None+ ) -> AsyncGenerator[SharedEventService, None]:+ # Define inline to prevent circular lookup+ from openhands.app_server.config import get_db_session++ async with get_db_session(state, request) as db_session:+ shared_conversation_info_service = SQLSharedConversationInfoService(+ db_session=db_session+ )++ bucket_name = self.bucket_name+ if bucket_name is None:+ raise ValueError(+ 'bucket_name is required. Set FILE_STORE_PATH environment variable.'+ )++ # Use role-based authentication - boto3 will automatically+ # use IAM role credentials when running in AWS+ s3_client = boto3.client(+ 's3',+ endpoint_url=os.getenv('AWS_S3_ENDPOINT'),+ )++ service = AwsSharedEventService(+ shared_conversation_info_service=shared_conversation_info_service,+ s3_client=s3_client,+ bucket_name=bucket_name,+ )+ yield servicediff --git a/enterprise/server/sharing/shared_event_router.py b/enterprise/server/sharing/shared_event_router.pyindex f5b54c27ef..1f42d1d32e 100644--- a/enterprise/server/sharing/shared_event_router.py+++ b/enterprise/server/sharing/shared_event_router.py@@ -5,19 +5,45 @@ from typing import Annotatedfrom uuid import UUIDfrom fastapi import APIRouter, Depends, Query-from server.sharing.google_cloud_shared_event_service import (- GoogleCloudSharedEventServiceInjector,+from server.sharing.shared_event_service import (+ SharedEventService,+ SharedEventServiceInjector,)-from server.sharing.shared_event_service import SharedEventServicefrom openhands.agent_server.models import EventPage, EventSortOrderfrom openhands.app_server.event_callback.event_callback_models import EventKindfrom openhands.sdk import Event+from openhands.utils.environment import StorageProvider, get_storage_provider+++def get_shared_event_service_injector() -> SharedEventServiceInjector:+ """Get the appropriate SharedEventServiceInjector based on configuration.++ Uses get_storage_provider() to determine the storage backend.+ See openhands.utils.environment for supported environment variables.++ Note: Shared events only support AWS and GCP storage. Filesystem storage+ falls back to GCP for shared events.+ """+ provider = get_storage_provider()++ if provider == StorageProvider.AWS:+ from server.sharing.aws_shared_event_service import (+ AwsSharedEventServiceInjector,+ )++ return AwsSharedEventServiceInjector()+ else:+ # GCP is the default for shared events (including filesystem fallback)+ from server.sharing.google_cloud_shared_event_service import (+ GoogleCloudSharedEventServiceInjector,+ )++ return GoogleCloudSharedEventServiceInjector()+router = APIRouter(prefix='/api/shared-events', tags=['Sharing'])-shared_event_service_dependency = Depends(- GoogleCloudSharedEventServiceInjector().depends-)+shared_event_service_dependency = Depends(get_shared_event_service_injector().depends)# Read methodsdiff --git a/enterprise/tests/unit/test_sharing/test_aws_shared_event_service.py b/enterprise/tests/unit/test_sharing/test_aws_shared_event_service.pynew file mode 100644index 0000000000..c90a741b1d--- /dev/null+++ b/enterprise/tests/unit/test_sharing/test_aws_shared_event_service.py@@ -0,0 +1,555 @@+"""Tests for AwsSharedEventService."""++import os+from datetime import UTC, datetime+from unittest.mock import AsyncMock, MagicMock, patch+from uuid import uuid4++import pytest+from server.sharing.aws_shared_event_service import (+ AwsSharedEventService,+ AwsSharedEventServiceInjector,+)+from server.sharing.shared_conversation_info_service import (+ SharedConversationInfoService,+)+from server.sharing.shared_conversation_models import SharedConversation++from openhands.agent_server.models import EventPage, EventSortOrder+from openhands.app_server.event.event_service import EventService+from openhands.sdk.llm import MetricsSnapshot+from openhands.sdk.llm.utils.metrics import TokenUsage+++def mock_shared_conversation_info_service():+ """Create a mock SharedConversationInfoService."""+ return AsyncMock(spec=SharedConversationInfoService)+++def mock_s3_client():+ """Create a mock S3 client."""+ return MagicMock()+++def mock_event_service():+ """Create a mock EventService for returned by get_event_service."""+ return AsyncMock(spec=EventService)+++def aws_shared_event_service(mock_shared_conversation_info_service, mock_s3_client):+ """Create an AwsSharedEventService for testing."""+ return AwsSharedEventService(+ shared_conversation_info_service=mock_shared_conversation_info_service,+ s3_client=mock_s3_client,+ bucket_name='test-bucket',+ )+++def sample_public_conversation():+ """Create a sample public conversation."""+ return SharedConversation(+ id=uuid4(),+ created_by_user_id='test_user',+ sandbox_id='test_sandbox',+ title='Test Public Conversation',+ created_at=datetime.now(UTC),+ updated_at=datetime.now(UTC),+ metrics=MetricsSnapshot(+ accumulated_cost=0.0,+ max_budget_per_task=10.0,+ accumulated_token_usage=TokenUsage(),+ ),+ )+++def sample_event():+ """Create a sample event."""+ # For testing purposes, we'll just use a mock that the EventPage can accept+ # The actual event creation is complex and not the focus of these tests+ return None+++class TestAwsSharedEventService:+ """Test cases for AwsSharedEventService."""++ async def test_get_shared_event_returns_event_for_public_conversation(+ self,+ aws_shared_event_service,+ mock_shared_conversation_info_service,+ mock_event_service,+ sample_public_conversation,+ sample_event,+ ):+ """Test that get_shared_event returns an event for a public conversation."""+ conversation_id = sample_public_conversation.id+ event_id = uuid4()++ # Mock the public conversation service to return a public conversation+ mock_shared_conversation_info_service.get_shared_conversation_info.return_value = sample_public_conversation++ # Mock get_event_service to return our mock event service+ aws_shared_event_service.get_event_service = AsyncMock(+ return_value=mock_event_service+ )++ # Mock the event service to return an event+ mock_event_service.get_event.return_value = sample_event++ # Call the method+ result = await aws_shared_event_service.get_shared_event(+ conversation_id, event_id+ )++ # Verify the result+ assert result == sample_event+ aws_shared_event_service.get_event_service.assert_called_once_with(+ conversation_id+ )+ mock_event_service.get_event.assert_called_once_with(conversation_id, event_id)++ async def test_get_shared_event_returns_none_for_private_conversation(+ self,+ aws_shared_event_service,+ mock_shared_conversation_info_service,+ mock_event_service,+ ):+ """Test that get_shared_event returns None for a private conversation."""+ conversation_id = uuid4()+ event_id = uuid4()++ # Mock get_event_service to return None (private conversation)+ aws_shared_event_service.get_event_service = AsyncMock(return_value=None)++ # Call the method+ result = await aws_shared_event_service.get_shared_event(+ conversation_id, event_id+ )++ # Verify the result+ assert result is None+ aws_shared_event_service.get_event_service.assert_called_once_with(+ conversation_id+ )+ # Event service should not be called since get_event_service returns None+ mock_event_service.get_event.assert_not_called()++ async def test_search_shared_events_returns_events_for_public_conversation(+ self,+ aws_shared_event_service,+ mock_shared_conversation_info_service,+ mock_event_service,+ sample_public_conversation,+ sample_event,+ ):+ """Test that search_shared_events returns events for a public conversation."""+ conversation_id = sample_public_conversation.id++ # Mock get_event_service to return our mock event service+ aws_shared_event_service.get_event_service = AsyncMock(+ return_value=mock_event_service+ )++ # Mock the event service to return events+ mock_event_page = EventPage(items=[], next_page_id=None)+ mock_event_service.search_events.return_value = mock_event_page++ # Call the method+ result = await aws_shared_event_service.search_shared_events(+ conversation_id=conversation_id,+ kind__eq='ActionEvent',+ limit=10,+ )++ # Verify the result+ assert result == mock_event_page+ assert len(result.items) == 0 # Empty list as we mocked++ aws_shared_event_service.get_event_service.assert_called_once_with(+ conversation_id+ )+ mock_event_service.search_events.assert_called_once_with(+ conversation_id=conversation_id,+ kind__eq='ActionEvent',+ timestamp__gte=None,+ timestamp__lt=None,+ sort_order=EventSortOrder.TIMESTAMP,+ page_id=None,+ limit=10,+ )++ async def test_search_shared_events_returns_empty_for_private_conversation(+ self,+ aws_shared_event_service,+ mock_shared_conversation_info_service,+ mock_event_service,+ ):+ """Test that search_shared_events returns empty page for a private conversation."""+ conversation_id = uuid4()++ # Mock get_event_service to return None (private conversation)+ aws_shared_event_service.get_event_service = AsyncMock(return_value=None)++ # Call the method+ result = await aws_shared_event_service.search_shared_events(+ conversation_id=conversation_id,+ limit=10,+ )++ # Verify the result+ assert isinstance(result, EventPage)+ assert len(result.items) == 0+ assert result.next_page_id is None++ aws_shared_event_service.get_event_service.assert_called_once_with(+ conversation_id+ )+ # Event service should not be called+ mock_event_service.search_events.assert_not_called()++ async def test_count_shared_events_returns_count_for_public_conversation(+ self,+ aws_shared_event_service,+ mock_shared_conversation_info_service,+ mock_event_service,+ sample_public_conversation,+ ):+ """Test that count_shared_events returns count for a public conversation."""+ conversation_id = sample_public_conversation.id++ # Mock get_event_service to return our mock event service+ aws_shared_event_service.get_event_service = AsyncMock(+ return_value=mock_event_service+ )++ # Mock the event service to return a count+ mock_event_service.count_events.return_value = 5++ # Call the method+ result = await aws_shared_event_service.count_shared_events(+ conversation_id=conversation_id,+ kind__eq='ActionEvent',+ )++ # Verify the result+ assert result == 5++ aws_shared_event_service.get_event_service.assert_called_once_with(+ conversation_id+ )+ mock_event_service.count_events.assert_called_once_with(+ conversation_id=conversation_id,+ kind__eq='ActionEvent',+ timestamp__gte=None,+ timestamp__lt=None,+ )++ async def test_count_shared_events_returns_zero_for_private_conversation(+ self,+ aws_shared_event_service,+ mock_shared_conversation_info_service,+ mock_event_service,+ ):+ """Test that count_shared_events returns 0 for a private conversation."""+ conversation_id = uuid4()++ # Mock get_event_service to return None (private conversation)+ aws_shared_event_service.get_event_service = AsyncMock(return_value=None)++ # Call the method+ result = await aws_shared_event_service.count_shared_events(+ conversation_id=conversation_id,+ )++ # Verify the result+ assert result == 0++ aws_shared_event_service.get_event_service.assert_called_once_with(+ conversation_id+ )+ # Event service should not be called+ mock_event_service.count_events.assert_not_called()++ async def test_batch_get_shared_events_returns_events_for_public_conversation(+ self,+ aws_shared_event_service,+ mock_shared_conversation_info_service,+ mock_event_service,+ sample_public_conversation,+ sample_event,+ ):+ """Test that batch_get_shared_events returns events for a public conversation."""+ conversation_id = sample_public_conversation.id+ event_ids = [uuid4() for _ in range(3)]++ # Mock get_event_service to return our mock event service+ aws_shared_event_service.get_event_service = AsyncMock(+ return_value=mock_event_service+ )++ # Mock the event service to return events+ mock_event_service.get_event.return_value = sample_event++ # Call the method+ results = await aws_shared_event_service.batch_get_shared_events(+ conversation_id, event_ids+ )++ # Verify the results+ assert len(results) == 3+ assert all(result == sample_event for result in results)+++class TestAwsSharedEventServiceGetEventService:+ """Test cases for AwsSharedEventService.get_event_service method."""++ async def test_get_event_service_returns_event_service_for_shared_conversation(+ self,+ aws_shared_event_service,+ mock_shared_conversation_info_service,+ sample_public_conversation,+ ):+ """Test that get_event_service returns an EventService for a shared conversation."""+ conversation_id = sample_public_conversation.id++ # Mock the shared conversation info service to return a shared conversation+ mock_shared_conversation_info_service.get_shared_conversation_info.return_value = sample_public_conversation++ # Call the method+ result = await aws_shared_event_service.get_event_service(conversation_id)++ # Verify the result+ assert result is not None+ mock_shared_conversation_info_service.get_shared_conversation_info.assert_called_once_with(+ conversation_id+ )++ async def test_get_event_service_returns_none_for_non_shared_conversation(+ self,+ aws_shared_event_service,+ mock_shared_conversation_info_service,+ ):+ """Test that get_event_service returns None for a non-shared conversation."""+ conversation_id = uuid4()++ # Mock the shared conversation info service to return None+ mock_shared_conversation_info_service.get_shared_conversation_info.return_value = None++ # Call the method+ result = await aws_shared_event_service.get_event_service(conversation_id)++ # Verify the result+ assert result is None+ mock_shared_conversation_info_service.get_shared_conversation_info.assert_called_once_with(+ conversation_id+ )+++class TestAwsSharedEventServiceInjector:+ """Test cases for AwsSharedEventServiceInjector."""++ def test_bucket_name_from_environment_variable(self):+ """Test that bucket_name is read from FILE_STORE_PATH environment variable."""+ test_bucket_name = 'test-bucket-name'+ with patch.dict(os.environ, {'FILE_STORE_PATH': test_bucket_name}):+ # Create a new injector instance to pick up the environment variable+ # Note: The class attribute is evaluated at class definition time,+ # so we need to test that the attribute exists and can be overridden+ injector = AwsSharedEventServiceInjector()+ injector.bucket_name = os.environ.get('FILE_STORE_PATH')+ assert injector.bucket_name == test_bucket_name++ def test_bucket_name_default_value_when_env_not_set(self):+ """Test that bucket_name is None when FILE_STORE_PATH is not set."""+ with patch.dict(os.environ, {}, clear=True):+ # Remove FILE_STORE_PATH if it exists+ os.environ.pop('FILE_STORE_PATH', None)+ injector = AwsSharedEventServiceInjector()+ # The bucket_name will be whatever was set at class definition time+ # or None if FILE_STORE_PATH was not set when the class was defined+ assert hasattr(injector, 'bucket_name')++ async def test_injector_yields_aws_shared_event_service(self):+ """Test that the injector yields an AwsSharedEventService instance."""+ mock_state = MagicMock()+ mock_request = MagicMock()+ mock_db_session = AsyncMock()++ # Create the injector+ injector = AwsSharedEventServiceInjector()+ injector.bucket_name = 'test-bucket'++ # Mock the get_db_session context manager+ mock_db_context = AsyncMock()+ mock_db_context.__aenter__.return_value = mock_db_session+ mock_db_context.__aexit__.return_value = None++ # Mock boto3.client+ mock_s3_client = MagicMock()++ with (+ patch(+ 'server.sharing.aws_shared_event_service.boto3.client',+ return_value=mock_s3_client,+ ),+ patch(+ 'openhands.app_server.config.get_db_session',+ return_value=mock_db_context,+ ),+ ):+ # Call the inject method+ async for service in injector.inject(mock_state, mock_request):+ # Verify the service is an instance of AwsSharedEventService+ assert isinstance(service, AwsSharedEventService)+ assert service.s3_client == mock_s3_client+ assert service.bucket_name == 'test-bucket'++ async def test_injector_uses_bucket_name_from_instance(self):+ """Test that the injector uses the bucket_name from the instance."""+ mock_state = MagicMock()+ mock_request = MagicMock()+ mock_db_session = AsyncMock()++ # Create the injector with a specific bucket name+ injector = AwsSharedEventServiceInjector()+ injector.bucket_name = 'my-custom-bucket'++ # Mock the get_db_session context manager+ mock_db_context = AsyncMock()+ mock_db_context.__aenter__.return_value = mock_db_session+ mock_db_context.__aexit__.return_value = None++ # Mock boto3.client+ mock_s3_client = MagicMock()++ with (+ patch(+ 'server.sharing.aws_shared_event_service.boto3.client',+ return_value=mock_s3_client,+ ),+ patch(+ 'openhands.app_server.config.get_db_session',+ return_value=mock_db_context,+ ),+ ):+ # Call the inject method+ async for service in injector.inject(mock_state, mock_request):+ assert service.bucket_name == 'my-custom-bucket'++ async def test_injector_creates_sql_shared_conversation_info_service(self):+ """Test that the injector creates SQLSharedConversationInfoService with db_session."""+ mock_state = MagicMock()+ mock_request = MagicMock()+ mock_db_session = AsyncMock()++ # Create the injector+ injector = AwsSharedEventServiceInjector()+ injector.bucket_name = 'test-bucket'++ # Mock the get_db_session context manager+ mock_db_context = AsyncMock()+ mock_db_context.__aenter__.return_value = mock_db_session+ mock_db_context.__aexit__.return_value = None++ # Mock boto3.client+ mock_s3_client = MagicMock()++ with (+ patch(+ 'server.sharing.aws_shared_event_service.boto3.client',+ return_value=mock_s3_client,+ ),+ patch(+ 'openhands.app_server.config.get_db_session',+ return_value=mock_db_context,+ ),+ patch(+ 'server.sharing.aws_shared_event_service.SQLSharedConversationInfoService'+ ) as mock_sql_service_class,+ ):+ mock_sql_service = MagicMock()+ mock_sql_service_class.return_value = mock_sql_service++ # Call the inject method+ async for service in injector.inject(mock_state, mock_request):+ # Verify the service has the correct shared_conversation_info_service+ assert service.shared_conversation_info_service == mock_sql_service++ # Verify SQLSharedConversationInfoService was created with db_session+ mock_sql_service_class.assert_called_once_with(db_session=mock_db_session)++ async def test_injector_works_without_request(self):+ """Test that the injector works when request is None."""+ mock_state = MagicMock()+ mock_db_session = AsyncMock()++ # Create the injector+ injector = AwsSharedEventServiceInjector()+ injector.bucket_name = 'test-bucket'++ # Mock the get_db_session context manager+ mock_db_context = AsyncMock()+ mock_db_context.__aenter__.return_value = mock_db_session+ mock_db_context.__aexit__.return_value = None++ # Mock boto3.client+ mock_s3_client = MagicMock()++ with (+ patch(+ 'server.sharing.aws_shared_event_service.boto3.client',+ return_value=mock_s3_client,+ ),+ patch(+ 'openhands.app_server.config.get_db_session',+ return_value=mock_db_context,+ ),+ ):+ # Call the inject method with request=None+ async for service in injector.inject(mock_state, request=None):+ assert isinstance(service, AwsSharedEventService)++ async def test_injector_uses_role_based_authentication(self):+ """Test that the injector uses role-based authentication (no explicit credentials)."""+ mock_state = MagicMock()+ mock_request = MagicMock()+ mock_db_session = AsyncMock()++ # Create the injector+ injector = AwsSharedEventServiceInjector()+ injector.bucket_name = 'test-bucket'++ # Mock the get_db_session context manager+ mock_db_context = AsyncMock()+ mock_db_context.__aenter__.return_value = mock_db_session+ mock_db_context.__aexit__.return_value = None++ # Mock boto3.client+ mock_s3_client = MagicMock()++ with (+ patch(+ 'server.sharing.aws_shared_event_service.boto3.client',+ return_value=mock_s3_client,+ ) as mock_boto3_client,+ patch(+ 'openhands.app_server.config.get_db_session',+ return_value=mock_db_context,+ ),+ patch.dict(os.environ, {'AWS_S3_ENDPOINT': 'https://s3.example.com'}),+ ):+ # Call the inject method+ async for service in injector.inject(mock_state, mock_request):+ pass++ # Verify boto3.client was called with 's3' and endpoint_url+ # but without explicit credentials (role-based auth)+ mock_boto3_client.assert_called_once_with(+ 's3',+ endpoint_url='https://s3.example.com',+ )diff --git a/enterprise/tests/unit/test_sharing/test_shared_event_router.py b/enterprise/tests/unit/test_sharing/test_shared_event_router.pynew file mode 100644index 0000000000..3182a549af--- /dev/null+++ b/enterprise/tests/unit/test_sharing/test_shared_event_router.py@@ -0,0 +1,171 @@+"""Tests for shared_event_router provider selection.++This module tests the get_shared_event_service_injector function which+determines which SharedEventServiceInjector to use based on environment variables.+"""++import os+from unittest.mock import patch++from server.sharing.aws_shared_event_service import AwsSharedEventServiceInjector+from server.sharing.google_cloud_shared_event_service import (+ GoogleCloudSharedEventServiceInjector,+)+from server.sharing.shared_event_router import get_shared_event_service_injector+++class TestGetSharedEventServiceInjector:+ """Test cases for get_shared_event_service_injector function."""++ def test_defaults_to_google_cloud_when_no_env_set(self):+ """Test that GoogleCloudSharedEventServiceInjector is used when no env is set."""+ with patch.dict(+ os.environ,+ {},+ clear=True,+ ):+ os.environ.pop('SHARED_EVENT_STORAGE_PROVIDER', None)+ os.environ.pop('FILE_STORE', None)++ injector = get_shared_event_service_injector()++ assert isinstance(injector, GoogleCloudSharedEventServiceInjector)++ def test_uses_google_cloud_when_file_store_google_cloud(self):+ """Test that GoogleCloudSharedEventServiceInjector is used when FILE_STORE=google_cloud."""+ with patch.dict(+ os.environ,+ {+ 'FILE_STORE': 'google_cloud',+ },+ clear=True,+ ):+ os.environ.pop('SHARED_EVENT_STORAGE_PROVIDER', None)++ injector = get_shared_event_service_injector()++ assert isinstance(injector, GoogleCloudSharedEventServiceInjector)++ def test_uses_aws_when_provider_aws(self):+ """Test that AwsSharedEventServiceInjector is used when SHARED_EVENT_STORAGE_PROVIDER=aws."""+ with patch.dict(+ os.environ,+ {+ 'SHARED_EVENT_STORAGE_PROVIDER': 'aws',+ },+ clear=True,+ ):+ injector = get_shared_event_service_injector()++ assert isinstance(injector, AwsSharedEventServiceInjector)++ def test_uses_gcp_when_provider_gcp(self):+ """Test that GoogleCloudSharedEventServiceInjector is used when SHARED_EVENT_STORAGE_PROVIDER=gcp."""+ with patch.dict(+ os.environ,+ {+ 'SHARED_EVENT_STORAGE_PROVIDER': 'gcp',+ },+ clear=True,+ ):+ injector = get_shared_event_service_injector()++ assert isinstance(injector, GoogleCloudSharedEventServiceInjector)++ def test_uses_gcp_when_provider_google_cloud(self):+ """Test that GoogleCloudSharedEventServiceInjector is used when SHARED_EVENT_STORAGE_PROVIDER=google_cloud."""+ with patch.dict(+ os.environ,+ {+ 'SHARED_EVENT_STORAGE_PROVIDER': 'google_cloud',+ },+ clear=True,+ ):+ injector = get_shared_event_service_injector()++ assert isinstance(injector, GoogleCloudSharedEventServiceInjector)++ def test_provider_takes_precedence_over_file_store(self):+ """Test that SHARED_EVENT_STORAGE_PROVIDER takes precedence over FILE_STORE."""+ with patch.dict(+ os.environ,+ {+ 'SHARED_EVENT_STORAGE_PROVIDER': 'aws',+ 'FILE_STORE': 'google_cloud',+ },+ clear=True,+ ):+ injector = get_shared_event_service_injector()++ # Should use AWS because SHARED_EVENT_STORAGE_PROVIDER takes precedence+ assert isinstance(injector, AwsSharedEventServiceInjector)++ def test_provider_gcp_takes_precedence_over_file_store_s3(self):+ """Test that SHARED_EVENT_STORAGE_PROVIDER=gcp takes precedence over FILE_STORE=s3."""+ with patch.dict(+ os.environ,+ {+ 'SHARED_EVENT_STORAGE_PROVIDER': 'gcp',+ 'FILE_STORE': 's3',+ },+ clear=True,+ ):+ injector = get_shared_event_service_injector()++ # Should use GCP because SHARED_EVENT_STORAGE_PROVIDER takes precedence+ assert isinstance(injector, GoogleCloudSharedEventServiceInjector)++ def test_provider_is_case_insensitive_aws(self):+ """Test that SHARED_EVENT_STORAGE_PROVIDER is case insensitive for AWS."""+ with patch.dict(+ os.environ,+ {+ 'SHARED_EVENT_STORAGE_PROVIDER': 'AWS',+ },+ clear=True,+ ):+ injector = get_shared_event_service_injector()++ assert isinstance(injector, AwsSharedEventServiceInjector)++ def test_provider_is_case_insensitive_gcp(self):+ """Test that SHARED_EVENT_STORAGE_PROVIDER is case insensitive for GCP."""+ with patch.dict(+ os.environ,+ {+ 'SHARED_EVENT_STORAGE_PROVIDER': 'GCP',+ },+ clear=True,+ ):+ injector = get_shared_event_service_injector()++ assert isinstance(injector, GoogleCloudSharedEventServiceInjector)++ def test_unknown_provider_defaults_to_google_cloud(self):+ """Test that unknown provider defaults to GoogleCloudSharedEventServiceInjector."""+ with patch.dict(+ os.environ,+ {+ 'SHARED_EVENT_STORAGE_PROVIDER': 'unknown_provider',+ },+ clear=True,+ ):+ injector = get_shared_event_service_injector()++ # Should default to GCP for unknown providers+ assert isinstance(injector, GoogleCloudSharedEventServiceInjector)++ def test_empty_provider_falls_back_to_file_store(self):+ """Test that empty SHARED_EVENT_STORAGE_PROVIDER falls back to FILE_STORE."""+ with patch.dict(+ os.environ,+ {+ 'SHARED_EVENT_STORAGE_PROVIDER': '',+ 'FILE_STORE': 'google_cloud',+ },+ clear=True,+ ):+ injector = get_shared_event_service_injector()++ # Should default to GCP for unknown providers+ assert isinstance(injector, GoogleCloudSharedEventServiceInjector)diff --git a/openhands/app_server/config.py b/openhands/app_server/config.pyindex 0cc42a471a..8c0ded6d2e 100644--- a/openhands/app_server/config.py+++ b/openhands/app_server/config.py@@ -56,6 +56,7 @@ from openhands.app_server.web_client.web_client_config_injector import ()from openhands.sdk.utils.models import OpenHandsModelfrom openhands.server.types import AppMode+from openhands.utils.environment import StorageProvider, get_storage_providerdef get_default_persistence_dir() -> Path:@@ -140,6 +141,9 @@ def config_from_env() -> AppServerConfig:from openhands.app_server.app_conversation.sql_app_conversation_start_task_service import ( # noqa: E501SQLAppConversationStartTaskServiceInjector,)+ from openhands.app_server.event.aws_event_service import (+ AwsEventServiceInjector,+ )from openhands.app_server.event.filesystem_event_service import (FilesystemEventServiceInjector,)@@ -174,8 +178,18 @@ def config_from_env() -> AppServerConfig:config: AppServerConfig = from_env(AppServerConfig, 'OH') # type: ignoreif config.event is None:- if os.environ.get('FILE_STORE') == 'google_cloud':- # Legacy V0 google cloud storage configuration+ provider = get_storage_provider()++ if provider == StorageProvider.AWS:+ # AWS S3 storage configuration+ bucket_name = os.environ.get('FILE_STORE_PATH')+ if not bucket_name:+ raise ValueError(+ 'FILE_STORE_PATH environment variable is required for S3 storage'+ )+ config.event = AwsEventServiceInjector(bucket_name=bucket_name)+ elif provider == StorageProvider.GCP:+ # Google Cloud storage configurationconfig.event = GoogleCloudEventServiceInjector(bucket_name=os.environ.get('FILE_STORE_PATH'))diff --git a/openhands/app_server/event/aws_event_service.py b/openhands/app_server/event/aws_event_service.pynew file mode 100644index 0000000000..fd6cf4017d--- /dev/null+++ b/openhands/app_server/event/aws_event_service.py@@ -0,0 +1,113 @@+"""AWS S3-based EventService implementation.++This implementation uses role-based authentication (no credentials needed).+"""++import json+import logging+import os+from dataclasses import dataclass+from pathlib import Path+from typing import Any, AsyncGenerator++import boto3+import botocore.exceptions+from fastapi import Request++from openhands.app_server.config import get_app_conversation_info_service+from openhands.app_server.event.event_service import EventService, EventServiceInjector+from openhands.app_server.event.event_service_base import EventServiceBase+from openhands.app_server.services.injector import InjectorState+from openhands.sdk import Event++_logger = logging.getLogger(__name__)+++@dataclass+class AwsEventService(EventServiceBase):+ """AWS S3-based implementation of EventService.++ Uses role-based authentication, so no explicit credentials are needed.+ """++ s3_client: Any+ bucket_name: str++ def _load_event(self, path: Path) -> Event | None:+ """Get the event at the path given."""+ try:+ response = self.s3_client.get_object(Bucket=self.bucket_name, Key=str(path))+ with response['Body'] as stream:+ json_data = stream.read().decode('utf-8')+ event = Event.model_validate_json(json_data)+ return event+ except botocore.exceptions.ClientError as e:+ if e.response['Error']['Code'] == 'NoSuchKey':+ return None+ _logger.exception(f'Error reading event from {path}')+ return None+ except Exception:+ _logger.exception(f'Error reading event from {path}')+ return None++ def _store_event(self, path: Path, event: Event):+ """Store the event given at the path given."""+ data = event.model_dump(mode='json')+ json_str = json.dumps(data, indent=2)+ self.s3_client.put_object(+ Bucket=self.bucket_name,+ Key=str(path),+ Body=json_str.encode('utf-8'),+ )++ def _search_paths(self, prefix: Path, page_id: str | None = None) -> list[Path]:+ """Search paths."""+ kwargs: dict[str, Any] = {+ 'Bucket': self.bucket_name,+ 'Prefix': str(prefix),+ }+ if page_id:+ kwargs['ContinuationToken'] = page_id++ response = self.s3_client.list_objects_v2(**kwargs)+ contents = response.get('Contents', [])+ paths = [Path(obj['Key']) for obj in contents]+ return paths+++class AwsEventServiceInjector(EventServiceInjector):+ bucket_name: str+ prefix: Path = Path('users')++ async def inject(+ self, state: InjectorState, request: Request | None = None+ ) -> AsyncGenerator[EventService, None]:+ from openhands.app_server.config import (+ get_user_context,+ )++ async with (+ get_user_context(state, request) as user_context,+ get_app_conversation_info_service(+ state, request+ ) as app_conversation_info_service,+ ):+ user_id = await user_context.get_user_id()++ bucket_name = self.bucket_name++ # Use role-based authentication - boto3 will automatically+ # use IAM role credentials when running in AWS+ s3_client = boto3.client(+ 's3',+ endpoint_url=os.getenv('AWS_S3_ENDPOINT'),+ )++ yield AwsEventService(+ prefix=self.prefix,+ user_id=user_id,+ app_conversation_info_service=app_conversation_info_service,+ s3_client=s3_client,+ bucket_name=bucket_name,+ app_conversation_info_load_tasks={},+ )diff --git a/openhands/utils/environment.py b/openhands/utils/environment.pyindex 140c1d385d..7c28bcfa89 100644--- a/openhands/utils/environment.py+++ b/openhands/utils/environment.py@@ -1,6 +1,7 @@from __future__ import annotationsimport os+from enum import Enumfrom functools import lru_cachefrom pathlib import Path@@ -9,6 +10,38 @@ _LEMONADE_PROVIDER_NAME = 'lemonade'_LEMONADE_MODEL_PREFIX = 'lemonade/'+class StorageProvider(str, Enum):+ """Storage provider types for event and shared event storage."""++ AWS = 'aws'+ GCP = 'gcp'+ FILESYSTEM = 'filesystem'+++def get_storage_provider() -> StorageProvider:+ """Get the storage provider based on environment variables.++ Determines the storage provider from environment configuration:+ - SHARED_EVENT_STORAGE_PROVIDER: Primary setting, supports 'aws', 'gcp', 'google_cloud'+ - FILE_STORE: Legacy fallback, supports 'google_cloud'++ Returns:+ StorageProvider: The configured storage provider (AWS, GCP, or FILESYSTEM)+ """+ provider = os.environ.get('SHARED_EVENT_STORAGE_PROVIDER', '').lower()++ # If not explicitly set, fall back to FILE_STORE+ if not provider:+ provider = os.environ.get('FILE_STORE', '').lower()++ if provider == 'aws':+ return StorageProvider.AWS+ elif provider in ('gcp', 'google_cloud'):+ return StorageProvider.GCP+ else:+ return StorageProvider.FILESYSTEM++@lru_cache(maxsize=1)def is_running_in_docker() -> bool:"""Best-effort detection for Docker containers."""diff --git a/tests/unit/app_server/test_aws_event_service.py b/tests/unit/app_server/test_aws_event_service.pynew file mode 100644index 0000000000..1b1f60e80b--- /dev/null+++ b/tests/unit/app_server/test_aws_event_service.py@@ -0,0 +1,213 @@+"""Tests for AwsEventService.++This module tests the AWS S3-based implementation of EventService,+focusing on search functionality and S3 operations.+"""++import json+from pathlib import Path+from unittest.mock import MagicMock+from uuid import uuid4++import botocore.exceptions+import pytest++from openhands.app_server.event.aws_event_service import (+ AwsEventService,+ AwsEventServiceInjector,+)+from openhands.sdk.event import PauseEvent, TokenEvent+++def mock_s3_client():+ """Create a mock S3 client."""+ return MagicMock()+++def service(mock_s3_client) -> AwsEventService:+ """Create an AwsEventService instance for testing."""+ return AwsEventService(+ prefix=Path('users'),+ user_id='test_user',+ app_conversation_info_service=None,+ s3_client=mock_s3_client,+ bucket_name='test-bucket',+ app_conversation_info_load_tasks={},+ )+++def service_no_user(mock_s3_client) -> AwsEventService:+ """Create an AwsEventService instance without user_id."""+ return AwsEventService(+ prefix=Path('users'),+ user_id=None,+ app_conversation_info_service=None,+ s3_client=mock_s3_client,+ bucket_name='test-bucket',+ app_conversation_info_load_tasks={},+ )+++def create_token_event() -> TokenEvent:+ """Helper to create a TokenEvent for testing."""+ return TokenEvent(+ source='agent', prompt_token_ids=[1, 2], response_token_ids=[3, 4]+ )+++def create_pause_event() -> PauseEvent:+ """Helper to create a PauseEvent for testing."""+ return PauseEvent(source='user')+++class TestAwsEventServiceLoadEvent:+ """Test cases for _load_event method."""++ def test_load_event_success(self, service: AwsEventService, mock_s3_client):+ """Test that _load_event successfully loads an event from S3."""+ event = create_token_event()+ json_data = event.model_dump_json()++ # Mock the S3 response+ mock_body = MagicMock()+ mock_body.read.return_value = json_data.encode('utf-8')+ mock_body.__enter__ = MagicMock(return_value=mock_body)+ mock_body.__exit__ = MagicMock(return_value=False)+ mock_s3_client.get_object.return_value = {'Body': mock_body}++ result = service._load_event(Path('some/path/event.json'))++ assert result is not None+ assert result.kind == 'TokenEvent'+ mock_s3_client.get_object.assert_called_once_with(+ Bucket='test-bucket', Key='some/path/event.json'+ )++ def test_load_event_not_found(self, service: AwsEventService, mock_s3_client):+ """Test that _load_event returns None when event doesn't exist."""+ error_response = {'Error': {'Code': 'NoSuchKey', 'Message': 'Not found'}}+ mock_s3_client.get_object.side_effect = botocore.exceptions.ClientError(+ error_response, 'GetObject'+ )++ result = service._load_event(Path('some/path/missing.json'))++ assert result is None++ def test_load_event_other_error(self, service: AwsEventService, mock_s3_client):+ """Test that _load_event returns None and logs error on other S3 errors."""+ error_response = {'Error': {'Code': 'AccessDenied', 'Message': 'Access denied'}}+ mock_s3_client.get_object.side_effect = botocore.exceptions.ClientError(+ error_response, 'GetObject'+ )++ result = service._load_event(Path('some/path/denied.json'))++ assert result is None+++class TestAwsEventServiceStoreEvent:+ """Test cases for _store_event method."""++ def test_store_event_success(self, service: AwsEventService, mock_s3_client):+ """Test that _store_event successfully stores an event to S3."""+ event = create_token_event()++ service._store_event(Path('some/path/event.json'), event)++ mock_s3_client.put_object.assert_called_once()+ call_args = mock_s3_client.put_object.call_args+ assert call_args.kwargs['Bucket'] == 'test-bucket'+ assert call_args.kwargs['Key'] == 'some/path/event.json'+ # Verify the body is valid JSON+ body = call_args.kwargs['Body'].decode('utf-8')+ data = json.loads(body)+ assert data['kind'] == 'TokenEvent'+++class TestAwsEventServiceSearchPaths:+ """Test cases for _search_paths method."""++ def test_search_paths_returns_paths(self, service: AwsEventService, mock_s3_client):+ """Test that _search_paths returns paths from S3."""+ mock_s3_client.list_objects_v2.return_value = {+ 'Contents': [+ {'Key': 'users/test_user/v1_conversations/abc123/event1.json'},+ {'Key': 'users/test_user/v1_conversations/abc123/event2.json'},+ ]+ }++ result = service._search_paths(Path('users/test_user/v1_conversations/abc123'))++ assert len(result) == 2+ assert result[0] == Path('users/test_user/v1_conversations/abc123/event1.json')+ assert result[1] == Path('users/test_user/v1_conversations/abc123/event2.json')++ def test_search_paths_empty_bucket(self, service: AwsEventService, mock_s3_client):+ """Test that _search_paths handles empty results."""+ mock_s3_client.list_objects_v2.return_value = {}++ result = service._search_paths(Path('users/test_user/v1_conversations/abc123'))++ assert len(result) == 0++ def test_search_paths_with_page_id(self, service: AwsEventService, mock_s3_client):+ """Test that _search_paths uses continuation token."""+ mock_s3_client.list_objects_v2.return_value = {+ 'Contents': [{'Key': 'event.json'}]+ }++ service._search_paths(Path('prefix'), page_id='continuation_token')++ mock_s3_client.list_objects_v2.assert_called_once_with(+ Bucket='test-bucket',+ Prefix='prefix',+ ContinuationToken='continuation_token',+ )+++class TestAwsEventServiceIntegration:+ """Integration tests for AwsEventService."""++ @pytest.mark.asyncio+ async def test_get_conversation_path_with_user_id(self, service: AwsEventService):+ """Test conversation path generation with user_id."""+ conversation_id = uuid4()++ path = await service.get_conversation_path(conversation_id)++ assert 'users' in str(path)+ assert 'test_user' in str(path)+ assert 'v1_conversations' in str(path)+ assert conversation_id.hex in str(path)++ @pytest.mark.asyncio+ async def test_get_conversation_path_without_user_id(+ self, service_no_user: AwsEventService+ ):+ """Test conversation path generation without user_id."""+ conversation_id = uuid4()++ path = await service_no_user.get_conversation_path(conversation_id)++ assert 'users' in str(path)+ assert 'test_user' not in str(path)+ assert 'v1_conversations' in str(path)+ assert conversation_id.hex in str(path)+++class TestAwsEventServiceInjector:+ """Test cases for AwsEventServiceInjector."""++ def test_injector_has_bucket_name(self):+ """Test that injector has bucket_name attribute."""+ injector = AwsEventServiceInjector(bucket_name='my-bucket')+ assert injector.bucket_name == 'my-bucket'++ def test_injector_has_default_prefix(self):+ """Test that injector has default prefix."""+ injector = AwsEventServiceInjector(bucket_name='my-bucket')+ assert injector.prefix == Path('users')diff --git a/tests/unit/app_server/test_config_event_service_selection.py b/tests/unit/app_server/test_config_event_service_selection.pynew file mode 100644index 0000000000..85362c9013--- /dev/null+++ b/tests/unit/app_server/test_config_event_service_selection.py@@ -0,0 +1,179 @@+"""Tests for config_from_env event service provider selection.++This module tests the event service provider selection logic in config_from_env,+which determines which EventServiceInjector to use based on environment variables.+"""++import os+from unittest.mock import patch++import pytest++# Note: We need to clear the global config cache before each test+# to ensure environment variable changes take effect++[email protected](autouse=True)+def reset_global_config():+ """Reset the global config before and after each test."""+ import openhands.app_server.config as config_module++ original_config = config_module._global_config+ config_module._global_config = None+ yield+ config_module._global_config = original_config+++def _get_clean_env():+ """Get a base environment dict with essential system vars preserved."""+ # Preserve essential system environment variables+ env = {}+ for key in ['PATH', 'HOME', 'PYTHONPATH', 'VIRTUAL_ENV', 'TMPDIR', 'TMP', 'TEMP']:+ if key in os.environ:+ env[key] = os.environ[key]+ return env+++class TestConfigFromEnvEventServiceSelection:+ """Test cases for event service provider selection in config_from_env."""++ def test_defaults_to_filesystem_when_no_env_set(self):+ """Test that FilesystemEventServiceInjector is used when no FILE_STORE is set."""+ from openhands.app_server.config import config_from_env+ from openhands.app_server.event.filesystem_event_service import (+ FilesystemEventServiceInjector,+ )++ env = _get_clean_env()+ with patch.dict(os.environ, env, clear=True):+ config = config_from_env()+ assert isinstance(config.event, FilesystemEventServiceInjector)++ def test_uses_google_cloud_when_file_store_google_cloud(self):+ """Test that GoogleCloudEventServiceInjector is used when FILE_STORE=google_cloud."""+ from openhands.app_server.config import config_from_env+ from openhands.app_server.event.google_cloud_event_service import (+ GoogleCloudEventServiceInjector,+ )++ env = _get_clean_env()+ env['FILE_STORE'] = 'google_cloud'+ env['FILE_STORE_PATH'] = 'test-gcp-bucket'++ with patch.dict(os.environ, env, clear=True):+ config = config_from_env()++ assert isinstance(config.event, GoogleCloudEventServiceInjector)+ assert config.event.bucket_name == 'test-gcp-bucket'++ def test_uses_gcp_when_provider_gcp(self):+ """Test that GoogleCloudEventServiceInjector is used when SHARED_EVENT_STORAGE_PROVIDER=gcp."""+ from openhands.app_server.config import config_from_env+ from openhands.app_server.event.google_cloud_event_service import (+ GoogleCloudEventServiceInjector,+ )++ env = _get_clean_env()+ env['SHARED_EVENT_STORAGE_PROVIDER'] = 'gcp'+ env['FILE_STORE_PATH'] = 'test-gcp-bucket'++ with patch.dict(os.environ, env, clear=True):+ config = config_from_env()+ assert isinstance(config.event, GoogleCloudEventServiceInjector)++ def test_uses_aws_when_provider_aws(self):+ """Test that AwsEventServiceInjector is used when SHARED_EVENT_STORAGE_PROVIDER=aws."""+ from openhands.app_server.config import config_from_env+ from openhands.app_server.event.aws_event_service import (+ AwsEventServiceInjector,+ )++ env = _get_clean_env()+ env['SHARED_EVENT_STORAGE_PROVIDER'] = 'aws'+ env['FILE_STORE_PATH'] = 'test-aws-bucket'++ with patch.dict(os.environ, env, clear=True):+ config = config_from_env()++ assert isinstance(config.event, AwsEventServiceInjector)+ assert config.event.bucket_name == 'test-aws-bucket'++ def test_aws_requires_file_store_path(self):+ """Test that AWS provider requires FILE_STORE_PATH to be set."""+ from openhands.app_server.config import config_from_env++ env = _get_clean_env()+ env['SHARED_EVENT_STORAGE_PROVIDER'] = 'aws'++ with patch.dict(os.environ, env, clear=True):+ with pytest.raises(ValueError) as exc_info:+ config_from_env()++ assert 'FILE_STORE_PATH' in str(exc_info.value)+ assert 'required' in str(exc_info.value).lower()++ def test_provider_takes_precedence_over_file_store(self):+ """Test that SHARED_EVENT_STORAGE_PROVIDER takes precedence over FILE_STORE."""+ from openhands.app_server.config import config_from_env+ from openhands.app_server.event.aws_event_service import (+ AwsEventServiceInjector,+ )++ env = _get_clean_env()+ env['SHARED_EVENT_STORAGE_PROVIDER'] = 'aws'+ env['FILE_STORE'] = 'google_cloud'+ env['FILE_STORE_PATH'] = 'test-bucket'++ with patch.dict(os.environ, env, clear=True):+ config = config_from_env()++ # Should use AWS because SHARED_EVENT_STORAGE_PROVIDER takes precedence+ assert isinstance(config.event, AwsEventServiceInjector)++ def test_provider_gcp_takes_precedence_over_file_store_s3(self):+ """Test that SHARED_EVENT_STORAGE_PROVIDER=gcp takes precedence over FILE_STORE=s3."""+ from openhands.app_server.config import config_from_env+ from openhands.app_server.event.google_cloud_event_service import (+ GoogleCloudEventServiceInjector,+ )++ env = _get_clean_env()+ env['SHARED_EVENT_STORAGE_PROVIDER'] = 'gcp'+ env['FILE_STORE'] = 's3'+ env['FILE_STORE_PATH'] = 'test-bucket'++ with patch.dict(os.environ, env, clear=True):+ config = config_from_env()++ # Should use GCP because SHARED_EVENT_STORAGE_PROVIDER takes precedence+ assert isinstance(config.event, GoogleCloudEventServiceInjector)++ def test_provider_is_case_insensitive(self):+ """Test that SHARED_EVENT_STORAGE_PROVIDER is case insensitive."""+ from openhands.app_server.config import config_from_env+ from openhands.app_server.event.aws_event_service import (+ AwsEventServiceInjector,+ )++ env = _get_clean_env()+ env['SHARED_EVENT_STORAGE_PROVIDER'] = 'AWS'+ env['FILE_STORE_PATH'] = 'test-bucket'++ with patch.dict(os.environ, env, clear=True):+ config = config_from_env()+ assert isinstance(config.event, AwsEventServiceInjector)++ def test_provider_gcp_is_case_insensitive(self):+ """Test that SHARED_EVENT_STORAGE_PROVIDER=GCP is case insensitive."""+ from openhands.app_server.config import config_from_env+ from openhands.app_server.event.google_cloud_event_service import (+ GoogleCloudEventServiceInjector,+ )++ env = _get_clean_env()+ env['SHARED_EVENT_STORAGE_PROVIDER'] = 'GCP'+ env['FILE_STORE_PATH'] = 'test-bucket'++ with patch.dict(os.environ, env, clear=True):+ config = config_from_env()+ assert isinstance(config.event, GoogleCloudEventServiceInjector)diff --git a/tests/unit/utils/test_environment.py b/tests/unit/utils/test_environment.pyindex 5c9bdc4111..45610ff61a 100644--- a/tests/unit/utils/test_environment.py+++ b/tests/unit/utils/test_environment.py@@ -1,6 +1,7 @@import pytestfrom openhands.utils import environment+from openhands.utils.environment import StorageProvider, get_storage_provider@pytest.fixture(autouse=True)@@ -30,3 +31,48 @@ def test_get_effective_base_url_non_lemonade(monkeypatch):base_url = 'https://api.example.com'result = environment.get_effective_llm_base_url('openai/gpt-4', base_url)assert result == base_url+++class TestGetStorageProvider:+ """Tests for get_storage_provider function."""++ def test_aws_from_shared_event_storage_provider(self, monkeypatch):+ monkeypatch.setenv('SHARED_EVENT_STORAGE_PROVIDER', 'aws')+ monkeypatch.delenv('FILE_STORE', raising=False)+ assert get_storage_provider() == StorageProvider.AWS++ def test_gcp_from_shared_event_storage_provider(self, monkeypatch):+ monkeypatch.setenv('SHARED_EVENT_STORAGE_PROVIDER', 'gcp')+ monkeypatch.delenv('FILE_STORE', raising=False)+ assert get_storage_provider() == StorageProvider.GCP++ def test_google_cloud_from_shared_event_storage_provider(self, monkeypatch):+ monkeypatch.setenv('SHARED_EVENT_STORAGE_PROVIDER', 'google_cloud')+ monkeypatch.delenv('FILE_STORE', raising=False)+ assert get_storage_provider() == StorageProvider.GCP++ def test_fallback_to_file_store_google_cloud(self, monkeypatch):+ monkeypatch.delenv('SHARED_EVENT_STORAGE_PROVIDER', raising=False)+ monkeypatch.setenv('FILE_STORE', 'google_cloud')+ assert get_storage_provider() == StorageProvider.GCP++ def test_filesystem_when_no_provider_set(self, monkeypatch):+ monkeypatch.delenv('SHARED_EVENT_STORAGE_PROVIDER', raising=False)+ monkeypatch.delenv('FILE_STORE', raising=False)+ assert get_storage_provider() == StorageProvider.FILESYSTEM++ def test_filesystem_for_unknown_provider(self, monkeypatch):+ monkeypatch.setenv('SHARED_EVENT_STORAGE_PROVIDER', 'unknown')+ assert get_storage_provider() == StorageProvider.FILESYSTEM++ def test_shared_event_storage_provider_takes_precedence(self, monkeypatch):+ monkeypatch.setenv('SHARED_EVENT_STORAGE_PROVIDER', 'aws')+ monkeypatch.setenv('FILE_STORE', 'google_cloud')+ assert get_storage_provider() == StorageProvider.AWS++ def test_case_insensitive(self, monkeypatch):+ monkeypatch.setenv('SHARED_EVENT_STORAGE_PROVIDER', 'AWS')+ assert get_storage_provider() == StorageProvider.AWS++ monkeypatch.setenv('SHARED_EVENT_STORAGE_PROVIDER', 'GCP')+ assert get_storage_provider() == StorageProvider.GCP