Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Add infinite scroll pagination and filesystem storage support to public share page (#13545)

Tim O'Farrell0fc4b0fb55ee
diff --git a/enterprise/server/sharing/filesystem_shared_event_service.py b/enterprise/server/sharing/filesystem_shared_event_service.py
new file mode 100644
index 0000000000..90b3a1f719
--- /dev/null
+++ b/enterprise/server/sharing/filesystem_shared_event_service.py
@@ -0,0 +1,143 @@
+"""Implementation of SharedEventService.
+
+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
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from datetime import datetime
+from pathlib import Path
+from typing import AsyncGenerator
+from uuid import UUID
+
+from fastapi import Request
+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.config import get_global_config
+from openhands.app_server.event.event_service import EventService
+from openhands.app_server.event.filesystem_event_service import FilesystemEventService
+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 FilesystemSharedEventService(SharedEventService):
+ """Implementation of SharedEventService that validates shared access."""
+
+ shared_conversation_info_service: SharedConversationInfoService
+ persistence_dir: Path
+
+ 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 FilesystemEventService(
+ prefix=self.persistence_dir,
+ 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 FilesystemSharedEventServiceInjector(SharedEventServiceInjector):
+ 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
+ )
+
+ service = FilesystemSharedEventService(
+ shared_conversation_info_service=shared_conversation_info_service,
+ persistence_dir=get_global_config().persistence_dir,
+ )
+ yield service
diff --git a/enterprise/server/sharing/shared_event_router.py b/enterprise/server/sharing/shared_event_router.py
index 2d8b500126..9ff6abaf67 100644
--- a/enterprise/server/sharing/shared_event_router.py
+++ b/enterprise/server/sharing/shared_event_router.py
@@ -33,6 +33,12 @@ def get_shared_event_service_injector() -> SharedEventServiceInjector:
)
return AwsSharedEventServiceInjector()
+ elif provider == StorageProvider.FILESYSTEM:
+ from server.sharing.filesystem_shared_event_service import (
+ FilesystemSharedEventServiceInjector,
+ )
+
+ return FilesystemSharedEventServiceInjector()
else:
# GCP is the default for shared events (including filesystem fallback)
from server.sharing.google_cloud_shared_event_service import (
diff --git a/enterprise/tests/unit/test_sharing/test_shared_event_router.py b/enterprise/tests/unit/test_sharing/test_shared_event_router.py
index 3182a549af..d31fce2b99 100644
--- a/enterprise/tests/unit/test_sharing/test_shared_event_router.py
+++ b/enterprise/tests/unit/test_sharing/test_shared_event_router.py
@@ -8,6 +8,9 @@ import os
from unittest.mock import patch
from server.sharing.aws_shared_event_service import AwsSharedEventServiceInjector
+from server.sharing.filesystem_shared_event_service import (
+ FilesystemSharedEventServiceInjector,
+)
from server.sharing.google_cloud_shared_event_service import (
GoogleCloudSharedEventServiceInjector,
)
@@ -17,8 +20,8 @@ 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."""
+ def test_defaults_to_filesystem_when_no_env_set(self):
+ """Test that FilesystemSharedEventServiceInjector is used when no env is set."""
with patch.dict(
os.environ,
{},
@@ -29,7 +32,8 @@ class TestGetSharedEventServiceInjector:
injector = get_shared_event_service_injector()
- assert isinstance(injector, GoogleCloudSharedEventServiceInjector)
+ # Default behavior is filesystem storage when nothing is configured
+ assert isinstance(injector, FilesystemSharedEventServiceInjector)
def test_uses_google_cloud_when_file_store_google_cloud(self):
"""Test that GoogleCloudSharedEventServiceInjector is used when FILE_STORE=google_cloud."""
@@ -141,8 +145,8 @@ class TestGetSharedEventServiceInjector:
assert isinstance(injector, GoogleCloudSharedEventServiceInjector)
- def test_unknown_provider_defaults_to_google_cloud(self):
- """Test that unknown provider defaults to GoogleCloudSharedEventServiceInjector."""
+ def test_unknown_provider_defaults_to_filesystem(self):
+ """Test that unknown provider defaults to FilesystemSharedEventServiceInjector."""
with patch.dict(
os.environ,
{
@@ -152,11 +156,11 @@ class TestGetSharedEventServiceInjector:
):
injector = get_shared_event_service_injector()
- # Should default to GCP for unknown providers
- assert isinstance(injector, GoogleCloudSharedEventServiceInjector)
+ # Should default to filesystem for unknown providers
+ assert isinstance(injector, FilesystemSharedEventServiceInjector)
- def test_empty_provider_falls_back_to_file_store(self):
- """Test that empty SHARED_EVENT_STORAGE_PROVIDER falls back to FILE_STORE."""
+ def test_empty_provider_falls_back_to_file_store_gcp(self):
+ """Test that empty SHARED_EVENT_STORAGE_PROVIDER falls back to FILE_STORE=google_cloud."""
with patch.dict(
os.environ,
{
@@ -167,5 +171,35 @@ class TestGetSharedEventServiceInjector:
):
injector = get_shared_event_service_injector()
- # Should default to GCP for unknown providers
+ # Should use GCP when FILE_STORE=google_cloud
assert isinstance(injector, GoogleCloudSharedEventServiceInjector)
+
+ def test_empty_provider_falls_back_to_file_store_s3(self):
+ """Test that empty SHARED_EVENT_STORAGE_PROVIDER falls back to FILE_STORE=s3."""
+ with patch.dict(
+ os.environ,
+ {
+ 'SHARED_EVENT_STORAGE_PROVIDER': '',
+ 'FILE_STORE': 's3',
+ },
+ clear=True,
+ ):
+ injector = get_shared_event_service_injector()
+
+ # Should use AWS when FILE_STORE=s3
+ assert isinstance(injector, AwsSharedEventServiceInjector)
+
+ def test_empty_provider_falls_back_to_file_store_filesystem(self):
+ """Test that empty SHARED_EVENT_STORAGE_PROVIDER falls back to FILE_STORE=filesystem."""
+ with patch.dict(
+ os.environ,
+ {
+ 'SHARED_EVENT_STORAGE_PROVIDER': '',
+ 'FILE_STORE': 'filesystem',
+ },
+ clear=True,
+ ):
+ injector = get_shared_event_service_injector()
+
+ # Should use filesystem when FILE_STORE=filesystem
+ assert isinstance(injector, FilesystemSharedEventServiceInjector)
diff --git a/frontend/src/hooks/query/use-shared-conversation-events.ts b/frontend/src/hooks/query/use-shared-conversation-events.ts
index 10c3379783..9adcc15ce1 100644
--- a/frontend/src/hooks/query/use-shared-conversation-events.ts
+++ b/frontend/src/hooks/query/use-shared-conversation-events.ts
@@ -1,17 +1,21 @@
-import { useQuery } from "@tanstack/react-query";
+import { useInfiniteQuery } from "@tanstack/react-query";
import { sharedConversationService } from "#/api/shared-conversation-service.api";
export const useSharedConversationEvents = (conversationId?: string) =>
- useQuery({
+ useInfiniteQuery({
queryKey: ["shared-conversation-events", conversationId],
- queryFn: () => {
+ queryFn: ({ pageParam }) => {
if (!conversationId) {
throw new Error("Conversation ID is required");
}
return sharedConversationService.getSharedConversationEvents(
conversationId,
+ 100,
+ pageParam,
);
},
+ initialPageParam: undefined as string | undefined,
+ getNextPageParam: (lastPage) => lastPage.next_page_id ?? undefined,
enabled: !!conversationId,
retry: false, // Don't retry for shared conversations
});
diff --git a/frontend/src/routes/shared-conversation.tsx b/frontend/src/routes/shared-conversation.tsx
index f21f144226..eaa7477f1e 100644
--- a/frontend/src/routes/shared-conversation.tsx
+++ b/frontend/src/routes/shared-conversation.tsx
@@ -10,6 +10,7 @@ import { LoadingSpinner } from "#/components/shared/loading-spinner";
import { handleEventForUI } from "#/utils/handle-event-for-ui";
import { OpenHandsEvent } from "#/types/v1/core";
import OpenHandsLogo from "#/assets/branding/openhands-logo.svg?react";
+import { useInfiniteScroll } from "#/hooks/use-infinite-scroll";
export default function SharedConversation() {
const { t } = useTranslation();
@@ -24,13 +25,19 @@ export default function SharedConversation() {
data: eventsData,
isLoading: isLoadingEvents,
error: eventsError,
+ hasNextPage,
+ fetchNextPage,
+ isFetchingNextPage,
} = useSharedConversationEvents(conversationId);
const isLoading = isLoadingConversation || isLoadingEvents;
const error = conversationError || eventsError;
- // Transform shared events to V1 format
- const v1Events = eventsData?.items || [];
+ // Flatten all pages of events into a single array
+ const v1Events = React.useMemo(() => {
+ if (!eventsData?.pages) return [];
+ return eventsData.pages.flatMap((page) => page.items);
+ }, [eventsData?.pages]);
// Reconstruct the same UI event stream used in live conversations so
// completed tool calls render as a single action/observation unit.
@@ -44,6 +51,13 @@ export default function SharedConversation() {
[v1Events],
);
+ // Set up infinite scroll to load more events when user scrolls to bottom
+ const scrollContainerRef = useInfiniteScroll({
+ hasNextPage: !!hasNextPage,
+ isFetchingNextPage,
+ fetchNextPage,
+ });
+
if (isLoading) {
return (
<div className="flex items-center justify-center h-screen bg-neutral-900">
@@ -98,7 +112,10 @@ export default function SharedConversation() {
</div>
{/* Chat panel - read-only */}
- <div className="flex-1 overflow-y-auto custom-scrollbar-always px-4 pt-4 gap-2">
+ <div
+ ref={scrollContainerRef}
+ className="flex-1 overflow-y-auto custom-scrollbar-always px-4 pt-4 gap-2"
+ >
<div className="max-w-4xl mx-auto p-4 border border-neutral-700 rounded">
{renderableEvents.length > 0 ? (
<V1Messages messages={renderableEvents} allEvents={v1Events} />
@@ -109,6 +126,11 @@ export default function SharedConversation() {
</div>
</div>
)}
+ {isFetchingNextPage && (
+ <div className="flex justify-center py-4">
+ <LoadingSpinner size="small" />
+ </div>
+ )}
</div>
</div>
</div>
diff --git a/openhands/app_server/event/filesystem_event_service.py b/openhands/app_server/event/filesystem_event_service.py
index 69af0841c7..3dcb687b4b 100644
--- a/openhands/app_server/event/filesystem_event_service.py
+++ b/openhands/app_server/event/filesystem_event_service.py
@@ -26,7 +26,8 @@ class FilesystemEventService(EventServiceBase):
content = Event.model_validate_json(content)
return content
except Exception:
- _logger.exception('Error reading event', stack_info=True)
+ if path.exists():
+ _logger.exception('Error reading event', stack_info=True)
return None
def _store_event(self, path: Path, event: Event):
diff --git a/openhands/utils/environment.py b/openhands/utils/environment.py
index 7c28bcfa89..9c534b41dd 100644
--- a/openhands/utils/environment.py
+++ b/openhands/utils/environment.py
@@ -22,8 +22,8 @@ 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'
+ - SHARED_EVENT_STORAGE_PROVIDER: Primary setting, supports 'aws', 's3', 'gcp', 'google_cloud'
+ - FILE_STORE: Legacy fallback, supports 'google_cloud', 's3', 'filesystem'
Returns:
StorageProvider: The configured storage provider (AWS, GCP, or FILESYSTEM)
@@ -34,7 +34,7 @@ def get_storage_provider() -> StorageProvider:
if not provider:
provider = os.environ.get('FILE_STORE', '').lower()
- if provider == 'aws':
+ if provider in ('aws', 's3'):
return StorageProvider.AWS
elif provider in ('gcp', 'google_cloud'):
return StorageProvider.GCP