Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Remove openhands.server.conversation_manager package (V0 to V1 migration) (#14034)

Tim O'Farrell13e9d7584ac1
diff --git a/enterprise/integrations/github/github_manager.py b/enterprise/integrations/github/github_manager.py
index 387dd29a56..93c3588d16 100644
--- a/enterprise/integrations/github/github_manager.py
+++ b/enterprise/integrations/github/github_manager.py
@@ -32,7 +32,6 @@ from pydantic import SecretStr
from server.auth.auth_error import ExpiredError
from server.auth.constants import GITHUB_APP_CLIENT_ID, GITHUB_APP_PRIVATE_KEY
from server.auth.token_manager import TokenManager
-from server.utils.conversation_callback_utils import register_callback_processor
from openhands.core.logger import openhands_logger as logger
from openhands.integrations.provider import ProviderToken, ProviderType
@@ -318,17 +317,12 @@ class GithubManager(Manager[GithubViewType]):
return
async def start_job(self, github_view: GithubViewType) -> None:
- """Kick off a job with openhands agent.
+ """Kick off a job with openhands agent using V1 app conversation system.
1. Get user credential
2. Initialize new conversation with repo
3. Save interaction data
"""
- # Importing here prevents circular import
- from server.conversation_callback_processor.github_callback_processor import (
- GithubCallbackProcessor,
- )
-
try:
msg_info: str = ''
@@ -402,19 +396,7 @@ class GithubManager(Manager[GithubViewType]):
f'[GitHub] Created conversation {conversation_id} for user {user_info.username}'
)
- if not github_view.v1_enabled:
- # Create a GithubCallbackProcessor
- processor = GithubCallbackProcessor(
- github_view=github_view,
- send_summary_instruction=True,
- )
-
- # Register the callback processor
- register_callback_processor(conversation_id, processor)
-
- logger.info(
- f'[Github] Registered callback processor for conversation {conversation_id}'
- )
+ # V1 callback processors are registered by the view during conversation creation
# Send message with conversation link
conversation_link = CONVERSATION_URL.format(conversation_id)
diff --git a/enterprise/integrations/github/github_view.py b/enterprise/integrations/github/github_view.py
index ba439c0d9a..656c26586a 100644
--- a/enterprise/integrations/github/github_view.py
+++ b/enterprise/integrations/github/github_view.py
@@ -43,7 +43,6 @@ from openhands.integrations.github.github_service import GithubServiceImpl
from openhands.integrations.provider import PROVIDER_TOKEN_TYPE, ProviderType
from openhands.integrations.service_types import Comment
from openhands.sdk import TextContent
-from openhands.server.services.conversation_service import start_conversation
from openhands.server.user_auth.user_auth import UserAuth
from openhands.storage.data_models.conversation_metadata import (
ConversationMetadata,
@@ -209,43 +208,9 @@ class GithubIssue(ResolverViewInterface):
conversation_metadata: ConversationMetadata,
saas_user_auth: UserAuth,
):
- logger.info(
- f'[GitHub V1]: User flag found for {self.user_info.keycloak_user_id} is {self.v1_enabled}'
- )
- if self.v1_enabled:
- # Use V1 app conversation service
- await self._create_v1_conversation(
- jinja_env, saas_user_auth, conversation_metadata
- )
- else:
- await self._create_v0_conversation(
- jinja_env, git_provider_tokens, conversation_metadata
- )
-
- async def _create_v0_conversation(
- self,
- jinja_env: Environment,
- git_provider_tokens: PROVIDER_TOKEN_TYPE,
- conversation_metadata: ConversationMetadata,
- ):
- """Create conversation using the legacy V0 system."""
- logger.info('[GitHub]: Creating V0 conversation')
- custom_secrets = await self._get_user_secrets()
-
- user_instructions, conversation_instructions = await self._get_instructions(
- jinja_env
- )
-
- await start_conversation(
- user_id=self.user_info.keycloak_user_id,
- git_provider_tokens=git_provider_tokens,
- custom_secrets=custom_secrets,
- initial_user_msg=user_instructions,
- image_urls=None,
- replay_json=None,
- conversation_id=conversation_metadata.conversation_id,
- conversation_metadata=conversation_metadata,
- conversation_instructions=conversation_instructions,
+ # V0 conversation path has been removed - all conversations use V1 app conversation service
+ await self._create_v1_conversation(
+ jinja_env, saas_user_auth, conversation_metadata
)
async def _get_v1_initial_user_message(self, jinja_env: Environment) -> str:
@@ -258,7 +223,6 @@ class GithubIssue(ResolverViewInterface):
comments, inline review comments) override this method to control ordering
(e.g., context first, then the triggering comment, then previous comments).
"""
-
user_instructions, conversation_instructions = await self._get_instructions(
jinja_env
)
diff --git a/enterprise/integrations/gitlab/gitlab_manager.py b/enterprise/integrations/gitlab/gitlab_manager.py
index c3641c6cc9..dd520aa221 100644
--- a/enterprise/integrations/gitlab/gitlab_manager.py
+++ b/enterprise/integrations/gitlab/gitlab_manager.py
@@ -24,7 +24,6 @@ from integrations.v1_utils import get_saas_user_auth
from jinja2 import Environment, FileSystemLoader
from pydantic import SecretStr
from server.auth.token_manager import TokenManager
-from server.utils.conversation_callback_utils import register_callback_processor
from openhands.core.logger import openhands_logger as logger
from openhands.integrations.gitlab.gitlab_service import GitLabServiceImpl
@@ -171,17 +170,11 @@ class GitlabManager(Manager[GitlabViewType]):
)
async def start_job(self, gitlab_view: GitlabViewType) -> None:
- """
- Start a job for the GitLab view.
+ """Start a job for the GitLab view using V1 app conversation system.
Args:
gitlab_view: The GitLab view object containing issue/PR/comment info
"""
- # Importing here prevents circular import
- from server.conversation_callback_processor.gitlab_callback_processor import (
- GitlabCallbackProcessor,
- )
-
try:
try:
user_info = gitlab_view.user_info
@@ -235,19 +228,7 @@ class GitlabManager(Manager[GitlabViewType]):
f'[GitLab] Created conversation {conversation_id} for user {user_info.username}'
)
- if not gitlab_view.v1_enabled:
- # Create a GitlabCallbackProcessor for this conversation
- processor = GitlabCallbackProcessor(
- gitlab_view=gitlab_view,
- send_summary_instruction=True,
- )
-
- # Register the callback processor
- register_callback_processor(conversation_id, processor)
-
- logger.info(
- f'[GitLab] Created callback processor for conversation {conversation_id}'
- )
+ # V1 callback processors are registered by the view during conversation creation
conversation_link = CONVERSATION_URL.format(conversation_id)
msg_info = f"I'm on it! {user_info.username} can [track my progress at all-hands.dev]({conversation_link})"
diff --git a/enterprise/integrations/gitlab/gitlab_view.py b/enterprise/integrations/gitlab/gitlab_view.py
index 59222484a6..b1c6d79443 100644
--- a/enterprise/integrations/gitlab/gitlab_view.py
+++ b/enterprise/integrations/gitlab/gitlab_view.py
@@ -31,7 +31,6 @@ from openhands.integrations.gitlab.gitlab_service import GitLabServiceImpl
from openhands.integrations.provider import PROVIDER_TOKEN_TYPE, ProviderType
from openhands.integrations.service_types import Comment
from openhands.sdk import TextContent
-from openhands.server.services.conversation_service import start_conversation
from openhands.server.user_auth.user_auth import UserAuth
from openhands.storage.data_models.conversation_metadata import (
ConversationMetadata,
@@ -167,41 +166,9 @@ class GitlabIssue(ResolverViewInterface):
conversation_metadata: ConversationMetadata,
saas_user_auth: UserAuth,
):
- # v1_enabled is already set at construction time in the factory method
- if self.v1_enabled:
- # Use V1 app conversation service
- await self._create_v1_conversation(
- jinja_env, saas_user_auth, conversation_metadata
- )
- else:
- await self._create_v0_conversation(
- jinja_env, git_provider_tokens, conversation_metadata
- )
-
- async def _create_v0_conversation(
- self,
- jinja_env: Environment,
- git_provider_tokens: PROVIDER_TOKEN_TYPE,
- conversation_metadata: ConversationMetadata,
- ):
- """Create conversation using the legacy V0 system."""
- logger.info('[GitLab]: Creating V0 conversation')
- custom_secrets = await self._get_user_secrets()
-
- user_instructions, conversation_instructions = await self._get_instructions(
- jinja_env
- )
-
- await start_conversation(
- user_id=self.user_info.keycloak_user_id,
- git_provider_tokens=git_provider_tokens,
- custom_secrets=custom_secrets,
- initial_user_msg=user_instructions,
- image_urls=None,
- replay_json=None,
- conversation_id=conversation_metadata.conversation_id,
- conversation_metadata=conversation_metadata,
- conversation_instructions=conversation_instructions,
+ # V0 conversation path has been removed - all conversations use V1 app conversation service
+ await self._create_v1_conversation(
+ jinja_env, saas_user_auth, conversation_metadata
)
async def _create_v1_conversation(
diff --git a/enterprise/integrations/jira_dc/jira_dc_manager.py b/enterprise/integrations/jira_dc/jira_dc_manager.py
index 4cc93cc98b..92975fc962 100644
--- a/enterprise/integrations/jira_dc/jira_dc_manager.py
+++ b/enterprise/integrations/jira_dc/jira_dc_manager.py
@@ -25,7 +25,6 @@ from integrations.utils import (
from jinja2 import Environment, FileSystemLoader
from server.auth.saas_user_auth import get_user_auth_from_keycloak_id
from server.auth.token_manager import TokenManager
-from server.utils.conversation_callback_utils import register_callback_processor
from storage.jira_dc_integration_store import JiraDcIntegrationStore
from storage.jira_dc_user import JiraDcUser
from storage.jira_dc_workspace import JiraDcWorkspace
@@ -355,12 +354,7 @@ class JiraDcManager(Manager[JiraDcViewInterface]):
return False
async def start_job(self, jira_dc_view: JiraDcViewInterface) -> None:
- """Start a Jira DC job/conversation."""
- # Import here to prevent circular import
- from server.conversation_callback_processor.jira_dc_callback_processor import (
- JiraDcCallbackProcessor,
- )
-
+ """Start a Jira DC job/conversation using V1 app conversation system."""
try:
user_info: JiraDcUser = jira_dc_view.jira_dc_user
logger.info(
@@ -368,7 +362,15 @@ class JiraDcManager(Manager[JiraDcViewInterface]):
f'issue {jira_dc_view.job_context.issue_key}',
)
- # Create conversation
+ # Set decrypted API key for new conversations (needed for V1 callback processor)
+ if isinstance(jira_dc_view, JiraDcNewConversationView):
+ api_key = self.token_manager.decrypt_text(
+ jira_dc_view.jira_dc_workspace.svc_acc_api_key
+ )
+ jira_dc_view._decrypted_api_key = api_key
+
+ # Create conversation using V1 app conversation system
+ # The callback processor is registered automatically by the view
conversation_id = await jira_dc_view.create_or_update_conversation(
self.jinja_env
)
@@ -377,21 +379,6 @@ class JiraDcManager(Manager[JiraDcViewInterface]):
f'[Jira DC] Created/Updated conversation {conversation_id} for issue {jira_dc_view.job_context.issue_key}'
)
- if isinstance(jira_dc_view, JiraDcNewConversationView):
- # Register callback processor for updates
- processor = JiraDcCallbackProcessor(
- issue_key=jira_dc_view.job_context.issue_key,
- workspace_name=jira_dc_view.jira_dc_workspace.name,
- base_api_url=jira_dc_view.job_context.base_api_url,
- )
-
- # Register the callback processor
- register_callback_processor(conversation_id, processor)
-
- logger.info(
- f'[Jira DC] Created callback processor for conversation {conversation_id}'
- )
-
# Send initial response
msg_info = jira_dc_view.get_response_msg()
diff --git a/enterprise/integrations/jira_dc/jira_dc_v1_callback_processor.py b/enterprise/integrations/jira_dc/jira_dc_v1_callback_processor.py
new file mode 100644
index 0000000000..a65ee933b1
--- /dev/null
+++ b/enterprise/integrations/jira_dc/jira_dc_v1_callback_processor.py
@@ -0,0 +1,243 @@
+"""Jira Data Center V1 callback processor.
+
+This processor handles events from V1 conversations and posts
+summaries back to Jira DC issues when the agent finishes work.
+"""
+
+import logging
+from uuid import UUID
+
+import httpx
+from integrations.utils import get_summary_instruction, markdown_to_jira_markup
+from pydantic import Field
+
+from openhands.agent_server.models import AskAgentRequest, AskAgentResponse
+from openhands.app_server.event_callback.event_callback_models import (
+ EventCallback,
+ EventCallbackProcessor,
+)
+from openhands.app_server.event_callback.event_callback_result_models import (
+ EventCallbackResult,
+ EventCallbackResultStatus,
+)
+from openhands.app_server.event_callback.util import (
+ ensure_conversation_found,
+ ensure_running_sandbox,
+ get_agent_server_url_from_sandbox,
+)
+from openhands.sdk import Event
+from openhands.sdk.event import ConversationStateUpdateEvent
+from openhands.utils.http_session import httpx_verify_option
+
+_logger = logging.getLogger(__name__)
+
+
+class JiraDcV1CallbackProcessor(EventCallbackProcessor):
+ """Callback processor for Jira Data Center V1 integrations."""
+
+ should_request_summary: bool = Field(default=True)
+ issue_key: str
+ workspace_name: str
+ base_api_url: str
+ svc_acc_api_key: str # Decrypted API key
+
+ async def __call__(
+ self,
+ conversation_id: UUID,
+ callback: EventCallback,
+ event: Event,
+ ) -> EventCallbackResult | None:
+ """Process events for Jira DC V1 integration."""
+ # Only handle ConversationStateUpdateEvent for execution_status
+ if not isinstance(event, ConversationStateUpdateEvent):
+ return None
+
+ if event.key != 'execution_status':
+ return None
+
+ _logger.info('[Jira DC] Callback agent state was %s', event)
+
+ # Only request summary when execution has finished successfully
+ if event.value != 'finished':
+ return None
+
+ _logger.info(
+ '[Jira DC] Should request summary: %s', self.should_request_summary
+ )
+
+ if not self.should_request_summary:
+ return None
+
+ self.should_request_summary = False
+
+ try:
+ _logger.info(f'[Jira DC] Requesting summary {conversation_id}')
+ summary = await self._request_summary(conversation_id)
+ _logger.info(
+ f'[Jira DC] Posting summary {conversation_id}',
+ extra={'summary': summary},
+ )
+ await self._post_summary_to_jira_dc(summary)
+
+ return EventCallbackResult(
+ status=EventCallbackResultStatus.SUCCESS,
+ event_callback_id=callback.id,
+ event_id=event.id,
+ conversation_id=conversation_id,
+ detail=summary,
+ )
+ except Exception as e:
+ _logger.exception(f'[Jira DC] Failed to post summary: {e}', stack_info=True)
+ return EventCallbackResult(
+ status=EventCallbackResultStatus.ERROR,
+ event_callback_id=callback.id,
+ event_id=event.id,
+ conversation_id=conversation_id,
+ detail=str(e),
+ )
+
+ async def _request_summary(self, conversation_id: UUID) -> str:
+ """Ask the agent to produce a summary of its work and return the agent response."""
+ # Import services within the method to avoid circular imports
+ from openhands.app_server.config import (
+ get_app_conversation_info_service,
+ get_httpx_client,
+ get_sandbox_service,
+ )
+ from openhands.app_server.services.injector import InjectorState
+ from openhands.app_server.user.specifiy_user_context import (
+ ADMIN,
+ USER_CONTEXT_ATTR,
+ )
+
+ # Create injector state for dependency injection
+ state = InjectorState()
+ setattr(state, USER_CONTEXT_ATTR, ADMIN)
+
+ async with (
+ get_app_conversation_info_service(state) as app_conversation_info_service,
+ get_sandbox_service(state) as sandbox_service,
+ get_httpx_client(state) as httpx_client,
+ ):
+ # 1. Conversation lookup
+ app_conversation_info = ensure_conversation_found(
+ await app_conversation_info_service.get_app_conversation_info(
+ conversation_id
+ ),
+ conversation_id,
+ )
+
+ # 2. Sandbox lookup + validation
+ sandbox = ensure_running_sandbox(
+ await sandbox_service.get_sandbox(app_conversation_info.sandbox_id),
+ app_conversation_info.sandbox_id,
+ )
+
+ assert (
+ sandbox.session_api_key is not None
+ ), f'No session API key for sandbox: {sandbox.id}'
+
+ # 3. URL + instruction
+ agent_server_url = get_agent_server_url_from_sandbox(sandbox)
+
+ # Prepare message based on agent state
+ message_content = get_summary_instruction()
+
+ # Ask the agent and return the response text
+ return await self._ask_question(
+ httpx_client=httpx_client,
+ agent_server_url=agent_server_url,
+ conversation_id=conversation_id,
+ session_api_key=sandbox.session_api_key,
+ message_content=message_content,
+ )
+
+ async def _ask_question(
+ self,
+ httpx_client: httpx.AsyncClient,
+ agent_server_url: str,
+ conversation_id: UUID,
+ session_api_key: str,
+ message_content: str,
+ ) -> str:
+ """Send a message to the agent server via the V1 API and return response text."""
+ send_message_request = AskAgentRequest(question=message_content)
+
+ url = (
+ f"{agent_server_url.rstrip('/')}"
+ f"/api/conversations/{conversation_id}/ask_agent"
+ )
+ headers = {'X-Session-API-Key': session_api_key}
+ payload = send_message_request.model_dump()
+
+ try:
+ response = await httpx_client.post(
+ url,
+ json=payload,
+ headers=headers,
+ timeout=30.0,
+ )
+ response.raise_for_status()
+
+ agent_response = AskAgentResponse.model_validate(response.json())
+ return agent_response.response
+
+ except httpx.HTTPStatusError as e:
+ error_detail = f'HTTP {e.response.status_code} error'
+ try:
+ error_body = e.response.text
+ if error_body:
+ error_detail += f': {error_body}'
+ except Exception:
+ pass
+
+ _logger.exception(
+ '[Jira DC] HTTP error sending message to %s: %s. '
+ 'Request payload: %s. Response headers: %s',
+ url,
+ error_detail,
+ payload,
+ dict(e.response.headers),
+ stack_info=True,
+ )
+ raise Exception(f'Failed to send message to agent server: {error_detail}')
+
+ except httpx.TimeoutException:
+ error_detail = f'Request timeout after 30 seconds to {url}'
+ _logger.exception(
+ '[Jira DC] Timeout error: %s. Request payload: %s',
+ error_detail,
+ payload,
+ stack_info=True,
+ )
+ raise Exception(f'Failed to send message to agent server: {error_detail}')
+
+ async def _post_summary_to_jira_dc(self, summary: str):
+ """Post the summary back to the Jira DC issue."""
+ if not all(
+ [
+ self.svc_acc_api_key,
+ self.issue_key,
+ self.base_api_url,
+ ]
+ ):
+ _logger.warning('[Jira DC] Missing required data for posting summary')
+ return
+
+ # Add a comment to the Jira DC issue with the summary
+ comment_url = f'{self.base_api_url}/rest/api/2/issue/{self.issue_key}/comment'
+
+ message = f'OpenHands resolved this issue:\n\n{summary}'
+ # Convert standard Markdown to Jira Wiki Markup for proper rendering
+ comment_body = {'body': markdown_to_jira_markup(message)}
+
+ headers = {'Authorization': f'Bearer {self.svc_acc_api_key}'}
+
+ async with httpx.AsyncClient(verify=httpx_verify_option()) as client:
+ response = await client.post(
+ comment_url,
+ headers=headers,
+ json=comment_body,
+ )
+ response.raise_for_status()
+ _logger.info(f'[Jira DC] Posted summary to {self.issue_key}')
diff --git a/enterprise/integrations/jira_dc/jira_dc_view.py b/enterprise/integrations/jira_dc/jira_dc_view.py
index 1364af4b6a..f6d32a18fd 100644
--- a/enterprise/integrations/jira_dc/jira_dc_view.py
+++ b/enterprise/integrations/jira_dc/jira_dc_view.py
@@ -1,34 +1,51 @@
-from dataclasses import dataclass
+"""Jira Data Center view implementations and factory.
+
+Views are responsible for:
+- Holding the webhook payload and auth context
+- Creating conversations using V1 app conversation system
+"""
+
+from dataclasses import dataclass, field
+from uuid import UUID, uuid4
from integrations.jira_dc.jira_dc_types import (
JiraDcViewInterface,
StartingConvoException,
)
+from integrations.jira_dc.jira_dc_v1_callback_processor import JiraDcV1CallbackProcessor
from integrations.models import JobContext
-from integrations.utils import CONVERSATION_URL, get_final_agent_observation
+from integrations.resolver_context import ResolverUserContext
+from integrations.resolver_org_router import resolve_org_for_repo
+from integrations.utils import CONVERSATION_URL
from jinja2 import Environment
from storage.jira_dc_conversation import JiraDcConversation
from storage.jira_dc_integration_store import JiraDcIntegrationStore
from storage.jira_dc_user import JiraDcUser
from storage.jira_dc_workspace import JiraDcWorkspace
-from openhands.core.logger import openhands_logger as logger
-from openhands.core.schema.agent import AgentState
-from openhands.events.action import MessageAction
-from openhands.events.serialization.event import event_to_dict
-from openhands.server.services.conversation_service import (
- create_new_conversation,
- setup_init_conversation_settings,
+from openhands.agent_server.models import SendMessageRequest
+from openhands.app_server.app_conversation.app_conversation_models import (
+ AppConversationStartRequest,
+ AppConversationStartTaskStatus,
)
-from openhands.server.shared import ConversationStoreImpl, config, conversation_manager
+from openhands.app_server.config import get_app_conversation_service
+from openhands.app_server.services.injector import InjectorState
+from openhands.app_server.user.specifiy_user_context import USER_CONTEXT_ATTR
+from openhands.core.logger import openhands_logger as logger
+from openhands.integrations.provider import ProviderHandler, ProviderType
+from openhands.sdk import TextContent
from openhands.server.user_auth.user_auth import UserAuth
-from openhands.storage.data_models.conversation_metadata import ConversationTrigger
+from openhands.storage.data_models.conversation_metadata import (
+ ConversationTrigger,
+)
integration_store = JiraDcIntegrationStore.get_instance()
@dataclass
class JiraDcNewConversationView(JiraDcViewInterface):
+ """View for creating a new Jira DC conversation."""
+
job_context: JobContext
saas_user_auth: UserAuth
jira_dc_user: JiraDcUser
@@ -36,9 +53,14 @@ class JiraDcNewConversationView(JiraDcViewInterface):
selected_repo: str | None
conversation_id: str
- async def _get_instructions(self, jinja_env: Environment) -> tuple[str, str]:
- """Instructions passed when conversation is first initialized"""
+ # Decrypted API key (set by manager)
+ _decrypted_api_key: str = field(default='', repr=False)
+ # Resolved org ID for V1 conversations
+ resolved_org_id: UUID | None = None
+
+ async def _get_instructions(self, jinja_env: Environment) -> tuple[str, str]:
+ """Instructions passed when conversation is first initialized."""
instructions_template = jinja_env.get_template('jira_dc_instructions.j2')
instructions = instructions_template.render()
@@ -54,58 +76,148 @@ class JiraDcNewConversationView(JiraDcViewInterface):
return instructions, user_msg
async def create_or_update_conversation(self, jinja_env: Environment) -> str:
- """Create a new Jira DC conversation"""
+ """Create a new Jira DC conversation using V1 app conversation system.
+ Returns:
+ The conversation ID
+
+ Raises:
+ StartingConvoException: If conversation creation fails
+ """
if not self.selected_repo:
raise StartingConvoException('No repository selected for this conversation')
- provider_tokens = await self.saas_user_auth.get_provider_tokens()
- user_secrets = await self.saas_user_auth.get_secrets()
+ # Generate conversation ID
+ self.conversation_id = uuid4().hex
+
+ # Save the JiraDC conversation mapping
+ jira_dc_conversation = JiraDcConversation(
+ conversation_id=self.conversation_id,
+ issue_id=self.job_context.issue_id,
+ issue_key=self.job_context.issue_key,
+ jira_dc_user_id=self.jira_dc_user.id,
+ )
+ await integration_store.create_conversation(jira_dc_conversation)
+
+ # Create V1 conversation
+ await self._create_v1_conversation(jinja_env)
+ return self.conversation_id
+
+ async def _create_v1_conversation(self, jinja_env: Environment):
+ """Create conversation using the V1 app conversation system."""
+ logger.info('[Jira DC]: Creating V1 conversation')
+
instructions, user_msg = await self._get_instructions(jinja_env)
- try:
- agent_loop_info = await create_new_conversation(
- user_id=self.jira_dc_user.keycloak_user_id,
- git_provider_tokens=provider_tokens,
- selected_repository=self.selected_repo,
- selected_branch=None,
- initial_user_msg=user_msg,
- conversation_instructions=instructions,
- image_urls=None,
- replay_json=None,
- conversation_trigger=ConversationTrigger.JIRA_DC,
- custom_secrets=user_secrets.custom_secrets if user_secrets else None,
- )
+ # Create the initial message request
+ initial_message = SendMessageRequest(
+ role='user', content=[TextContent(text=user_msg)]
+ )
+
+ # Create the Jira DC V1 callback processor
+ jira_dc_callback_processor = self._create_jira_dc_v1_callback_processor()
- self.conversation_id = agent_loop_info.conversation_id
+ # Resolve org ID for the V1 system
+ self.resolved_org_id = await self._get_resolved_org_id()
- logger.info(f'[Jira DC] Created conversation {self.conversation_id}')
+ # Determine git provider
+ git_provider = await self._get_git_provider()
+
+ injector_state = InjectorState()
+
+ # Create the V1 conversation start request
+ start_request = AppConversationStartRequest(
+ conversation_id=UUID(self.conversation_id),
+ system_message_suffix=instructions if instructions else None,
+ initial_message=initial_message,
+ selected_repository=self.selected_repo,
+ selected_branch=None,
+ git_provider=git_provider,
+ title=f'Jira DC Issue {self.job_context.issue_key}: {self.job_context.issue_title or "Unknown"}',
+ trigger=ConversationTrigger.JIRA,
+ processors=[jira_dc_callback_processor],
+ )
+
+ # Set up the Jira DC user context for the V1 system
+ jira_dc_user_context = ResolverUserContext(
+ saas_user_auth=self.saas_user_auth,
+ resolver_org_id=self.resolved_org_id,
+ )
+ setattr(injector_state, USER_CONTEXT_ATTR, jira_dc_user_context)
+
+ async with get_app_conversation_service(
+ injector_state
+ ) as app_conversation_service:
+ async for task in app_conversation_service.start_app_conversation(
+ start_request
+ ):
+ if task.status == AppConversationStartTaskStatus.ERROR:
+ logger.error(f'Failed to start V1 conversation: {task.detail}')
+ raise RuntimeError(
+ f'Failed to start V1 conversation: {task.detail}'
+ )
+
+ logger.info(f'[Jira DC]: Created new conversation: {self.conversation_id}')
+
+ def _create_jira_dc_v1_callback_processor(self) -> JiraDcV1CallbackProcessor:
+ """Create a V1 callback processor for Jira DC integration."""
+ return JiraDcV1CallbackProcessor(
+ issue_key=self.job_context.issue_key,
+ workspace_name=self.jira_dc_workspace.name,
+ base_api_url=self.job_context.base_api_url,
+ svc_acc_api_key=self._decrypted_api_key,
+ )
- # Store Jira DC conversation mapping
- jira_dc_conversation = JiraDcConversation(
- conversation_id=self.conversation_id,
- issue_id=self.job_context.issue_id,
- issue_key=self.job_context.issue_key,
- jira_dc_user_id=self.jira_dc_user.id,
+ async def _get_git_provider(self) -> ProviderType | None:
+ """Determine the git provider from the selected repository."""
+ if not self.selected_repo:
+ return None
+
+ provider_tokens = await self.saas_user_auth.get_provider_tokens()
+ if not provider_tokens:
+ return None
+
+ try:
+ provider_handler = ProviderHandler(provider_tokens)
+ repository = await provider_handler.verify_repo_provider(self.selected_repo)
+ return repository.git_provider
+ except Exception as e:
+ logger.warning(
+ f'[Jira DC] Failed to determine git provider for {self.selected_repo}: {e}'
)
+ return None
- await integration_store.create_conversation(jira_dc_conversation)
+ async def _get_resolved_org_id(self) -> UUID | None:
+ """Resolve the org ID for V1 conversations."""
+ provider_tokens = await self.saas_user_auth.get_provider_tokens()
+ if not provider_tokens or not self.selected_repo:
+ return None
- return self.conversation_id
+ try:
+ provider_handler = ProviderHandler(provider_tokens)
+ repository = await provider_handler.verify_repo_provider(self.selected_repo)
+ resolved_org_id = await resolve_org_for_repo(
+ provider=repository.git_provider.value,
+ full_repo_name=self.selected_repo,
+ keycloak_user_id=self.jira_dc_user.keycloak_user_id,
+ )
+ return resolved_org_id
except Exception as e:
- logger.error(
- f'[Jira DC] Failed to create conversation: {str(e)}', exc_info=True
+ logger.warning(
+ f'[Jira DC] Failed to resolve org for {self.selected_repo}: {e}'
)
- raise StartingConvoException(f'Failed to create conversation: {str(e)}')
+ return None
def get_response_msg(self) -> str:
- """Get the response message to send back to Jira DC"""
+ """Get the response message to send back to Jira DC."""
conversation_link = CONVERSATION_URL.format(self.conversation_id)
return f"I'm on it! {self.job_context.display_name} can [track my progress here|{conversation_link}]."
@dataclass
class JiraDcExistingConversationView(JiraDcViewInterface):
+ """View for sending messages to an existing Jira DC conversation."""
+
job_context: JobContext
saas_user_auth: UserAuth
jira_dc_user: JiraDcUser
@@ -114,8 +226,7 @@ class JiraDcExistingConversationView(JiraDcViewInterface):
conversation_id: str
async def _get_instructions(self, jinja_env: Environment) -> tuple[str, str]:
- """Instructions passed when conversation is first initialized"""
-
+ """Instructions passed when conversation is updated."""
user_msg_template = jinja_env.get_template('jira_dc_existing_conversation.j2')
user_msg = user_msg_template.render(
issue_key=self.job_context.issue_key,
@@ -127,64 +238,107 @@ class JiraDcExistingConversationView(JiraDcViewInterface):
return '', user_msg
async def create_or_update_conversation(self, jinja_env: Environment) -> str:
- """Update an existing Jira conversation"""
-
- user_id = self.jira_dc_user.keycloak_user_id
-
- try:
- conversation_store = await ConversationStoreImpl.get_instance(
- config, user_id
- )
-
- try:
- await conversation_store.get_metadata(self.conversation_id)
- except FileNotFoundError:
- raise StartingConvoException('Conversation no longer exists.')
-
- provider_tokens = await self.saas_user_auth.get_provider_tokens()
- if provider_tokens is None:
- raise ValueError('Could not load provider tokens')
- providers_set = list(provider_tokens.keys())
+ """Send a message to an existing V1 conversation.
+
+ Returns:
+ The conversation ID
+ """
+ await self._send_message_to_v1_conversation(jinja_env)
+ return self.conversation_id
+
+ async def _send_message_to_v1_conversation(self, jinja_env: Environment):
+ """Send a message to an existing V1 conversation using the agent server API."""
+ import httpx
+
+ from openhands.app_server.config import (
+ get_app_conversation_info_service,
+ get_httpx_client,
+ get_sandbox_service,
+ )
+ from openhands.app_server.event_callback.util import (
+ ensure_conversation_found,
+ get_agent_server_url_from_sandbox,
+ )
+ from openhands.app_server.sandbox.sandbox_models import SandboxStatus
+ from openhands.app_server.services.injector import InjectorState
+ from openhands.app_server.user.specifiy_user_context import (
+ ADMIN,
+ USER_CONTEXT_ATTR,
+ )
- conversation_init_data = await setup_init_conversation_settings(
- user_id, self.conversation_id, providers_set
+ _, user_msg = await self._get_instructions(jinja_env)
+
+ # Create injector state for dependency injection
+ state = InjectorState()
+ setattr(state, USER_CONTEXT_ATTR, ADMIN)
+
+ async with (
+ get_app_conversation_info_service(state) as app_conversation_info_service,
+ get_sandbox_service(state) as sandbox_service,
+ get_httpx_client(state) as httpx_client,
+ ):
+ # 1. Conversation lookup
+ conversation_uuid = UUID(self.conversation_id)
+ app_conversation_info = ensure_conversation_found(
+ await app_conversation_info_service.get_app_conversation_info(
+ conversation_uuid
+ ),
+ conversation_uuid,
)
- # Either join ongoing conversation, or restart the conversation
- agent_loop_info = await conversation_manager.maybe_start_agent_loop(
- self.conversation_id, conversation_init_data, user_id
+ # 2. Sandbox lookup + validation
+ sandbox = await sandbox_service.get_sandbox(
+ app_conversation_info.sandbox_id
)
- if agent_loop_info.event_store is None:
- raise StartingConvoException('Event store not available')
+ if sandbox is None or sandbox.status != SandboxStatus.RUNNING:
+ logger.warning(
+ f'[Jira DC] Sandbox not running for conversation {self.conversation_id}'
+ )
+ return
- final_agent_observation = get_final_agent_observation(
- agent_loop_info.event_store
- )
- agent_state = (
- None
- if len(final_agent_observation) == 0
- else final_agent_observation[0].agent_state
- )
+ if sandbox.session_api_key is None:
+ logger.warning(
+ f'[Jira DC] No session API key for sandbox: {sandbox.id}'
+ )
+ return
- if not agent_state or agent_state == AgentState.LOADING:
- raise StartingConvoException('Conversation is still starting')
+ # 3. Build URL and send message
+ agent_server_url = get_agent_server_url_from_sandbox(sandbox)
- _, user_msg = await self._get_instructions(jinja_env)
- user_message_event = MessageAction(content=user_msg)
- await conversation_manager.send_event_to_conversation(
- self.conversation_id, event_to_dict(user_message_event)
+ send_message_request = SendMessageRequest(
+ role='user', content=[TextContent(text=user_msg)]
)
- return self.conversation_id
- except Exception as e:
- logger.error(
- f'[Jira] Failed to create conversation: {str(e)}', exc_info=True
+ url = (
+ f"{agent_server_url.rstrip('/')}"
+ f'/api/conversations/{self.conversation_id}/messages'
)
- raise StartingConvoException(f'Failed to create conversation: {str(e)}')
+ headers = {'X-Session-API-Key': sandbox.session_api_key}
+ payload = send_message_request.model_dump()
+
+ try:
+ response = await httpx_client.post(
+ url,
+ json=payload,
+ headers=headers,
+ timeout=30.0,
+ )
+ response.raise_for_status()
+ logger.info(
+ f'[Jira DC] Sent message to existing conversation {self.conversation_id}'
+ )
+ except httpx.HTTPStatusError as e:
+ logger.error(
+ f'[Jira DC] Failed to send message: HTTP {e.response.status_code}'
+ )
+ raise
+ except Exception as e:
+ logger.error(f'[Jira DC] Failed to send message: {e}')
+ raise
def get_response_msg(self) -> str:
- """Get the response message to send back to Jira"""
+ """Get the response message to send back to Jira."""
conversation_link = CONVERSATION_URL.format(self.conversation_id)
return f"I'm on it! {self.job_context.display_name} can [continue tracking my progress here|{conversation_link}]."
@@ -200,7 +354,6 @@ class JiraDcFactory:
jira_dc_workspace: JiraDcWorkspace,
) -> JiraDcViewInterface:
"""Create appropriate Jira DC view based on the payload."""
-
if not jira_dc_user or not saas_user_auth or not jira_dc_workspace:
raise StartingConvoException('User not authenticated with Jira integration')
diff --git a/enterprise/integrations/linear/linear_manager.py b/enterprise/integrations/linear/linear_manager.py
deleted file mode 100644
index 708963ab02..0000000000
--- a/enterprise/integrations/linear/linear_manager.py
+++ /dev/null
@@ -1,536 +0,0 @@
-import hashlib
-import hmac
-from typing import Dict, Optional, Tuple
-
-import httpx
-from fastapi import Request
-from integrations.linear.linear_types import LinearViewInterface
-from integrations.linear.linear_view import (
- LinearExistingConversationView,
- LinearFactory,
- LinearNewConversationView,
-)
-from integrations.manager import Manager
-from integrations.models import JobContext, Message
-from integrations.utils import (
- HOST_URL,
- OPENHANDS_RESOLVER_TEMPLATES_DIR,
- filter_potential_repos_by_user_msg,
- get_session_expired_message,
-)
-from jinja2 import Environment, FileSystemLoader
-from server.auth.saas_user_auth import get_user_auth_from_keycloak_id
-from server.auth.token_manager import TokenManager
-from server.utils.conversation_callback_utils import register_callback_processor
-from storage.linear_integration_store import LinearIntegrationStore
-from storage.linear_user import LinearUser
-from storage.linear_workspace import LinearWorkspace
-
-from openhands.core.logger import openhands_logger as logger
-from openhands.integrations.provider import ProviderHandler
-from openhands.integrations.service_types import Repository
-from openhands.server.shared import server_config
-from openhands.server.types import (
- LLMAuthenticationError,
- MissingSettingsError,
- SessionExpiredError,
-)
-from openhands.server.user_auth.user_auth import UserAuth
-from openhands.utils.http_session import httpx_verify_option
-
-
-class LinearManager(Manager[LinearViewInterface]):
- def __init__(self, token_manager: TokenManager):
- self.token_manager = token_manager
- self.integration_store = LinearIntegrationStore.get_instance()
- self.api_url = 'https://api.linear.app/graphql'
- self.jinja_env = Environment(
- loader=FileSystemLoader(OPENHANDS_RESOLVER_TEMPLATES_DIR + 'linear')
- )
-
- async def authenticate_user(
- self, linear_user_id: str, workspace_id: int
- ) -> tuple[LinearUser | None, UserAuth | None]:
- """Authenticate Linear user and get their OpenHands user auth."""
-
- # Find active Linear user by Linear user ID and workspace ID
- linear_user = await self.integration_store.get_active_user(
- linear_user_id, workspace_id
- )
-
- if not linear_user:
- logger.warning(
- f'[Linear] No active Linear user found for {linear_user_id} in workspace {workspace_id}'
- )
- return None, None
-
- saas_user_auth = await get_user_auth_from_keycloak_id(
- linear_user.keycloak_user_id
- )
- return linear_user, saas_user_auth
-
- async def _get_repositories(self, user_auth: UserAuth) -> list[Repository]:
- """Get repositories that the user has access to."""
- provider_tokens = await user_auth.get_provider_tokens()
- if provider_tokens is None:
- return []
- access_token = await user_auth.get_access_token()
- user_id = await user_auth.get_user_id()
- client = ProviderHandler(
- provider_tokens=provider_tokens,
- external_auth_token=access_token,
- external_auth_id=user_id,
- )
- repos: list[Repository] = await client.get_repositories(
- 'pushed', server_config.app_mode, None, None, None, None
- )
- return repos
-
- async def validate_request(
- self, request: Request
- ) -> Tuple[bool, Optional[str], Optional[Dict]]:
- """Verify Linear webhook signature."""
- signature = request.headers.get('linear-signature')
- body = await request.body()
- payload = await request.json()
- actor_url = payload.get('actor', {}).get('url', '')
- workspace_name = ''
-
- # Extract workspace name from actor URL
- # Format: https://linear.app/{workspace}/profiles/{user}
- if actor_url.startswith('https://linear.app/'):
- url_parts = actor_url.split('/')
- if len(url_parts) >= 4:
- workspace_name = url_parts[3] # Extract workspace name
- else:
- logger.warning(f'[Linear] Invalid actor URL format: {actor_url}')
- return False, None, None
- else:
- logger.warning(
- f'[Linear] Actor URL does not match expected format: {actor_url}'
- )
- return False, None, None
-
- if not workspace_name:
- logger.warning('[Linear] No workspace name found in webhook payload')
- return False, None, None
-
- if not signature:
- logger.warning('[Linear] No signature found in webhook headers')
- return False, None, None
-
- workspace = await self.integration_store.get_workspace_by_name(workspace_name)
-
- if not workspace:
- logger.warning('[Linear] Could not identify workspace for webhook')
- return False, None, None
-
- if workspace.status != 'active':
- logger.warning(f'[Linear] Workspace {workspace.id} is not active')
- return False, None, None
-
- webhook_secret = self.token_manager.decrypt_text(workspace.webhook_secret)
- digest = hmac.new(webhook_secret.encode(), body, hashlib.sha256).hexdigest()
-
- if hmac.compare_digest(signature, digest):
- logger.info('[Linear] Webhook signature verified successfully')
- return True, signature, payload
-
- return False, None, None
-
- def parse_webhook(self, payload: Dict) -> JobContext | None:
- action = payload.get('action')
- type = payload.get('type')
-
- if action == 'create' and type == 'Comment':
- data = payload.get('data', {})
- comment = data.get('body', '')
-
- if '@openhands' not in comment:
- return None
-
- issue_data = data.get('issue', {})
- issue_id = issue_data.get('id', '')
- issue_key = issue_data.get('identifier', '')
- elif action == 'update' and type == 'Issue':
- data = payload.get('data', {})
- labels = data.get('labels', [])
-
- has_openhands_label = False
- label_id = ''
- for label in labels:
- if label.get('name') == 'openhands':
- label_id = label.get('id', '')
- has_openhands_label = True
- break
-
- if not has_openhands_label and not label_id:
- return None
-
- labelIdChanges = data.get('updatedFrom', {}).get('labelIds', [])
-
- if labelIdChanges and label_id in labelIdChanges:
- return None # Label was added previously, ignore this webhook
-
- issue_id = data.get('id', '')
- issue_key = data.get('identifier', '')
- comment = ''
-
- else:
- return None
-
- actor = payload.get('actor', {})
- display_name = actor.get('name', '')
- user_email = actor.get('email', '')
- actor_url = actor.get('url', '')
- actor_id = actor.get('id', '')
- workspace_name = ''
-
- if actor_url.startswith('https://linear.app/'):
- url_parts = actor_url.split('/')
- if len(url_parts) >= 4:
- workspace_name = url_parts[3] # Extract workspace name
- else:
- logger.warning(f'[Linear] Invalid actor URL format: {actor_url}')
- return None
- else:
- logger.warning(
- f'[Linear] Actor URL does not match expected format: {actor_url}'
- )
- return None
-
- if not all(
- [issue_id, issue_key, display_name, user_email, actor_id, workspace_name]
- ):
- logger.warning('[Linear] Missing required fields in webhook payload')
- return None
-
- return JobContext(
- issue_id=issue_id,
- issue_key=issue_key,
- user_msg=comment,
- user_email=user_email,
- platform_user_id=actor_id,
- workspace_name=workspace_name,
- display_name=display_name,
- )
-
- async def receive_message(self, message: Message):
- """Process incoming Linear webhook message."""
- payload = message.message.get('payload', {})
- job_context = self.parse_webhook(payload)
-
- if not job_context:
- logger.info('[Linear] Webhook does not match trigger conditions')
- return
-
- # Get workspace by user email domain
- workspace = await self.integration_store.get_workspace_by_name(
- job_context.workspace_name
- )
- if not workspace:
- logger.warning(
- f'[Linear] No workspace found for email domain: {job_context.workspace_name}'
- )
- await self._send_error_comment(
- job_context.issue_id,
- 'Your workspace is not configured with Linear integration.',
- None,
- )
- return
-
- # Prevent any recursive triggers from the service account
- if job_context.user_email == workspace.svc_acc_email:
- return
-
- if workspace.status != 'active':
- logger.warning(f'[Linear] Workspace {workspace.id} is not active')
- await self._send_error_comment(
- job_context.issue_id,
- 'Linear integration is not active for your workspace.',
- workspace,
- )
- return
-
- # Authenticate user
- linear_user, saas_user_auth = await self.authenticate_user(
- job_context.platform_user_id, workspace.id
- )
- if not linear_user or not saas_user_auth:
- logger.warning(
- f'[Linear] User authentication failed for {job_context.user_email}'
- )
- await self._send_error_comment(
- job_context.issue_id,
- f'User {job_context.user_email} is not authenticated or active in the Linear integration.',
- workspace,
- )
- return
-
- # Get issue details
- try:
- api_key = self.token_manager.decrypt_text(workspace.svc_acc_api_key)
- issue_title, issue_description = await self.get_issue_details(
- job_context.issue_id, api_key
- )
- job_context.issue_title = issue_title
- job_context.issue_description = issue_description
- except Exception as e:
- logger.error(f'[Linear] Failed to get issue context: {str(e)}')
- await self._send_error_comment(
- job_context.issue_id,
- 'Failed to retrieve issue details. Please check the issue ID and try again.',
- workspace,
- )
- return
-
- try:
- # Create Linear view
- linear_view = await LinearFactory.create_linear_view_from_payload(
- job_context,
- saas_user_auth,
- linear_user,
- workspace,
- )
- except Exception as e:
- logger.error(
- f'[Linear] Failed to create linear view: {str(e)}', exc_info=True
- )
- await self._send_error_comment(
- job_context.issue_id,
- 'Failed to initialize conversation. Please try again.',
- workspace,
- )
- return
-
- if not await self.is_job_requested(message, linear_view):
- return
-
- await self.start_job(linear_view)
-
- async def is_job_requested(
- self, message: Message, linear_view: LinearViewInterface
- ) -> bool:
- """
- Check if a job is requested and handle repository selection.
- """
-
- if isinstance(linear_view, LinearExistingConversationView):
- return True
-
- try:
- # Get user repositories
- user_repos: list[Repository] = await self._get_repositories(
- linear_view.saas_user_auth
- )
-
- target_str = f'{linear_view.job_context.issue_description}\n{linear_view.job_context.user_msg}'
-
- # Try to infer repository from issue description
- match, repos = filter_potential_repos_by_user_msg(target_str, user_repos)
-
- if match:
- # Found exact repository match
- linear_view.selected_repo = repos[0].full_name
- logger.info(f'[Linear] Inferred repository: {repos[0].full_name}')
- return True
- else:
- # No clear match - send repository selection comment
- await self._send_repo_selection_comment(linear_view)
- return False
-
- except Exception as e:
- logger.error(f'[Linear] Error in is_job_requested: {str(e)}')
- return False
-
- async def start_job(self, linear_view: LinearViewInterface) -> None:
- """Start a Linear job/conversation."""
- # Import here to prevent circular import
- from server.conversation_callback_processor.linear_callback_processor import (
- LinearCallbackProcessor,
- )
-
- try:
- user_info: LinearUser = linear_view.linear_user
- logger.info(
- f'[Linear] Starting job for user {user_info.keycloak_user_id} '
- f'issue {linear_view.job_context.issue_key}',
- )
-
- # Create conversation
- conversation_id = await linear_view.create_or_update_conversation(
- self.jinja_env
- )
-
- logger.info(
- f'[Linear] Created/Updated conversation {conversation_id} for issue {linear_view.job_context.issue_key}'
- )
-
- if isinstance(linear_view, LinearNewConversationView):
- # Register callback processor for updates
- processor = LinearCallbackProcessor(
- issue_id=linear_view.job_context.issue_id,
- issue_key=linear_view.job_context.issue_key,
- workspace_name=linear_view.linear_workspace.name,
- )
-
- # Register the callback processor
- register_callback_processor(conversation_id, processor)
-
- logger.info(
- f'[Linear] Created callback processor for conversation {conversation_id}'
- )
-
- # Send initial response
- msg_info = linear_view.get_response_msg()
-
- except MissingSettingsError as e:
- logger.warning(f'[Linear] Missing settings error: {str(e)}')
- msg_info = f'Please re-login into [OpenHands Cloud]({HOST_URL}) before starting a job.'
-
- except LLMAuthenticationError as e:
- logger.warning(f'[Linear] LLM authentication error: {str(e)}')
- msg_info = f'Please set a valid LLM API key in [OpenHands Cloud]({HOST_URL}) before starting a job.'
-
- except SessionExpiredError as e:
- logger.warning(f'[Linear] Session expired: {str(e)}')
- msg_info = get_session_expired_message()
-
- except Exception as e:
- logger.error(
- f'[Linear] Unexpected error starting job: {str(e)}', exc_info=True
- )
- msg_info = 'Sorry, there was an unexpected error starting the job. Please try again.'
-
- # Send response comment
- try:
- api_key = self.token_manager.decrypt_text(
- linear_view.linear_workspace.svc_acc_api_key
- )
- await self.send_message(
- msg_info,
- linear_view.job_context.issue_id,
- api_key,
- )
- except Exception as e:
- logger.error(f'[Linear] Failed to send response message: {str(e)}')
-
- async def _query_api(self, query: str, variables: Dict, api_key: str) -> Dict:
- """Query Linear GraphQL API."""
- headers = {'Authorization': api_key}
- async with httpx.AsyncClient(verify=httpx_verify_option()) as client:
- response = await client.post(
- self.api_url,
- headers=headers,
- json={'query': query, 'variables': variables},
- )
- response.raise_for_status()
- return response.json()
-
- async def get_issue_details(self, issue_id: str, api_key: str) -> Tuple[str, str]:
- """Get issue details from Linear API."""
- query = """
- query Issue($issueId: String!) {
- issue(id: $issueId) {
- id
- identifier
- title
- description
- syncedWith {
- metadata {
- ... on ExternalEntityInfoGithubMetadata {
- owner
- repo
- }
- }
- }
- }
- }
- """
- issue_payload = await self._query_api(query, {'issueId': issue_id}, api_key)
-
- if not issue_payload:
- raise ValueError(f'Issue with ID {issue_id} not found.')
-
- issue_data = issue_payload.get('data', {}).get('issue', {})
- title = issue_data.get('title', '')
- description = issue_data.get('description', '')
- synced_with = issue_data.get('syncedWith', [])
- owner = ''
- repo = ''
- if synced_with:
- owner = synced_with[0].get('metadata', {}).get('owner', '')
- repo = synced_with[0].get('metadata', {}).get('repo', '')
-
- if not title:
- raise ValueError(f'Issue with ID {issue_id} does not have a title.')
-
- if not description:
- raise ValueError(f'Issue with ID {issue_id} does not have a description.')
-
- if owner and repo:
- description += f'\n\nGit Repo: {owner}/{repo}'
-
- return title, description
-
- async def send_message(self, message: str, issue_id: str, api_key: str):
- """Send message/comment to Linear issue.
-
- Args:
- message: The message content to send (plain text string)
- issue_id: The Linear issue ID to comment on
- api_key: The Linear API key for authentication
- """
- query = """
- mutation CommentCreate($input: CommentCreateInput!) {
- commentCreate(input: $input) {
- success
- comment {
- id
- }
- }
- }
- """
- variables = {'input': {'issueId': issue_id, 'body': message}}
- return await self._query_api(query, variables, api_key)
-
- async def _send_error_comment(
- self, issue_id: str, error_msg: str, workspace: LinearWorkspace | None
- ):
- """Send error comment to Linear issue."""
- if not workspace:
- logger.error('[Linear] Cannot send error comment - no workspace available')
- return
-
- try:
- api_key = self.token_manager.decrypt_text(workspace.svc_acc_api_key)
- await self.send_message(error_msg, issue_id, api_key)
- except Exception as e:
- logger.error(f'[Linear] Failed to send error comment: {str(e)}')
-
- async def _send_repo_selection_comment(self, linear_view: LinearViewInterface):
- """Send a comment with repository options for the user to choose."""
- try:
- comment_msg = (
- 'I need to know which repository to work with. '
- 'Please add it to your issue description or send a followup comment.'
- )
-
- api_key = self.token_manager.decrypt_text(
- linear_view.linear_workspace.svc_acc_api_key
- )
-
- await self.send_message(
- comment_msg,
- linear_view.job_context.issue_id,
- api_key,
- )
-
- logger.info(
- f'[Linear] Sent repository selection comment for issue {linear_view.job_context.issue_key}'
- )
-
- except Exception as e:
- logger.error(
- f'[Linear] Failed to send repository selection comment: {str(e)}'
- )
diff --git a/enterprise/integrations/linear/linear_types.py b/enterprise/integrations/linear/linear_types.py
deleted file mode 100644
index 237fdcb303..0000000000
--- a/enterprise/integrations/linear/linear_types.py
+++ /dev/null
@@ -1,40 +0,0 @@
-from abc import ABC, abstractmethod
-
-from integrations.models import JobContext
-from jinja2 import Environment
-from storage.linear_user import LinearUser
-from storage.linear_workspace import LinearWorkspace
-
-from openhands.server.user_auth.user_auth import UserAuth
-
-
-class LinearViewInterface(ABC):
- """Interface for Linear views that handle different types of Linear interactions."""
-
- job_context: JobContext
- saas_user_auth: UserAuth
- linear_user: LinearUser
- linear_workspace: LinearWorkspace
- selected_repo: str | None
- conversation_id: str
-
- @abstractmethod
- async def _get_instructions(self, jinja_env: Environment) -> tuple[str, str]:
- """Get initial instructions for the conversation."""
- pass
-
- @abstractmethod
- async def create_or_update_conversation(self, jinja_env: Environment) -> str:
- """Create or update a conversation and return the conversation ID."""
- pass
-
- @abstractmethod
- def get_response_msg(self) -> str:
- """Get the response message to send back to Linear."""
- pass
-
-
-class StartingConvoException(Exception):
- """Exception raised when starting a conversation fails."""
-
- pass
diff --git a/enterprise/integrations/linear/linear_view.py b/enterprise/integrations/linear/linear_view.py
deleted file mode 100644
index 9a62ac762f..0000000000
--- a/enterprise/integrations/linear/linear_view.py
+++ /dev/null
@@ -1,288 +0,0 @@
-from dataclasses import dataclass
-from uuid import uuid4
-
-from integrations.linear.linear_types import LinearViewInterface, StartingConvoException
-from integrations.models import JobContext
-from integrations.resolver_org_router import resolve_org_for_repo
-from integrations.utils import CONVERSATION_URL, get_final_agent_observation
-from jinja2 import Environment
-from server.config import get_config
-from storage.linear_conversation import LinearConversation
-from storage.linear_integration_store import LinearIntegrationStore
-from storage.linear_user import LinearUser
-from storage.linear_workspace import LinearWorkspace
-from storage.saas_conversation_store import SaasConversationStore
-
-from openhands.core.logger import openhands_logger as logger
-from openhands.core.schema.agent import AgentState
-from openhands.events.action import MessageAction
-from openhands.events.serialization.event import event_to_dict
-from openhands.integrations.provider import ProviderHandler
-from openhands.server.services.conversation_service import (
- setup_init_conversation_settings,
- start_conversation,
-)
-from openhands.server.shared import ConversationStoreImpl, config, conversation_manager
-from openhands.server.user_auth.user_auth import UserAuth
-from openhands.storage.data_models.conversation_metadata import (
- ConversationMetadata,
- ConversationTrigger,
-)
-from openhands.utils.conversation_summary import get_default_conversation_title
-
-integration_store = LinearIntegrationStore.get_instance()
-
-
-@dataclass
-class LinearNewConversationView(LinearViewInterface):
- job_context: JobContext
- saas_user_auth: UserAuth
- linear_user: LinearUser
- linear_workspace: LinearWorkspace
- selected_repo: str | None
- conversation_id: str
-
- async def _get_instructions(self, jinja_env: Environment) -> tuple[str, str]:
- """Instructions passed when conversation is first initialized"""
-
- instructions_template = jinja_env.get_template('linear_instructions.j2')
- instructions = instructions_template.render()
-
- user_msg_template = jinja_env.get_template('linear_new_conversation.j2')
-
- user_msg = user_msg_template.render(
- issue_key=self.job_context.issue_key,
- issue_title=self.job_context.issue_title,
- issue_description=self.job_context.issue_description,
- user_message=self.job_context.user_msg or '',
- )
-
- return instructions, user_msg
-
- async def create_or_update_conversation(self, jinja_env: Environment) -> str:
- """Create a new Linear conversation"""
-
- if not self.selected_repo:
- raise StartingConvoException('No repository selected for this conversation')
-
- provider_tokens = await self.saas_user_auth.get_provider_tokens()
- user_secrets = await self.saas_user_auth.get_secrets()
- instructions, user_msg = await self._get_instructions(jinja_env)
-
- try:
- user_id = self.linear_user.keycloak_user_id
-
- # Resolve git provider from repository
- resolved_git_provider = None
- if provider_tokens:
- try:
- provider_handler = ProviderHandler(provider_tokens)
- repository = await provider_handler.verify_repo_provider(
- self.selected_repo
- )
- resolved_git_provider = repository.git_provider
- except Exception as e:
- logger.warning(
- f'[Linear] Failed to resolve git provider for {self.selected_repo}: {e}'
- )
-
- # Resolve target org based on claimed git organizations
- resolved_org_id = None
- if resolved_git_provider and self.selected_repo:
- try:
- resolved_org_id = await resolve_org_for_repo(
- provider=resolved_git_provider.value,
- full_repo_name=self.selected_repo,
- keycloak_user_id=user_id,
- )
- except Exception as e:
- logger.warning(
- f'[Linear] Failed to resolve org for {self.selected_repo}: {e}'
- )
-
- # Create the conversation store with resolver org routing
- # (bypasses initialize_conversation to avoid threading enterprise-only
- # resolver_org_id through the generic OSS interface)
- store = await SaasConversationStore.get_resolver_instance(
- get_config(),
- user_id,
- resolved_org_id,
- )
-
- conversation_id = uuid4().hex
- conversation_metadata = ConversationMetadata(
- trigger=ConversationTrigger.LINEAR,
- conversation_id=conversation_id,
- title=get_default_conversation_title(conversation_id),
- user_id=user_id,
- selected_repository=self.selected_repo,
- selected_branch=None,
- git_provider=resolved_git_provider,
- )
- await store.save_metadata(conversation_metadata)
-
- await start_conversation(
- user_id=user_id,
- git_provider_tokens=provider_tokens,
- custom_secrets=user_secrets.custom_secrets if user_secrets else None,
- initial_user_msg=user_msg,
- image_urls=None,
- replay_json=None,
- conversation_id=conversation_id,
- conversation_metadata=conversation_metadata,
- conversation_instructions=instructions,
- )
-
- self.conversation_id = conversation_id
-
- logger.info(f'[Linear] Created conversation {self.conversation_id}')
-
- # Store Linear conversation mapping
- linear_conversation = LinearConversation(
- conversation_id=self.conversation_id,
- issue_id=self.job_context.issue_id,
- issue_key=self.job_context.issue_key,
- linear_user_id=self.linear_user.id,
- )
-
- await integration_store.create_conversation(linear_conversation)
-
- return self.conversation_id
- except Exception as e:
- logger.error(
- f'[Linear] Failed to create conversation: {str(e)}', exc_info=True
- )
- raise StartingConvoException(f'Failed to create conversation: {str(e)}')
-
- def get_response_msg(self) -> str:
- """Get the response message to send back to Linear"""
- conversation_link = CONVERSATION_URL.format(self.conversation_id)
- return f"I'm on it! {self.job_context.display_name} can [track my progress here]({conversation_link})."
-
-
-@dataclass
-class LinearExistingConversationView(LinearViewInterface):
- job_context: JobContext
- saas_user_auth: UserAuth
- linear_user: LinearUser
- linear_workspace: LinearWorkspace
- selected_repo: str | None
- conversation_id: str
-
- async def _get_instructions(self, jinja_env: Environment) -> tuple[str, str]:
- """Instructions passed when conversation is first initialized"""
-
- user_msg_template = jinja_env.get_template('linear_existing_conversation.j2')
- user_msg = user_msg_template.render(
- issue_key=self.job_context.issue_key,
- user_message=self.job_context.user_msg or '',
- issue_title=self.job_context.issue_title,
- issue_description=self.job_context.issue_description,
- )
-
- return '', user_msg
-
- async def create_or_update_conversation(self, jinja_env: Environment) -> str:
- """Update an existing Linear conversation"""
-
- user_id = self.linear_user.keycloak_user_id
-
- try:
- conversation_store = await ConversationStoreImpl.get_instance(
- config, user_id
- )
-
- try:
- await conversation_store.get_metadata(self.conversation_id)
- except FileNotFoundError:
- raise StartingConvoException('Conversation no longer exists.')
-
- provider_tokens = await self.saas_user_auth.get_provider_tokens()
- if provider_tokens is None:
- raise ValueError('Could not load provider tokens')
- providers_set = list(provider_tokens.keys())
-
- conversation_init_data = await setup_init_conversation_settings(
- user_id, self.conversation_id, providers_set
- )
-
- # Either join ongoing conversation, or restart the conversation
- agent_loop_info = await conversation_manager.maybe_start_agent_loop(
- self.conversation_id, conversation_init_data, user_id
- )
-
- if agent_loop_info.event_store is None:
- raise StartingConvoException('Event store not available')
-
- final_agent_observation = get_final_agent_observation(
- agent_loop_info.event_store
- )
- agent_state = (
- None
- if len(final_agent_observation) == 0
- else final_agent_observation[0].agent_state
- )
-
- if not agent_state or agent_state == AgentState.LOADING:
- raise StartingConvoException('Conversation is still starting')
-
- _, user_msg = await self._get_instructions(jinja_env)
- user_message_event = MessageAction(content=user_msg)
- await conversation_manager.send_event_to_conversation(
- self.conversation_id, event_to_dict(user_message_event)
- )
-
- return self.conversation_id
- except Exception as e:
- logger.error(
- f'[Linear] Failed to create conversation: {str(e)}', exc_info=True
- )
- raise StartingConvoException(f'Failed to create conversation: {str(e)}')
-
- def get_response_msg(self) -> str:
- """Get the response message to send back to Linear"""
- conversation_link = CONVERSATION_URL.format(self.conversation_id)
- return f"I'm on it! {self.job_context.display_name} can [continue tracking my progress here]({conversation_link})."
-
-
-class LinearFactory:
- """Factory for creating Linear views based on message content"""
-
- @staticmethod
- async def create_linear_view_from_payload(
- job_context: JobContext,
- saas_user_auth: UserAuth,
- linear_user: LinearUser,
- linear_workspace: LinearWorkspace,
- ) -> LinearViewInterface:
- """Create appropriate Linear view based on the message and user state"""
-
- if not linear_user or not saas_user_auth or not linear_workspace:
- raise StartingConvoException(
- 'User not authenticated with Linear integration'
- )
-
- conversation = await integration_store.get_user_conversations_by_issue_id(
- job_context.issue_id, linear_user.id
- )
- if conversation:
- logger.info(
- f'[Linear] Found existing conversation for issue {job_context.issue_id}'
- )
- return LinearExistingConversationView(
- job_context=job_context,
- saas_user_auth=saas_user_auth,
- linear_user=linear_user,
- linear_workspace=linear_workspace,
- selected_repo=None,
- conversation_id=conversation.conversation_id,
- )
-
- return LinearNewConversationView(
- job_context=job_context,
- saas_user_auth=saas_user_auth,
- linear_user=linear_user,
- linear_workspace=linear_workspace,
- selected_repo=None, # Will be set later after repo inference
- conversation_id='', # Will be set when conversation is created
- )
diff --git a/enterprise/integrations/slack/slack_manager.py b/enterprise/integrations/slack/slack_manager.py
index 65698791b7..d691706b78 100644
--- a/enterprise/integrations/slack/slack_manager.py
+++ b/enterprise/integrations/slack/slack_manager.py
@@ -24,7 +24,6 @@ from integrations.utils import (
from integrations.v1_utils import get_saas_user_auth
from jinja2 import Environment, FileSystemLoader
from server.constants import SLACK_CLIENT_ID
-from server.utils.conversation_callback_utils import register_callback_processor
from slack_sdk.oauth import AuthorizeUrlGenerator
from slack_sdk.web.async_client import AsyncWebClient
from sqlalchemy import select
@@ -698,11 +697,7 @@ class SlackManager(Manager[SlackViewInterface]):
return False
async def start_job(self, slack_view: SlackViewInterface) -> None:
- # Importing here prevents circular import
- from server.conversation_callback_processor.slack_callback_processor import (
- SlackCallbackProcessor,
- )
-
+ """Start a Slack job using V1 app conversation system."""
try:
msg_info = None
user_info = slack_view.slack_to_openhands_user
@@ -719,37 +714,7 @@ class SlackManager(Manager[SlackViewInterface]):
f'[Slack] Created conversation {conversation_id} for user {user_info.slack_display_name}'
)
- # Only add SlackCallbackProcessor for new conversations (not updates) and non-v1 conversations
- if (
- not isinstance(slack_view, SlackUpdateExistingConversationView)
- and not slack_view.v1_enabled
- ):
- # We don't re-subscribe for follow up messages from slack.
- # Summaries are generated for every messages anyways, we only need to do
- # this subscription once for the event which kicked off the job.
-
- processor = SlackCallbackProcessor(
- slack_user_id=slack_view.slack_user_id,
- channel_id=slack_view.channel_id,
- message_ts=slack_view.message_ts,
- thread_ts=slack_view.thread_ts,
- team_id=slack_view.team_id,
- )
-
- # Register the callback processor
- register_callback_processor(conversation_id, processor)
-
- logger.info(
- f'[Slack] Created callback processor for conversation {conversation_id}'
- )
- elif isinstance(slack_view, SlackUpdateExistingConversationView):
- logger.info(
- f'[Slack] Skipping callback processor for existing conversation update {conversation_id}'
- )
- elif slack_view.v1_enabled:
- logger.info(
- f'[Slack] Skipping callback processor for v1 conversation {conversation_id}'
- )
+ # V1 callback processors are registered by the view during conversation creation
msg_info = slack_view.get_response_msg()
diff --git a/enterprise/integrations/slack/slack_view.py b/enterprise/integrations/slack/slack_view.py
index cfcc28be1d..a33f4da75e 100644
--- a/enterprise/integrations/slack/slack_view.py
+++ b/enterprise/integrations/slack/slack_view.py
@@ -14,13 +14,10 @@ from integrations.slack.slack_v1_callback_processor import SlackV1CallbackProces
from integrations.utils import (
CONVERSATION_URL,
ENABLE_V1_SLACK_RESOLVER,
- get_final_agent_observation,
get_user_v1_enabled_setting,
)
from jinja2 import Environment
-from server.config import get_config
from slack_sdk import WebClient
-from storage.saas_conversation_store import SaasConversationStore
from storage.slack_conversation import SlackConversation
from storage.slack_conversation_store import SlackConversationStore
from storage.slack_team_store import SlackTeamStore
@@ -36,23 +33,13 @@ from openhands.app_server.sandbox.sandbox_models import SandboxStatus
from openhands.app_server.services.injector import InjectorState
from openhands.app_server.user.specifiy_user_context import USER_CONTEXT_ATTR
from openhands.core.logger import openhands_logger as logger
-from openhands.core.schema.agent import AgentState
-from openhands.events.action import MessageAction
-from openhands.events.serialization.event import event_to_dict
from openhands.integrations.provider import ProviderHandler
from openhands.sdk import TextContent
-from openhands.server.services.conversation_service import (
- setup_init_conversation_settings,
- start_conversation,
-)
-from openhands.server.shared import ConversationStoreImpl, config, conversation_manager
from openhands.server.user_auth.user_auth import UserAuth
from openhands.storage.data_models.conversation_metadata import (
- ConversationMetadata,
ConversationTrigger,
)
from openhands.utils.async_utils import GENERAL_TIMEOUT
-from openhands.utils.conversation_summary import get_default_conversation_title
# =================================================
# SECTION: Slack view types
@@ -205,7 +192,6 @@ class SlackNewConversationView(SlackViewInterface):
self._verify_necessary_values_are_set()
provider_tokens = await self.saas_user_auth.get_provider_tokens()
- user_secrets = await self.saas_user_auth.get_secrets()
# Determine git provider from repository (needed for both org routing and conversation creation)
self._resolved_git_provider = None
@@ -223,68 +209,9 @@ class SlackNewConversationView(SlackViewInterface):
keycloak_user_id=self.slack_to_openhands_user.keycloak_user_id,
)
- # Check if V1 conversations are enabled for this user
- self.v1_enabled = await is_v1_enabled_for_slack_resolver(
- self.slack_to_openhands_user.keycloak_user_id
- )
-
- if self.v1_enabled:
- # Use V1 app conversation service
- await self._create_v1_conversation(jinja)
- return self.conversation_id
- else:
- # Use existing V0 conversation service
- await self._create_v0_conversation(jinja, provider_tokens, user_secrets)
- return self.conversation_id
-
- async def _create_v0_conversation(
- self, jinja: Environment, provider_tokens, user_secrets
- ) -> None:
- """Create conversation using the legacy V0 system."""
- user_instructions, conversation_instructions = await self._get_instructions(
- jinja
- )
-
- user_id = self.slack_to_openhands_user.keycloak_user_id
-
- # Create the conversation store with resolver org routing
- # (bypasses initialize_conversation to avoid threading enterprise-only
- # resolver_org_id through the generic OSS interface)
- store = await SaasConversationStore.get_resolver_instance(
- get_config(),
- user_id,
- self.resolved_org_id,
- )
-
- conversation_id = uuid4().hex
- conversation_metadata = ConversationMetadata(
- trigger=ConversationTrigger.SLACK,
- conversation_id=conversation_id,
- title=get_default_conversation_title(conversation_id),
- user_id=user_id,
- selected_repository=self.selected_repo,
- selected_branch=None,
- git_provider=self._resolved_git_provider,
- )
- await store.save_metadata(conversation_metadata)
-
- await start_conversation(
- user_id=user_id,
- git_provider_tokens=provider_tokens,
- custom_secrets=user_secrets.custom_secrets if user_secrets else None,
- initial_user_msg=user_instructions,
- image_urls=None,
- replay_json=None,
- conversation_id=conversation_id,
- conversation_metadata=conversation_metadata,
- conversation_instructions=(
- conversation_instructions if conversation_instructions else None
- ),
- )
-
- self.conversation_id = conversation_id
- logger.info(f'[Slack]: Created V0 conversation: {self.conversation_id}')
- await self.save_slack_convo(v1_enabled=False)
+ # V0 conversation path has been removed - all conversations use V1 app conversation service
+ await self._create_v1_conversation(jinja)
+ return self.conversation_id
async def _create_v1_conversation(self, jinja: Environment) -> None:
"""Create conversation using the new V1 app conversation system."""
@@ -378,53 +305,6 @@ class SlackUpdateExistingConversationView(SlackNewConversationView):
return user_message, ''
- async def send_message_to_v0_conversation(self, jinja: Environment):
- user_info: SlackUser = self.slack_to_openhands_user
- user_id = user_info.keycloak_user_id
- saas_user_auth: UserAuth = self.saas_user_auth
- provider_tokens = await saas_user_auth.get_provider_tokens()
-
- try:
- conversation_store = await ConversationStoreImpl.get_instance(
- config, user_id
- )
- await conversation_store.get_metadata(self.conversation_id)
- except FileNotFoundError:
- raise StartingConvoException('Conversation no longer exists.')
-
- # Should we raise here if there are no provider tokens?
- providers_set = list(provider_tokens.keys()) if provider_tokens else []
-
- conversation_init_data = await setup_init_conversation_settings(
- user_id, self.conversation_id, providers_set
- )
-
- # Either join ongoing conversation, or restart the conversation
- agent_loop_info = await conversation_manager.maybe_start_agent_loop(
- self.conversation_id, conversation_init_data, user_id
- )
-
- if agent_loop_info.event_store is None:
- raise StartingConvoException('Event store not available')
-
- final_agent_observation = get_final_agent_observation(
- agent_loop_info.event_store
- )
- agent_state = (
- None
- if len(final_agent_observation) == 0
- else final_agent_observation[0].agent_state
- )
-
- if not agent_state or agent_state == AgentState.LOADING:
- raise StartingConvoException('Conversation is still starting')
-
- instructions, _ = await self._get_instructions(jinja)
- user_msg = MessageAction(content=instructions)
- await conversation_manager.send_event_to_conversation(
- self.conversation_id, event_to_dict(user_msg)
- )
-
async def send_message_to_v1_conversation(self, jinja: Environment):
"""Send a message to a v1 conversation using the agent server API."""
# Import services within the method to avoid circular imports
@@ -519,7 +399,7 @@ class SlackUpdateExistingConversationView(SlackNewConversationView):
raise Exception(f'Failed to send message to v1 conversation: {str(e)}')
async def create_or_update_conversation(self, jinja: Environment) -> str:
- """Send new user message to converation"""
+ """Send new user message to conversation."""
user_info: SlackUser = self.slack_to_openhands_user
user_id = user_info.keycloak_user_id
@@ -531,10 +411,8 @@ class SlackUpdateExistingConversationView(SlackNewConversationView):
f'{user_info.slack_display_name} is not authorized to send messages to this conversation.'
)
- if self.slack_conversation.v1_enabled:
- await self.send_message_to_v1_conversation(jinja)
- else:
- await self.send_message_to_v0_conversation(jinja)
+ # All conversations use V1 app conversation system
+ await self.send_message_to_v1_conversation(jinja)
return self.conversation_id
diff --git a/enterprise/integrations/utils.py b/enterprise/integrations/utils.py
index 74ab7b62ff..970bc14288 100644
--- a/enterprise/integrations/utils.py
+++ b/enterprise/integrations/utils.py
@@ -3,7 +3,6 @@ from __future__ import annotations
import json
import os
import re
-from typing import TYPE_CHECKING
from jinja2 import Environment, FileSystemLoader
from server.constants import WEB_HOST
@@ -20,12 +19,6 @@ from openhands.events.event_filter import EventFilter
from openhands.events.event_store_abc import EventStoreABC
from openhands.events.observation.agent import AgentStateChangedObservation
from openhands.integrations.service_types import Repository
-from openhands.storage.data_models.conversation_status import ConversationStatus
-
-if TYPE_CHECKING:
- from openhands.server.conversation_manager.conversation_manager import (
- ConversationManager,
- )
# ---- DO NOT REMOVE ----
# WARNING: Langfuse depends on the WEB_HOST environment variable being set to track events.
@@ -363,43 +356,6 @@ def extract_summary_from_event_store(
return summary_event.final_thought
-async def get_event_store_from_conversation_manager(
- conversation_manager: ConversationManager, conversation_id: str
-) -> EventStoreABC:
- agent_loop_infos = await conversation_manager.get_agent_loop_info(
- filter_to_sids={conversation_id}
- )
- if not agent_loop_infos or agent_loop_infos[0].status != ConversationStatus.RUNNING:
- raise RuntimeError(f'conversation_not_running:{conversation_id}')
- event_store = agent_loop_infos[0].event_store
- if not event_store:
- raise RuntimeError(f'event_store_missing:{conversation_id}')
- return event_store
-
-
-async def get_last_user_msg_from_conversation_manager(
- conversation_manager: ConversationManager, conversation_id: str
-):
- event_store = await get_event_store_from_conversation_manager(
- conversation_manager, conversation_id
- )
- return get_last_user_msg(event_store)
-
-
-async def extract_summary_from_conversation_manager(
- conversation_manager: ConversationManager, conversation_id: str
-) -> str:
- """
- Get agent summary or alternative message depending on current AgentState
- """
-
- event_store = await get_event_store_from_conversation_manager(
- conversation_manager, conversation_id
- )
- summary = extract_summary_from_event_store(event_store, conversation_id)
- return append_conversation_footer(summary, conversation_id)
-
-
def append_conversation_footer(message: str, conversation_id: str) -> str:
"""
Append a small footer with the conversation URL to a message.
diff --git a/enterprise/saas_server.py b/enterprise/saas_server.py
index d04e90568e..7936b315e2 100644
--- a/enterprise/saas_server.py
+++ b/enterprise/saas_server.py
@@ -17,7 +17,6 @@ from server.auth.constants import ( # noqa: E402
BITBUCKET_DATA_CENTER_HOST,
ENABLE_JIRA,
ENABLE_JIRA_DC,
- ENABLE_LINEAR,
GITHUB_APP_CLIENT_ID,
GITLAB_APP_CLIENT_ID,
)
@@ -29,12 +28,10 @@ from server.routes.api_keys import api_router as api_keys_router # noqa: E402
from server.routes.auth import api_router, oauth_router # noqa: E402
from server.routes.billing import billing_router # noqa: E402
from server.routes.email import api_router as email_router # noqa: E402
-from server.routes.event_webhook import event_webhook_router # noqa: E402
from server.routes.feedback import router as feedback_router # noqa: E402
from server.routes.github_proxy import add_github_proxy_routes # noqa: E402
from server.routes.integration.jira import jira_integration_router # noqa: E402
from server.routes.integration.jira_dc import jira_dc_integration_router # noqa: E402
-from server.routes.integration.linear import linear_integration_router # noqa: E402
from server.routes.integration.slack import slack_router # noqa: E402
from server.routes.mcp_patch import patch_mcp_server # noqa: E402
from server.routes.oauth_device import oauth_device_router # noqa: E402
@@ -136,8 +133,6 @@ if ENABLE_JIRA:
base_app.include_router(jira_integration_router)
if ENABLE_JIRA_DC:
base_app.include_router(jira_dc_integration_router)
-if ENABLE_LINEAR:
- base_app.include_router(linear_integration_router)
if BITBUCKET_DATA_CENTER_HOST:
from server.routes.bitbucket_dc_proxy import (
router as bitbucket_dc_proxy_router, # noqa: E402
@@ -146,9 +141,6 @@ if BITBUCKET_DATA_CENTER_HOST:
base_app.include_router(bitbucket_dc_proxy_router)
base_app.include_router(email_router) # Add routes for email management
base_app.include_router(feedback_router) # Add routes for conversation feedback
-base_app.include_router(
- event_webhook_router
-) # Add routes for Events in nested runtimes
base_app.add_middleware(
diff --git a/enterprise/server/clustered_conversation_manager.py b/enterprise/server/clustered_conversation_manager.py
deleted file mode 100644
index ee10e37246..0000000000
--- a/enterprise/server/clustered_conversation_manager.py
+++ /dev/null
@@ -1,808 +0,0 @@
-import asyncio
-import json
-import time
-from dataclasses import dataclass, field
-from uuid import uuid4
-
-import socketio
-from server.logger import logger
-from server.utils.conversation_callback_utils import invoke_conversation_callbacks
-from sqlalchemy import select
-from storage.database import a_session_maker
-from storage.stored_conversation_metadata_saas import StoredConversationMetadataSaas
-
-from openhands.core.config import LLMConfig
-from openhands.core.config.openhands_config import OpenHandsConfig
-from openhands.core.config.utils import load_openhands_config
-from openhands.core.schema.agent import AgentState
-from openhands.events.action import MessageAction
-from openhands.events.event_store import EventStore
-from openhands.events.event_store_abc import EventStoreABC
-from openhands.events.observation import AgentStateChangedObservation
-from openhands.events.stream import EventStreamSubscriber
-from openhands.llm.llm_registry import LLMRegistry
-from openhands.runtime.runtime_status import RuntimeStatus
-from openhands.server.config.server_config import ServerConfig
-from openhands.server.conversation_manager.conversation_manager import (
- ConversationManager,
-)
-from openhands.server.conversation_manager.standalone_conversation_manager import (
- StandaloneConversationManager,
-)
-from openhands.server.data_models.agent_loop_info import AgentLoopInfo
-from openhands.server.monitoring import MonitoringListener
-from openhands.server.session.agent_session import WAIT_TIME_BEFORE_CLOSE
-from openhands.server.session.session import Session
-from openhands.server.settings import Settings
-from openhands.storage.files import FileStore
-from openhands.utils.async_utils import call_sync_from_async, wait_all
-from openhands.utils.shutdown_listener import should_continue
-
-# Time in seconds between cleanup operations for stale conversations
-_CLEANUP_INTERVAL_SECONDS = 15
-
-# Time in seconds before a Redis entry is considered expired if not refreshed
-_REDIS_ENTRY_TIMEOUT_SECONDS = 15
-
-# Time in seconds between updates to Redis entries
-_REDIS_UPDATE_INTERVAL_SECONDS = 5
-
-_REDIS_POLL_TIMEOUT = 0.15
-
-
-@dataclass
-class _LLMResponseRequest:
- query_id: str
- response: str | None
- flag: asyncio.Event
-
-
-@dataclass
-class ClusteredConversationManager(StandaloneConversationManager):
- """Manages conversations in clustered mode (multiple server instances with Redis).
-
- This class extends StandaloneConversationManager to provide distributed conversation
- management across multiple server instances using Redis as a communication channel
- and state store. It handles:
-
- - Cross-server message passing via Redis pub/sub
- - Tracking of conversations and connections across the cluster
- - Graceful recovery from server failures
- - Enforcement of conversation limits across the cluster
- - Cleanup of stale conversations and connections
-
- The Redis communication uses several key patterns:
- - ohcnv:{user_id}:{conversation_id} - Marks a conversation as active
- - ohcnct:{user_id}:{conversation_id}:{connection_id} - Tracks connections to conversations
- """
-
- _redis_listen_task: asyncio.Task | None = field(default=None)
- _redis_update_task: asyncio.Task | None = field(default=None)
-
- _llm_responses: dict[str, _LLMResponseRequest] = field(default_factory=dict)
-
- def __post_init__(self):
- # We increment the max_concurrent_conversations by 1 because this class
- # marks the conversation as started in Redis before checking the number
- # of running conversations. This prevents race conditions where multiple
- # servers might simultaneously start new conversations.
- self.config.max_concurrent_conversations += 1
-
- async def __aenter__(self):
- await super().__aenter__()
- self._redis_update_task = asyncio.create_task(
- self._update_state_in_redis_task()
- )
- self._redis_listen_task = asyncio.create_task(self._redis_subscribe())
- return self
-
- async def __aexit__(self, exc_type, exc_value, traceback):
- if self._redis_update_task:
- self._redis_update_task.cancel()
- self._redis_update_task = None
- if self._redis_listen_task:
- self._redis_listen_task.cancel()
- self._redis_listen_task = None
- await super().__aexit__(exc_type, exc_value, traceback)
-
- async def _redis_subscribe(self):
- """Subscribe to Redis messages for cross-server communication.
-
- This method creates a Redis pub/sub subscription to receive messages from
- other server instances. It runs in a continuous loop until cancelled.
- """
- logger.debug('_redis_subscribe')
- redis_client = self._get_redis_client()
- pubsub = redis_client.pubsub()
- await pubsub.subscribe('session_msg')
- while should_continue():
- try:
- message = await pubsub.get_message(
- ignore_subscribe_messages=True, timeout=5
- )
- if message:
- await self._process_message(message)
- except asyncio.CancelledError:
- logger.debug('redis_subscribe_cancelled')
- return
- except Exception as e:
- try:
- asyncio.get_running_loop()
- logger.exception(f'error_reading_from_redis:{str(e)}')
- except RuntimeError:
- # Loop has been shut down, exit gracefully
- return
-
- async def _process_message(self, message: dict):
- """Process messages received from Redis pub/sub.
-
- Handles three types of messages:
- - 'event': Forward an event to a local session
- - 'close_session': Close a local session
- - 'session_closing': Handle remote session closure
-
- Args:
- message: The Redis pub/sub message containing the action to perform
- """
- data = json.loads(message['data'])
- logger.debug(f'got_published_message:{message}')
- message_type = data['message_type']
-
- if message_type == 'event':
- # Forward an event to a local session if it exists
- sid = data['sid']
- session = self._local_agent_loops_by_sid.get(sid)
- if session:
- await session.dispatch(data['data'])
- elif message_type == 'close_session':
- # Close a local session if it exists
- sid = data['sid']
- if sid in self._local_agent_loops_by_sid:
- await self._close_session(sid)
- elif message_type == 'session_closing':
- # Handle connections to a session that is closing on another node
- # We only get this in the event of graceful shutdown,
- # which can't be guaranteed - nodes can simply vanish unexpectedly!
- sid = data['sid']
- user_id = data['user_id']
- logger.debug(f'session_closing:{sid}')
-
- # Create a list of items to process to avoid modifying dict during iteration
- items = list(self._local_connection_id_to_session_id.items())
- for connection_id, local_sid in items:
- if sid == local_sid:
- logger.warning(
- f'local_connection_to_closing_session:{connection_id}:{sid}'
- )
- await self._handle_remote_conversation_stopped(
- user_id, connection_id
- )
- elif message_type == 'llm_completion':
- # Request extraneous llm completion from session's LLM Registry
- sid = data['sid']
- service_id = data['service_id']
- messages = data['messages']
- llm_config = data['llm_config']
- query_id = data['query_id']
-
- session = self._local_agent_loops_by_sid.get(sid)
- if session:
- llm_registry: LLMRegistry = session.llm_registry
- response = await call_sync_from_async(
- llm_registry.request_extraneous_completion,
- service_id,
- llm_config,
- messages,
- )
- await self._get_redis_client().publish(
- 'session_msg',
- json.dumps(
- {
- 'query_id': query_id,
- 'response': response,
- 'message_type': 'llm_completion_response',
- }
- ),
- )
- elif message_type == 'llm_completion_response':
- query_id = data['query_id']
- llm_response = self._llm_responses.get(query_id)
- if llm_response:
- llm_response.response = data['response']
- llm_response.flag.set()
-
- def _get_redis_client(self):
- return getattr(self.sio.manager, 'redis', None)
-
- def _get_redis_conversation_key(self, user_id: str | None, conversation_id: str):
- return f'ohcnv:{user_id}:{conversation_id}'
-
- def _get_redis_connection_key(
- self, user_id: str, conversation_id: str, connection_id: str
- ):
- return f'ohcnct:{user_id}:{conversation_id}:{connection_id}'
-
- async def _get_event_store(self, sid, user_id) -> EventStoreABC | None:
- session = self._local_agent_loops_by_sid.get(sid)
- if session:
- logger.debug('found_local_agent_loop', extra={'sid': sid})
- return session.agent_session.event_stream
-
- redis = self._get_redis_client()
- key = self._get_redis_conversation_key(user_id, sid)
- value = await redis.get(key)
- if value:
- logger.debug('found_remote_agent_loop', extra={'sid': sid})
- return EventStore(sid, self.file_store, user_id)
-
- return None
-
- async def get_running_agent_loops(
- self, user_id: str | None = None, filter_to_sids: set[str] | None = None
- ) -> set[str]:
- sids = await self.get_running_agent_loops_locally(user_id, filter_to_sids)
- if not filter_to_sids or len(sids) != len(filter_to_sids):
- remote_sids = await self._get_running_agent_loops_remotely(
- user_id, filter_to_sids
- )
- sids = sids.union(remote_sids)
- return sids
-
- async def get_running_agent_loops_locally(
- self, user_id: str | None = None, filter_to_sids: set[str] | None = None
- ) -> set[str]:
- sids = await super().get_running_agent_loops(user_id, filter_to_sids)
- return sids
-
- async def _get_running_agent_loops_remotely(
- self,
- user_id: str | None = None,
- filter_to_sids: set[str] | None = None,
- ) -> set[str]:
- """Get the set of conversation IDs running on remote servers.
-
- Args:
- user_id: Optional user ID to filter conversations by
- filter_to_sids: Optional set of conversation IDs to filter by
-
- Returns:
- A set of conversation IDs running on remote servers
- """
- if filter_to_sids is not None and not filter_to_sids:
- return set()
- if user_id:
- pattern = self._get_redis_conversation_key(user_id, '*')
- else:
- pattern = self._get_redis_conversation_key('*', '*')
- redis = self._get_redis_client()
- result = set()
- async for key in redis.scan_iter(pattern):
- conversation_id = key.decode().split(':')[2]
- if filter_to_sids is None or conversation_id in filter_to_sids:
- result.add(conversation_id)
- return result
-
- async def get_connections(
- self, user_id: str | None = None, filter_to_sids: set[str] | None = None
- ) -> dict[str, str]:
- connections = await super().get_connections(user_id, filter_to_sids)
- if not filter_to_sids or len(connections) != len(filter_to_sids):
- remote_connections = await self._get_connections_remotely(
- user_id, filter_to_sids
- )
- connections.update(remote_connections)
- return connections
-
- async def _get_connections_remotely(
- self,
- user_id: str | None = None,
- filter_to_sids: set[str] | None = None,
- ) -> dict[str, str]:
- if filter_to_sids is not None and not filter_to_sids:
- return {}
- if user_id:
- pattern = self._get_redis_connection_key(user_id, '*', '*')
- else:
- pattern = self._get_redis_connection_key('*', '*', '*')
- redis = self._get_redis_client()
- result = {}
- async for key in redis.scan_iter(pattern):
- parts = key.decode().split(':')
- conversation_id = parts[2]
- connection_id = parts[3]
- if filter_to_sids is None or conversation_id in filter_to_sids:
- result[connection_id] = conversation_id
- return result
-
- async def send_to_event_stream(self, connection_id: str, data: dict) -> None:
- sid = self._local_connection_id_to_session_id.get(connection_id)
- if sid:
- await self.send_event_to_conversation(sid, data)
-
- async def request_llm_completion(
- self,
- sid: str,
- service_id: str,
- llm_config: LLMConfig,
- messages: list[dict[str, str]],
- ) -> str:
- session = self._local_agent_loops_by_sid.get(sid)
- if session:
- llm_registry = session.llm_registry
- return llm_registry.request_extraneous_completion(
- service_id, llm_config, messages
- )
-
- flag = asyncio.Event()
- query_id = str(uuid4())
- query = _LLMResponseRequest(query_id=query_id, response=None, flag=flag)
- self._llm_responses[query_id] = query
-
- try:
- redis_client = self._get_redis_client()
- await redis_client.publish(
- 'session_msg',
- json.dumps(
- {
- 'message_type': 'llm_completion',
- 'query_id': query_id,
- 'sid': sid,
- 'service_id': service_id,
- 'llm_config': llm_config,
- 'message': messages,
- }
- ),
- )
-
- async with asyncio.timeout(_REDIS_POLL_TIMEOUT):
- await flag.wait()
-
- if query.response:
- return query.response
-
- raise Exception('Failed to perform LLM completion')
- except TimeoutError:
- raise Exception('Timeout occured')
-
- async def send_event_to_conversation(self, sid: str, data: dict):
- if not sid:
- return
- session = self._local_agent_loops_by_sid.get(sid)
- if session:
- await session.dispatch(data)
- else:
- # The session is running on another node
- redis_client = self._get_redis_client()
- await redis_client.publish(
- 'session_msg',
- json.dumps({'message_type': 'event', 'sid': sid, 'data': data}),
- )
-
- async def close_session(self, sid: str):
- # Send a message to other nodes telling them to close this session if they have the agent loop, and close any connections.
- redis_client = self._get_redis_client()
- await redis_client.publish(
- 'session_msg',
- json.dumps({'message_type': 'close_session', 'sid': sid}),
- )
- await self._close_session(sid)
-
- async def maybe_start_agent_loop(
- self,
- sid: str,
- settings: Settings,
- user_id: str | None,
- initial_user_msg: MessageAction | None = None,
- replay_json: str | None = None,
- ) -> AgentLoopInfo:
- # If we can set the key in redis then no other worker is running this conversation
- redis = self._get_redis_client()
- key = self._get_redis_conversation_key(user_id, sid) # type: ignore
- created = await redis.set(key, 1, nx=True, ex=_REDIS_ENTRY_TIMEOUT_SECONDS)
- if created:
- await self._start_agent_loop(
- sid, settings, user_id, initial_user_msg, replay_json
- )
-
- event_store = await self._get_event_store(sid, user_id)
- if not event_store:
- logger.error(
- f'No event stream after starting agent loop: {sid}',
- extra={'sid': sid},
- )
- raise RuntimeError(f'no_event_stream:{sid}')
-
- return AgentLoopInfo(
- conversation_id=sid,
- url=self._get_conversation_url(sid),
- session_api_key=None,
- event_store=event_store,
- )
-
- async def _update_state_in_redis_task(self):
- while should_continue():
- try:
- await self._update_state_in_redis()
- await asyncio.sleep(_REDIS_UPDATE_INTERVAL_SECONDS)
- except asyncio.CancelledError:
- return
- except Exception:
- try:
- asyncio.get_running_loop()
- logger.exception('error_reading_from_redis')
- except RuntimeError:
- return # Loop has been shut down
-
- async def _update_state_in_redis(self):
- """Refresh all entries in Redis to maintain conversation state across the cluster.
-
- This method:
- 1. Scans Redis for all conversation keys to build a mapping of conversation IDs to user IDs
- 2. Updates Redis entries for all local conversations to prevent them from expiring
- 3. Updates Redis entries for all local connections to prevent them from expiring
-
- This is critical for maintaining the distributed state and allowing other servers
- to detect when a server has gone down unexpectedly.
- """
- redis = self._get_redis_client()
-
- # Build a mapping of conversation_id -> user_id from existing Redis keys
- pattern = self._get_redis_conversation_key('*', '*')
- conversation_user_ids = {}
- async for key in redis.scan_iter(pattern):
- parts = key.decode().split(':')
- conversation_user_ids[parts[2]] = parts[1]
-
- pipe = redis.pipeline()
-
- # Add multiple commands to the pipeline
- # First, update all local agent loops
- for sid, session in self._local_agent_loops_by_sid.items():
- if sid:
- await pipe.set(
- self._get_redis_conversation_key(session.user_id, sid),
- 1,
- ex=_REDIS_ENTRY_TIMEOUT_SECONDS,
- )
-
- # Then, update all local connections
- for (
- connection_id,
- conversation_id,
- ) in self._local_connection_id_to_session_id.items():
- user_id = conversation_user_ids.get(conversation_id)
- if user_id:
- await pipe.set(
- self._get_redis_connection_key(
- user_id, conversation_id, connection_id
- ),
- 1,
- ex=_REDIS_ENTRY_TIMEOUT_SECONDS,
- )
-
- # Execute all commands in the pipeline
- await pipe.execute()
-
- async def _disconnect_from_stopped(self):
- """
- Handle connections to conversations that have stopped unexpectedly.
-
- This method detects when a local connection is pointing to a conversation
- that was running on another server that has crashed or been terminated
- without proper cleanup. It:
-
- 1. Identifies local connections to remote conversations
- 2. Checks which remote conversations are still running in Redis
- 3. Disconnects from conversations that are no longer running
- 4. Attempts to restart the conversation locally if possible
- """
- # Get the remote sessions with local connections
- connected_to_remote_sids = set(
- self._local_connection_id_to_session_id.values()
- ) - set(self._local_agent_loops_by_sid.keys())
- if not connected_to_remote_sids:
- return
-
- # Get the list of sessions which are actually running
- redis = self._get_redis_client()
- pattern = self._get_redis_conversation_key('*', '*')
- running_remote = set()
- async for key in redis.scan_iter(pattern):
- parts = key.decode().split(':')
- running_remote.add(parts[2])
-
- # Get the list of connections locally where the remote agentloop has died.
- stopped_conversation_ids = connected_to_remote_sids - running_remote
- if not stopped_conversation_ids:
- return
-
- # Process each connection to a stopped conversation
- items = list(self._local_connection_id_to_session_id.items())
- for connection_id, conversation_id in items:
- if conversation_id in stopped_conversation_ids:
- logger.warning(
- f'local_connection_to_stopped_conversation:{connection_id}:{conversation_id}'
- )
- # Look up the user_id from the database
- async with a_session_maker() as session:
- result = await session.execute(
- select(StoredConversationMetadataSaas).where(
- StoredConversationMetadataSaas.conversation_id
- == conversation_id
- )
- )
- conversation_metadata_saas = result.scalars().first()
- user_id = (
- str(conversation_metadata_saas.user_id)
- if conversation_metadata_saas
- else None
- )
- # Handle the stopped conversation asynchronously
- asyncio.create_task(
- self._handle_remote_conversation_stopped(user_id, connection_id) # type: ignore
- )
-
- async def _close_disconnected(self):
- async with self._conversations_lock:
- # Create a list of items to process to avoid modifying dict during iteration
- items = list(self._detached_conversations.items())
- for sid, (conversation, detach_time) in items:
- await conversation.disconnect()
- self._detached_conversations.pop(sid, None)
-
- close_threshold = time.time() - self.config.sandbox.close_delay
- running_loops = list(self._local_agent_loops_by_sid.items())
- running_loops.sort(key=lambda item: item[1].last_active_ts)
- sid_to_close: list[str] = []
- for sid, session in running_loops:
- state = session.agent_session.get_state()
- if session.last_active_ts < close_threshold and state not in [
- AgentState.RUNNING,
- None,
- ]:
- sid_to_close.append(sid)
-
- # First we filter out any conversation that has local connections
- connections = await super().get_connections(filter_to_sids=set(sid_to_close))
- connected_sids = set(connections.values())
- sid_to_close = [sid for sid in sid_to_close if sid not in connected_sids]
-
- # Next we filter out any conversation that has remote connections
- if sid_to_close:
- connections = await self._get_connections_remotely(
- filter_to_sids=set(sid_to_close)
- )
- connected_sids = {sid for _, sid in connections.items()}
- sid_to_close = [sid for sid in sid_to_close if sid not in connected_sids]
-
- await wait_all(
- (self._close_session(sid) for sid in sid_to_close),
- timeout=WAIT_TIME_BEFORE_CLOSE,
- )
-
- async def _cleanup_stale(self):
- while should_continue():
- try:
- logger.info(
- 'conversation_manager',
- extra={
- 'attached': len(self._active_conversations),
- 'detached': len(self._detached_conversations),
- 'running': len(self._local_agent_loops_by_sid),
- 'local_conn': len(self._local_connection_id_to_session_id),
- },
- )
- await self._disconnect_from_stopped()
- await self._close_disconnected()
- await asyncio.sleep(_CLEANUP_INTERVAL_SECONDS)
- except asyncio.CancelledError:
- async with self._conversations_lock:
- for conversation, _ in self._detached_conversations.values():
- await conversation.disconnect()
- self._detached_conversations.clear()
- await wait_all(
- (
- self._close_session(sid)
- for sid in self._local_agent_loops_by_sid
- ),
- timeout=WAIT_TIME_BEFORE_CLOSE,
- )
- return
- except Exception:
- logger.warning('error_cleaning_stale', exc_info=True, stack_info=True)
- await asyncio.sleep(_CLEANUP_INTERVAL_SECONDS)
-
- async def _close_session(self, sid: str):
- logger.info(f'_close_session:{sid}')
- redis = self._get_redis_client()
-
- # Keys to delete from redis
- to_delete = []
-
- # Remove connections
- connection_ids_to_remove = list(
- connection_id
- for connection_id, conn_sid in self._local_connection_id_to_session_id.items()
- if sid == conn_sid
- )
-
- if connection_ids_to_remove:
- pattern = self._get_redis_connection_key('*', sid, '*')
- async for key in redis.scan_iter(pattern):
- parts = key.decode().split(':')
- connection_id = parts[3]
- if connection_id in connection_ids_to_remove:
- to_delete.append(key)
-
- logger.info(f'removing connections: {connection_ids_to_remove}')
- for connection_id in connection_ids_to_remove:
- await self.sio.disconnect(connection_id)
- self._local_connection_id_to_session_id.pop(connection_id, None)
-
- # Delete the conversation key if running locally
- session = self._local_agent_loops_by_sid.pop(sid, None)
- if not session:
- logger.info(f'no_session_to_close:{sid}')
- if to_delete:
- redis.delete(*to_delete)
- return
-
- to_delete.append(self._get_redis_conversation_key(session.user_id, sid))
- await redis.delete(*to_delete)
- try:
- redis_client = self._get_redis_client()
- if redis_client:
- await redis_client.publish(
- 'session_msg',
- json.dumps(
- {
- 'sid': session.sid,
- 'message_type': 'session_closing',
- 'user_id': session.user_id,
- }
- ),
- )
- except Exception:
- logger.info(
- 'error_publishing_close_session_event', exc_info=True, stack_info=True
- )
-
- await session.close()
- logger.info(f'closed_session:{session.sid}')
-
- async def get_agent_loop_info(self, user_id=None, filter_to_sids=None):
- # conversation_ids = await self.get_running_agent_loops(user_id=user_id, filter_to_sids=filter_to_sids)
- redis = self._get_redis_client()
- results = []
- if user_id:
- pattern = self._get_redis_conversation_key(user_id, '*')
- else:
- pattern = self._get_redis_conversation_key('*', '*')
-
- async for key in redis.scan_iter(pattern):
- uid, conversation_id = key.decode().split(':')[1:]
- if filter_to_sids is None or conversation_id in filter_to_sids:
- results.append(
- AgentLoopInfo(
- conversation_id,
- url=self._get_conversation_url(conversation_id),
- session_api_key=None,
- event_store=EventStore(conversation_id, self.file_store, uid),
- runtime_status=RuntimeStatus.READY,
- )
- )
- return results
-
- @classmethod
- def get_instance(
- cls,
- sio: socketio.AsyncServer,
- config: OpenHandsConfig,
- file_store: FileStore,
- server_config: ServerConfig,
- monitoring_listener: MonitoringListener | None,
- ) -> ConversationManager:
- return ClusteredConversationManager(
- sio,
- config,
- file_store,
- server_config,
- monitoring_listener, # type: ignore[arg-type]
- )
-
- async def _handle_remote_conversation_stopped(
- self, user_id: str, connection_id: str
- ):
- """Handle a situation where a remote conversation has stopped unexpectedly.
-
- When a server hosting a conversation crashes or is terminated without proper
- cleanup, this method attempts to recover by:
- 1. Verifying the connection and conversation still exist
- 2. Checking if we can start a new conversation (within limits)
- 3. Restarting the conversation locally if possible
- 4. Disconnecting the client if recovery isn't possible
-
- Args:
- user_id: The user ID associated with the conversation
- connection_id: The connection ID to handle
- """
- conversation_id = self._local_connection_id_to_session_id.get(connection_id)
-
- # Not finding a user_id or a conversation_id indicates we are in some unknown state
- # so we disconnect
- if not user_id or not conversation_id:
- await self.sio.disconnect(connection_id)
- return
-
- # Wait a second for connections to stabilize
- await asyncio.sleep(1)
-
- # Check if there are too many loops running - if so disconnect
- response_ids = await self.get_running_agent_loops(user_id)
- if len(response_ids) > self.config.max_concurrent_conversations:
- await self.sio.disconnect(connection_id)
- return
-
- # Restart the agent loop
- from storage.saas_settings_store import SaasSettingsStore
-
- config = load_openhands_config()
- settings_store = await SaasSettingsStore.get_instance(config, user_id)
- settings = await settings_store.load()
- if not settings:
- logger.error(f'Failed to load settings for user {user_id}')
- return
- await self.maybe_start_agent_loop(conversation_id, settings, user_id)
-
- async def _start_agent_loop(
- self,
- sid: str,
- settings: Settings,
- user_id: str | None,
- initial_user_msg: MessageAction | None = None,
- replay_json: str | None = None,
- ) -> Session:
- """Start an agent loop and add conversation callback subscriber.
-
- This method calls the parent implementation and then adds a subscriber
- to the event stream that will invoke conversation callbacks when events occur.
- """
- # Call the parent method to start the agent loop
- session = await super()._start_agent_loop(
- sid, settings, user_id, initial_user_msg, replay_json
- )
-
- # Subscribers run in a different thread - if we are going to access socketio, redis or anything else
- # bound to the main event loop, we need to pass callbacks back to the main event loop.
- loop = asyncio.get_running_loop()
-
- # Add a subscriber for conversation callbacks
- def conversation_callback_handler(event):
- """Handle events by invoking conversation callbacks."""
- try:
- if isinstance(event, AgentStateChangedObservation):
- asyncio.run_coroutine_threadsafe(
- invoke_conversation_callbacks(sid, event), loop
- )
- except Exception as e:
- logger.error(
- f'Error invoking conversation callbacks for {sid}: {str(e)}',
- extra={'session_id': sid, 'error': str(e)},
- exc_info=True,
- )
-
- # Subscribe to the event stream with our callback handler
- try:
- session.agent_session.event_stream.subscribe(
- EventStreamSubscriber.SERVER,
- conversation_callback_handler,
- 'conversation_callbacks',
- )
- except ValueError:
- # Already subscribed - this can happen if the method is called multiple times
- pass
-
- return session
-
- def get_local_session(self, sid: str) -> Session:
- return self._local_agent_loops_by_sid[sid]
diff --git a/enterprise/server/config.py b/enterprise/server/config.py
index 6e5a784715..402eda0bfb 100644
--- a/enterprise/server/config.py
+++ b/enterprise/server/config.py
@@ -75,10 +75,6 @@ class SaaSServerConfig(ServerConfig):
conversation_store_class: str = (
'storage.saas_conversation_store.SaasConversationStore'
)
- conversation_manager_class: str = os.environ.get(
- 'CONVERSATION_MANAGER_CLASS',
- 'server.clustered_conversation_manager.ClusteredConversationManager',
- )
monitoring_listener_class: str = (
'server.saas_monitoring_listener.SaaSMonitoringListener'
)
diff --git a/enterprise/server/conversation_callback_processor/README.md b/enterprise/server/conversation_callback_processor/README.md
deleted file mode 100644
index 1edcb2252b..0000000000
--- a/enterprise/server/conversation_callback_processor/README.md
+++ /dev/null
@@ -1,56 +0,0 @@
-# Conversation Callback Processor
-
-This module provides a framework for processing conversation events and sending summaries or notifications to external platforms like Slack and GitLab.
-
-## Overview
-
-The conversation callback processor system consists of two main components:
-
-1. **ConversationCallback**: A database model that stores information about callbacks to be executed when specific conversation events occur.
-2. **ConversationCallbackProcessor**: An abstract base class that defines the interface for processors that handle conversation events.
-
-## How It Works
-
-### ConversationCallback
-
-The `ConversationCallback` class is a database model that stores:
-
-- A reference to a conversation (`conversation_id`)
-- The current status of the callback (`ACTIVE`, `COMPLETED`, or `ERROR`)
-- The type of processor to use (`processor_type`)
-- Serialized processor configuration (`processor_json`)
-- Timestamps for creation and updates
-
-This model provides methods to:
-- `get_processor()`: Dynamically instantiate the processor from the stored type and JSON data
-- `set_processor()`: Store a processor instance by serializing its type and data
-
-### ConversationCallbackProcessor
-
-The `ConversationCallbackProcessor` is an abstract base class that defines the interface for all callback processors. It:
-
-- Is a Pydantic model that can be serialized to/from JSON
-- Requires implementing the `__call__` method to process conversation events
-- Receives the callback instance and an `AgentStateChangedObservation` when called
-
-## Implemented Processors
-
-### SlackCallbackProcessor
-
-The `SlackCallbackProcessor` sends conversation summaries to Slack channels when specific agent state changes occur. It:
-
-1. Monitors for agent state changes to `AWAITING_USER_INPUT` or `FINISHED`
-2. Sends a summary instruction to the conversation if needed
-3. Extracts a summary from the conversation
-4. Sends the summary to the appropriate Slack channel
-5. Marks the callback as completed
-
-### GithubCallbackProcessor and GitlabCallbackProcessor
-
-The `GithubCallbackProcessor` and `GitlabCallbackProcessor` send conversation summaries to GitHub / GitLab issues when specific agent state changes occur. They:
-
-1. Monitors for agent state changes to `AWAITING_USER_INPUT` or `FINISHED`
-2. Sends a summary instruction to the conversation if needed
-3. Extracts a summary from the conversation
-4. Sends the summary to the appropriate Github or GitLab issue
-5. Marks the callback as completed
diff --git a/enterprise/server/conversation_callback_processor/__init__.py b/enterprise/server/conversation_callback_processor/__init__.py
deleted file mode 100644
index 9bb62d3dec..0000000000
--- a/enterprise/server/conversation_callback_processor/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-# This file makes the conversation_callback_processor directory a Python package
diff --git a/enterprise/server/conversation_callback_processor/github_callback_processor.py b/enterprise/server/conversation_callback_processor/github_callback_processor.py
deleted file mode 100644
index 41e42b530a..0000000000
--- a/enterprise/server/conversation_callback_processor/github_callback_processor.py
+++ /dev/null
@@ -1,135 +0,0 @@
-import asyncio
-from datetime import datetime
-
-from integrations.github.github_manager import GithubManager
-from integrations.github.github_view import GithubViewType
-from integrations.utils import (
- extract_summary_from_conversation_manager,
- get_summary_instruction,
-)
-from server.auth.token_manager import TokenManager
-from storage.conversation_callback import (
- CallbackStatus,
- ConversationCallback,
- ConversationCallbackProcessor,
-)
-
-from openhands.core.logger import openhands_logger as logger
-from openhands.core.schema.agent import AgentState
-from openhands.events.action import MessageAction
-from openhands.events.observation.agent import AgentStateChangedObservation
-from openhands.events.serialization.event import event_to_dict
-from openhands.server.shared import conversation_manager
-
-
-class GithubCallbackProcessor(ConversationCallbackProcessor):
- """
- Processor for sending conversation summaries to GitHub.
-
- This processor is used to send summaries of conversations to GitHub issues/PRs
- when agent state changes occur.
- """
-
- github_view: GithubViewType
- send_summary_instruction: bool = True
-
- async def _send_message_to_github(self, message: str) -> None:
- """Send a message to GitHub.
-
- Args:
- message: The message content to send to GitHub
- """
- try:
- # Get the token manager
- token_manager = TokenManager()
-
- # Create GitHub manager
- from integrations.github.data_collector import GitHubDataCollector
-
- github_manager = GithubManager(token_manager, GitHubDataCollector())
-
- # Send the message directly as a string
- await github_manager.send_message(message, self.github_view)
-
- logger.info(
- f'[GitHub] Sent summary message to {self.github_view.full_repo_name}#{self.github_view.issue_number}'
- )
- except Exception as e:
- logger.exception(f'[GitHub] Failed to send summary message: {str(e)}')
-
- async def __call__(
- self,
- callback: ConversationCallback,
- observation: AgentStateChangedObservation,
- ) -> None:
- """
- Process a conversation event by sending a summary to GitHub.
-
- Args:
- callback: The conversation callback
- observation: The AgentStateChangedObservation that triggered the callback
- """
- logger.info(f'[GitHub] Callback agent state was {observation.agent_state}')
- if observation.agent_state not in (
- AgentState.AWAITING_USER_INPUT,
- AgentState.FINISHED,
- ):
- return
-
- conversation_id = callback.conversation_id
- try:
- # If we need to send a summary instruction first
- if self.send_summary_instruction:
- logger.info(
- f'[GitHub] Sending summary instruction for conversation {conversation_id}'
- )
-
- # Get the summary instruction
- summary_instruction = get_summary_instruction()
- summary_event = event_to_dict(
- MessageAction(content=summary_instruction)
- )
-
- # Add the summary instruction to the event stream
- logger.info(
- f'[GitHub] Sending summary instruction to conversation {conversation_id} {summary_event}'
- )
- await conversation_manager.send_event_to_conversation(
- conversation_id, summary_event
- )
-
- logger.info(
- f'[GitHub] Sent summary instruction to conversation {conversation_id} {summary_event}'
- )
-
- # Update the processor state - the outer session will commit this
- self.send_summary_instruction = False
- callback.set_processor(self)
- callback.updated_at = datetime.now()
- return
-
- # Extract the summary from the event store
- logger.info(
- f'[GitHub] Extracting summary for conversation {conversation_id}'
- )
- summary = await extract_summary_from_conversation_manager(
- conversation_manager, conversation_id
- )
-
- # Send the summary to GitHub
- asyncio.create_task(self._send_message_to_github(summary))
-
- logger.info(f'[GitHub] Summary sent for conversation {conversation_id}')
-
- # Mark callback as completed status - the outer session will commit this
- callback.status = CallbackStatus.COMPLETED
- callback.updated_at = datetime.now()
-
- except Exception as e:
- logger.exception(
- f'[GitHub] Error processing conversation callback: {str(e)}'
- )
- # Mark callback as error to prevent infinite re-invocation
- # The outer session will commit this
- callback.status = CallbackStatus.ERROR
- callback.updated_at = datetime.now()
diff --git a/enterprise/server/conversation_callback_processor/gitlab_callback_processor.py b/enterprise/server/conversation_callback_processor/gitlab_callback_processor.py
deleted file mode 100644
index acefaeccff..0000000000
--- a/enterprise/server/conversation_callback_processor/gitlab_callback_processor.py
+++ /dev/null
@@ -1,136 +0,0 @@
-import asyncio
-from datetime import datetime
-
-from integrations.gitlab.gitlab_manager import GitlabManager
-from integrations.gitlab.gitlab_view import GitlabViewType
-from integrations.utils import (
- extract_summary_from_conversation_manager,
- get_summary_instruction,
-)
-from server.auth.token_manager import TokenManager
-from storage.conversation_callback import (
- CallbackStatus,
- ConversationCallback,
- ConversationCallbackProcessor,
-)
-from storage.database import a_session_maker
-
-from openhands.core.logger import openhands_logger as logger
-from openhands.core.schema.agent import AgentState
-from openhands.events.action import MessageAction
-from openhands.events.observation.agent import AgentStateChangedObservation
-from openhands.events.serialization.event import event_to_dict
-from openhands.server.shared import conversation_manager
-
-token_manager = TokenManager()
-gitlab_manager = GitlabManager(token_manager)
-
-
-class GitlabCallbackProcessor(ConversationCallbackProcessor):
- """Processor for sending conversation summaries to GitLab.
-
- This processor is used to send summaries of conversations to GitLab
- when agent state changes occur.
- """
-
- gitlab_view: GitlabViewType
- send_summary_instruction: bool = True
-
- async def _send_message_to_gitlab(self, message: str) -> None:
- """Send a message to GitLab.
-
- Args:
- message: The message content to send to GitLab
- """
- try:
- # Get the token manager
- token_manager = TokenManager()
- gitlab_manager = GitlabManager(token_manager)
-
- # Send the message directly as a string
- await gitlab_manager.send_message(message, self.gitlab_view)
-
- logger.info(
- f'[GitLab] Sent summary message to {self.gitlab_view.full_repo_name}#{self.gitlab_view.issue_number}'
- )
- except Exception as e:
- logger.exception(f'[GitLab] Failed to send summary message: {str(e)}')
-
- async def __call__(
- self,
- callback: ConversationCallback,
- observation: AgentStateChangedObservation,
- ) -> None:
- """
- Process a conversation event by sending a summary to GitLab.
-
- Args:
- callback: The conversation callback
- observation: The AgentStateChangedObservation that triggered the callback
- """
- logger.info(f'[GitLab] Callback agent state was {observation.agent_state}')
- if observation.agent_state not in (
- AgentState.AWAITING_USER_INPUT,
- AgentState.FINISHED,
- ):
- return
-
- conversation_id = callback.conversation_id
- try:
- # If we need to send a summary instruction first
- if self.send_summary_instruction:
- logger.info(
- f'[GitLab] Sending summary instruction for conversation {conversation_id}'
- )
-
- # Get the summary instruction
- summary_instruction = get_summary_instruction()
- summary_event = event_to_dict(
- MessageAction(content=summary_instruction)
- )
-
- # Add the summary instruction to the event stream
- logger.info(
- f'[GitLab] Sending summary instruction to conversation {conversation_id} {summary_event}'
- )
- await conversation_manager.send_event_to_conversation(
- conversation_id, summary_event
- )
-
- logger.info(
- f'[GitLab] Sent summary instruction to conversation {conversation_id} {summary_event}'
- )
-
- # Update the processor state
- self.send_summary_instruction = False
- callback.set_processor(self)
- callback.updated_at = datetime.now()
- async with a_session_maker() as session:
- session.merge(callback)
- await session.commit()
- return
-
- # Extract the summary from the event store
- logger.info(
- f'[GitLab] Extracting summary for conversation {conversation_id}'
- )
- summary = await extract_summary_from_conversation_manager(
- conversation_manager, conversation_id
- )
-
- # Send the summary to GitLab
- asyncio.create_task(self._send_message_to_gitlab(summary))
-
- logger.info(f'[GitLab] Summary sent for conversation {conversation_id}')
-
- # Mark callback as completed status
- callback.status = CallbackStatus.COMPLETED
- callback.updated_at = datetime.now()
- async with a_session_maker() as session:
- session.merge(callback)
- await session.commit()
-
- except Exception as e:
- logger.exception(
- f'[GitLab] Error processing conversation callback: {str(e)}'
- )
diff --git a/enterprise/server/conversation_callback_processor/jira_callback_processor.py b/enterprise/server/conversation_callback_processor/jira_callback_processor.py
deleted file mode 100644
index 987e04970a..0000000000
--- a/enterprise/server/conversation_callback_processor/jira_callback_processor.py
+++ /dev/null
@@ -1,154 +0,0 @@
-import asyncio
-
-from integrations.jira.jira_manager import JiraManager
-from integrations.utils import (
- extract_summary_from_conversation_manager,
- get_last_user_msg_from_conversation_manager,
- get_summary_instruction,
- markdown_to_jira_markup,
-)
-from server.auth.token_manager import TokenManager
-from storage.conversation_callback import (
- ConversationCallback,
- ConversationCallbackProcessor,
-)
-
-from openhands.core.logger import openhands_logger as logger
-from openhands.core.schema.agent import AgentState
-from openhands.events.action import MessageAction
-from openhands.events.observation.agent import AgentStateChangedObservation
-from openhands.events.serialization.event import event_to_dict
-from openhands.server.shared import conversation_manager
-
-token_manager = TokenManager()
-jira_manager = JiraManager(token_manager)
-integration_store = jira_manager.integration_store
-
-
-class JiraCallbackProcessor(ConversationCallbackProcessor):
- """
- Processor for sending conversation summaries to Jira.
-
- This processor is used to send summaries of conversations to Jira issues
- when agent state changes occur.
- """
-
- issue_key: str
- workspace_name: str
-
- async def _send_comment_to_jira(self, message: str) -> None:
- """Send a comment to Jira issue.
-
- Args:
- message: The message content to send to Jira
- """
- try:
- # Get workspace details to retrieve API credentials
- workspace = await jira_manager.integration_store.get_workspace_by_name(
- self.workspace_name
- )
- if not workspace:
- logger.error(f'[Jira] Workspace {self.workspace_name} not found')
- return
-
- if workspace.status != 'active':
- logger.error(f'[Jira] Workspace {workspace.id} is not active')
- return
-
- # Decrypt API key
- api_key = jira_manager.token_manager.decrypt_text(workspace.svc_acc_api_key)
-
- # Send comment directly as a string
- await jira_manager.send_message(
- message,
- issue_key=self.issue_key,
- jira_cloud_id=workspace.jira_cloud_id,
- svc_acc_email=workspace.svc_acc_email,
- svc_acc_api_key=api_key,
- )
-
- logger.info(
- f'[Jira] Sent summary comment to issue {self.issue_key} '
- f'(workspace {self.workspace_name})'
- )
- except Exception as e:
- logger.error(f'[Jira] Failed to send summary comment: {str(e)}')
-
- async def __call__(
- self,
- callback: ConversationCallback,
- observation: AgentStateChangedObservation,
- ) -> None:
- """
- Process a conversation event by sending a summary to Jira.
-
- Args:
- callback: The conversation callback
- observation: The AgentStateChangedObservation that triggered the callback
- """
- logger.info(f'[Jira] Callback agent state was {observation.agent_state}')
- if observation.agent_state not in (
- AgentState.AWAITING_USER_INPUT,
- AgentState.FINISHED,
- ):
- return
-
- conversation_id = callback.conversation_id
- try:
- logger.info(
- f'[Jira] Sending summary instruction for conversation {conversation_id}'
- )
-
- # Get the summary instruction
- summary_instruction = get_summary_instruction()
- summary_event = event_to_dict(MessageAction(content=summary_instruction))
-
- # Prevent infinite loops for summary callback that always sends instructions when agent stops
- # We should not request summary if the last message is the summary request
- last_user_msg = await get_last_user_msg_from_conversation_manager(
- conversation_manager, conversation_id
- )
- logger.info(
- 'last_user_msg',
- extra={
- 'last_user_msg': [m.content for m in last_user_msg],
- 'summary_instruction': summary_instruction,
- },
- )
- if (
- len(last_user_msg) > 0
- and last_user_msg[0].content == summary_instruction
- ):
- # Extract the summary from the event store
- logger.info(
- f'[Jira] Extracting summary for conversation {conversation_id}'
- )
- summary_markdown = await extract_summary_from_conversation_manager(
- conversation_manager, conversation_id
- )
-
- summary = markdown_to_jira_markup(summary_markdown)
-
- asyncio.create_task(self._send_comment_to_jira(summary))
-
- logger.info(f'[Jira] Summary sent for conversation {conversation_id}')
- return
-
- # Add the summary instruction to the event stream
- logger.info(
- f'[Jira] Sending summary instruction to conversation {conversation_id} {summary_event}'
- )
- await conversation_manager.send_event_to_conversation(
- conversation_id, summary_event
- )
-
- logger.info(
- f'[Jira] Sent summary instruction to conversation {conversation_id} {summary_event}'
- )
-
- except Exception:
- logger.error(
- '[Jira] Error processing conversation callback',
- exc_info=True,
- stack_info=True,
- )
diff --git a/enterprise/server/conversation_callback_processor/jira_dc_callback_processor.py b/enterprise/server/conversation_callback_processor/jira_dc_callback_processor.py
deleted file mode 100644
index 15c485a52a..0000000000
--- a/enterprise/server/conversation_callback_processor/jira_dc_callback_processor.py
+++ /dev/null
@@ -1,158 +0,0 @@
-import asyncio
-
-from integrations.jira_dc.jira_dc_manager import JiraDcManager
-from integrations.utils import (
- extract_summary_from_conversation_manager,
- get_last_user_msg_from_conversation_manager,
- get_summary_instruction,
- markdown_to_jira_markup,
-)
-from server.auth.token_manager import TokenManager
-from storage.conversation_callback import (
- ConversationCallback,
- ConversationCallbackProcessor,
-)
-
-from openhands.core.logger import openhands_logger as logger
-from openhands.core.schema.agent import AgentState
-from openhands.events.action import MessageAction
-from openhands.events.observation.agent import AgentStateChangedObservation
-from openhands.events.serialization.event import event_to_dict
-from openhands.server.shared import conversation_manager
-
-token_manager = TokenManager()
-jira_dc_manager = JiraDcManager(token_manager)
-
-
-class JiraDcCallbackProcessor(ConversationCallbackProcessor):
- """
- Processor for sending conversation summaries to Jira DC.
-
- This processor is used to send summaries of conversations to Jira DC issues
- when agent state changes occur.
- """
-
- issue_key: str
- workspace_name: str
- base_api_url: str
-
- async def _send_comment_to_jira_dc(self, message: str) -> None:
- """Send a comment to Jira DC issue.
-
- Args:
- message: The message content to send to Jira DC
- """
- try:
- # Get workspace details to retrieve API credentials
- workspace = await jira_dc_manager.integration_store.get_workspace_by_name(
- self.workspace_name
- )
- if not workspace:
- logger.error(f'[Jira DC] Workspace {self.workspace_name} not found')
- return
-
- if workspace.status != 'active':
- logger.error(f'[Jira DC] Workspace {workspace.id} is not active')
- return
-
- # Decrypt API key
- api_key = jira_dc_manager.token_manager.decrypt_text(
- workspace.svc_acc_api_key
- )
-
- # Send comment directly as a string
- await jira_dc_manager.send_message(
- message,
- issue_key=self.issue_key,
- base_api_url=self.base_api_url,
- svc_acc_api_key=api_key,
- )
-
- logger.info(
- f'[Jira DC] Sent summary comment to issue {self.issue_key} '
- f'(workspace {self.workspace_name})'
- )
- except Exception as e:
- logger.error(f'[Jira DC] Failed to send summary comment: {str(e)}')
-
- async def __call__(
- self,
- callback: ConversationCallback,
- observation: AgentStateChangedObservation,
- ) -> None:
- """
- Process a conversation event by sending a summary to Jira DC.
-
- Args:
- callback: The conversation callback
- observation: The AgentStateChangedObservation that triggered the callback
- """
- logger.info(f'[Jira DC] Callback agent state was {observation.agent_state}')
- if observation.agent_state not in (
- AgentState.AWAITING_USER_INPUT,
- AgentState.FINISHED,
- ):
- return
-
- conversation_id = callback.conversation_id
- try:
- logger.info(
- f'[Jira DC] Sending summary instruction for conversation {conversation_id}'
- )
-
- # Get the summary instruction
- summary_instruction = get_summary_instruction()
- summary_event = event_to_dict(MessageAction(content=summary_instruction))
-
- # Prevent infinite loops for summary callback that always sends instructions when agent stops
- # We should not request summary if the last message is the summary request
- last_user_msg = await get_last_user_msg_from_conversation_manager(
- conversation_manager, conversation_id
- )
- logger.info(
- 'last_user_msg',
- extra={
- 'last_user_msg': [m.content for m in last_user_msg],
- 'summary_instruction': summary_instruction,
- },
- )
- if (
- len(last_user_msg) > 0
- and last_user_msg[0].content == summary_instruction
- ):
- # Extract the summary from the event store
- logger.info(
- f'[Jira DC] Extracting summary for conversation {conversation_id}'
- )
-
- summary_markdown = await extract_summary_from_conversation_manager(
- conversation_manager, conversation_id
- )
-
- summary = markdown_to_jira_markup(summary_markdown)
-
- asyncio.create_task(self._send_comment_to_jira_dc(summary))
-
- logger.info(
- f'[Jira DC] Summary sent for conversation {conversation_id}'
- )
- return
-
- # Add the summary instruction to the event stream
- logger.info(
- f'[Jira DC] Sending summary instruction to conversation {conversation_id} {summary_event}'
- )
- await conversation_manager.send_event_to_conversation(
- conversation_id, summary_event
- )
-
- logger.info(
- f'[Jira DC] Sent summary instruction to conversation {conversation_id} {summary_event}'
- )
-
- except Exception:
- logger.error(
- '[Jira DC] Error processing conversation callback',
- exc_info=True,
- stack_info=True,
- )
diff --git a/enterprise/server/conversation_callback_processor/linear_callback_processor.py b/enterprise/server/conversation_callback_processor/linear_callback_processor.py
deleted file mode 100644
index c617ce32f4..0000000000
--- a/enterprise/server/conversation_callback_processor/linear_callback_processor.py
+++ /dev/null
@@ -1,152 +0,0 @@
-import asyncio
-
-from integrations.linear.linear_manager import LinearManager
-from integrations.utils import (
- extract_summary_from_conversation_manager,
- get_last_user_msg_from_conversation_manager,
- get_summary_instruction,
-)
-from server.auth.token_manager import TokenManager
-from storage.conversation_callback import (
- ConversationCallback,
- ConversationCallbackProcessor,
-)
-
-from openhands.core.logger import openhands_logger as logger
-from openhands.core.schema.agent import AgentState
-from openhands.events.action import MessageAction
-from openhands.events.observation.agent import AgentStateChangedObservation
-from openhands.events.serialization.event import event_to_dict
-from openhands.server.shared import conversation_manager
-
-token_manager = TokenManager()
-linear_manager = LinearManager(token_manager)
-
-
-class LinearCallbackProcessor(ConversationCallbackProcessor):
- """
- Processor for sending conversation summaries to Linear.
-
- This processor is used to send summaries of conversations to Linear issues
- when agent state changes occur.
- """
-
- issue_id: str
- issue_key: str
- workspace_name: str
-
- async def _send_comment_to_linear(self, message: str) -> None:
- """Send a comment to Linear issue.
-
- Args:
- message: The message content to send to Linear
- """
- try:
- # Get workspace details to retrieve API key
- workspace = await linear_manager.integration_store.get_workspace_by_name(
- self.workspace_name
- )
- if not workspace:
- logger.error(f'[Linear] Workspace {self.workspace_name} not found')
- return
-
- if workspace.status != 'active':
- logger.error(f'[Linear] Workspace {workspace.id} is not active')
- return
-
- # Decrypt API key
- api_key = linear_manager.token_manager.decrypt_text(
- workspace.svc_acc_api_key
- )
-
- # Send comment directly as a string
- await linear_manager.send_message(
- message,
- self.issue_id,
- api_key,
- )
-
- logger.info(
- f'[Linear] Sent summary comment to issue {self.issue_key} '
- f'(workspace {self.workspace_name})'
- )
- except Exception as e:
- logger.error(f'[Linear] Failed to send summary comment: {str(e)}')
-
- async def __call__(
- self,
- callback: ConversationCallback,
- observation: AgentStateChangedObservation,
- ) -> None:
- """
- Process a conversation event by sending a summary to Linear.
-
- Args:
- callback: The conversation callback
- observation: The AgentStateChangedObservation that triggered the callback
- """
- logger.info(f'[Linear] Callback agent state was {observation.agent_state}')
- if observation.agent_state not in (
- AgentState.AWAITING_USER_INPUT,
- AgentState.FINISHED,
- ):
- return
-
- conversation_id = callback.conversation_id
- try:
- logger.info(
- f'[Linear] Sending summary instruction for conversation {conversation_id}'
- )
-
- # Get the summary instruction
- summary_instruction = get_summary_instruction()
- summary_event = event_to_dict(MessageAction(content=summary_instruction))
-
- # Prevent infinite loops for summary callback that always sends instructions when agent stops
- # We should not request summary if the last message is the summary request
- last_user_msg = await get_last_user_msg_from_conversation_manager(
- conversation_manager, conversation_id
- )
- logger.info(
- 'last_user_msg',
- extra={
- 'last_user_msg': [m.content for m in last_user_msg],
- 'summary_instruction': summary_instruction,
- },
- )
- if (
- len(last_user_msg) > 0
- and last_user_msg[0].content == summary_instruction
- ):
- # Extract the summary from the event store
- logger.info(
- f'[Linear] Extracting summary for conversation {conversation_id}'
- )
- summary = await extract_summary_from_conversation_manager(
- conversation_manager, conversation_id
- )
-
- # Send the summary to Linear
- asyncio.create_task(self._send_comment_to_linear(summary))
-
- logger.info(f'[Linear] Summary sent for conversation {conversation_id}')
- return
-
- # Add the summary instruction to the event stream
- logger.info(
- f'[Linear] Sending summary instruction to conversation {conversation_id} {summary_event}'
- )
- await conversation_manager.send_event_to_conversation(
- conversation_id, summary_event
- )
-
- logger.info(
- f'[Linear] Sent summary instruction to conversation {conversation_id} {summary_event}'
- )
-
- except Exception:
- logger.error(
- '[Linear] Error processing conversation callback',
- exc_info=True,
- stack_info=True,
- )
diff --git a/enterprise/server/conversation_callback_processor/slack_callback_processor.py b/enterprise/server/conversation_callback_processor/slack_callback_processor.py
deleted file mode 100644
index ce7f06245c..0000000000
--- a/enterprise/server/conversation_callback_processor/slack_callback_processor.py
+++ /dev/null
@@ -1,179 +0,0 @@
-import asyncio
-
-from integrations.models import Message, SourceType
-from integrations.slack.slack_manager import SlackManager
-from integrations.slack.slack_view import SlackFactory
-from integrations.utils import (
- extract_summary_from_conversation_manager,
- get_last_user_msg_from_conversation_manager,
- get_summary_instruction,
-)
-from server.auth.token_manager import TokenManager
-from storage.conversation_callback import (
- ConversationCallback,
- ConversationCallbackProcessor,
-)
-
-from openhands.core.logger import openhands_logger as logger
-from openhands.core.schema.agent import AgentState
-from openhands.events.action import MessageAction
-from openhands.events.observation.agent import AgentStateChangedObservation
-from openhands.events.serialization.event import event_to_dict
-from openhands.server.shared import conversation_manager
-
-token_manager = TokenManager()
-slack_manager = SlackManager(token_manager)
-
-
-class SlackCallbackProcessor(ConversationCallbackProcessor):
- """Processor for sending conversation summaries to Slack.
-
- This processor is used to send summaries of conversations to Slack channels
- when agent state changes occur.
- """
-
- slack_user_id: str
- channel_id: str
- message_ts: str
- thread_ts: str | None
- team_id: str
- last_user_msg_id: int | None = None
-
- async def _send_message_to_slack(self, message: str) -> None:
- """Send a message to Slack.
-
- Args:
- message: The message content to send to Slack
- """
- try:
- # Create a message object for Slack view creation (incoming message format)
- message_obj = Message(
- source=SourceType.SLACK,
- message={
- 'slack_user_id': self.slack_user_id,
- 'channel_id': self.channel_id,
- 'message_ts': self.message_ts,
- 'thread_ts': self.thread_ts,
- 'team_id': self.team_id,
- 'user_msg': message,
- },
- )
-
- slack_user, saas_user_auth = await slack_manager.authenticate_user(
- self.slack_user_id
- )
- slack_view = await SlackFactory.create_slack_view_from_payload(
- message_obj, slack_user, saas_user_auth
- )
- # Send the message directly as a string
- await slack_manager.send_message(message, slack_view)
-
- logger.info(
- f'[Slack] Sent summary message to channel {self.channel_id} '
- f'for user {self.slack_user_id}'
- )
- except Exception as e:
- logger.error(f'[Slack] Failed to send summary message: {str(e)}')
-
- async def __call__(
- self,
- callback: ConversationCallback,
- observation: AgentStateChangedObservation,
- ) -> None:
- """
- Process a conversation event by sending a summary to Slack.
-
- Args:
- conversation_id: The ID of the conversation to process
- observation: The AgentStateChangedObservation that triggered the callback
- callback: The conversation callback
- """
- logger.info(f'[Slack] Callback agent state was {observation.agent_state}')
- if observation.agent_state not in (
- AgentState.AWAITING_USER_INPUT,
- AgentState.FINISHED,
- ):
- return
-
- conversation_id = callback.conversation_id
- try:
- logger.info(f'[Slack] Processing conversation {conversation_id}')
-
- # Get the summary instruction
- summary_instruction = get_summary_instruction()
- summary_event = event_to_dict(MessageAction(content=summary_instruction))
-
- # Prevent infinite loops for summary callback that always sends instructions when agent stops
- # We should not request summary if the last message is the summary request
- last_user_msg = await get_last_user_msg_from_conversation_manager(
- conversation_manager, conversation_id
- )
-
- # Check if we have any messages
- if len(last_user_msg) == 0:
- logger.info(
- f'[Slack] No messages found for conversation {conversation_id}'
- )
- return
-
- # Get the ID of the last user message
- current_msg_id = last_user_msg[0].id if last_user_msg else None
-
- logger.info(
- 'last_user_msg',
- extra={
- 'last_user_msg': [m.content for m in last_user_msg],
- 'summary_instruction': summary_instruction,
- 'current_msg_id': current_msg_id,
- 'last_user_msg_id': self.last_user_msg_id,
- },
- )
-
- # Check if the message ID has changed
- if current_msg_id == self.last_user_msg_id:
- logger.info(
- f'[Slack] Skipping processing as message ID has not changed: {current_msg_id}'
- )
- return
-
- # Update the last user message ID
- self.last_user_msg_id = current_msg_id
-
- # Update the processor in the callback and save to database
- callback.set_processor(self)
-
- logger.info(f'[Slack] Updated last_user_msg_id to {self.last_user_msg_id}')
-
- if last_user_msg[0].content == summary_instruction:
- # Extract the summary from the event store
- logger.info(
- f'[Slack] Extracting summary for conversation {conversation_id}'
- )
- summary = await extract_summary_from_conversation_manager(
- conversation_manager, conversation_id
- )
-
- # Send the summary to Slack
- asyncio.create_task(self._send_message_to_slack(summary))
-
- logger.info(f'[Slack] Summary sent for conversation {conversation_id}')
- return
-
- # Add the summary instruction to the event stream
- logger.info(
- f'[Slack] Sending summary instruction to conversation {conversation_id} {summary_event}'
- )
- await conversation_manager.send_event_to_conversation(
- conversation_id, summary_event
- )
-
- logger.info(
- f'[Slack] Sent summary instruction to conversation {conversation_id} {summary_event}'
- )
-
- except Exception:
- logger.error(
- '[Slack] Error processing conversation callback',
- exc_info=True,
- stack_info=True,
- )
diff --git a/enterprise/server/routes/auth.py b/enterprise/server/routes/auth.py
index 52aff28693..4d7e2dbc1b 100644
--- a/enterprise/server/routes/auth.py
+++ b/enterprise/server/routes/auth.py
@@ -31,7 +31,6 @@ from server.constants import (
DEPLOYMENT_MODE,
IS_FEATURE_ENV,
)
-from server.routes.event_webhook import _get_session_api_key, _get_user_id
from server.services.org_invitation_service import (
EmailMismatchError,
InvitationExpiredError,
@@ -39,6 +38,7 @@ from server.services.org_invitation_service import (
OrgInvitationService,
UserAlreadyMemberError,
)
+from server.utils.conversation_utils import get_session_api_key, get_user_id
from server.utils.rate_limit_utils import check_rate_limit_by_user_id
from server.utils.url_utils import get_cookie_domain, get_cookie_samesite, get_web_url
from sqlalchemy import select
@@ -770,8 +770,8 @@ async def refresh_tokens(
x_session_api_key: Annotated[str | None, Header(alias='X-Session-API-Key')],
) -> TokenResponse:
"""Return the latest token for a given provider."""
- user_id = _get_user_id(sid)
- session_api_key = await _get_session_api_key(user_id, sid)
+ user_id = get_user_id(sid)
+ session_api_key = await get_session_api_key(sid)
if session_api_key != x_session_api_key:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail='Forbidden')
diff --git a/enterprise/server/routes/event_webhook.py b/enterprise/server/routes/event_webhook.py
deleted file mode 100644
index 8c48d0a69f..0000000000
--- a/enterprise/server/routes/event_webhook.py
+++ /dev/null
@@ -1,247 +0,0 @@
-import base64
-import json
-from enum import Enum
-from typing import Annotated, Tuple
-
-from fastapi import (
- APIRouter,
- BackgroundTasks,
- Header,
- HTTPException,
- Request,
- Response,
- status,
-)
-from pydantic import BaseModel
-from server.logger import logger
-from server.utils.conversation_callback_utils import (
- process_event,
- update_agent_state,
- update_conversation_metadata,
- update_conversation_stats,
-)
-from storage.database import session_maker
-from storage.stored_conversation_metadata_saas import StoredConversationMetadataSaas
-
-from openhands.server.shared import conversation_manager
-
-event_webhook_router = APIRouter(prefix='/event-webhook')
-
-
-class BatchMethod(Enum):
- POST = 'POST'
- DELETE = 'DELETE'
-
-
-class BatchOperation(BaseModel):
- method: BatchMethod
- path: str
- content: str | None = None
- encoding: str | None = None
-
- def get_content(self) -> bytes:
- if self.content is None:
- raise ValueError('empty_content_in_batch')
- if self.encoding == 'base64':
- return base64.b64decode(self.content.encode('ascii'))
- return self.content.encode('utf-8')
-
- def get_content_json(self) -> dict:
- return json.loads(self.get_content())
-
-
-async def _process_batch_operations_background(
- batch_ops: list[BatchOperation],
- x_session_api_key: str | None,
-):
- """Background task to process batched webhook requests with multiple file operations"""
- prev_conversation_id = None
- user_id = None
-
- for batch_op in batch_ops:
- try:
- if batch_op.method != BatchMethod.POST:
- # Log unhandled methods for future implementation
- logger.info(
- 'invalid_operation_in_batch_webhook',
- extra={
- 'method': str(batch_op.method),
- 'path': batch_op.path,
- },
- )
- continue
-
- # Updates to certain paths in the nested runtime are ignored
- if batch_op.path in {'settings.json', 'secrets.json'}:
- continue
-
- conversation_id, subpath = _parse_conversation_id_and_subpath(batch_op.path)
-
- # If the conversation id changes, then we must recheck the session_api_key
- if conversation_id != prev_conversation_id:
- user_id = _get_user_id(conversation_id)
- session_api_key = await _get_session_api_key(user_id, conversation_id)
- prev_conversation_id = conversation_id
- if session_api_key != x_session_api_key:
- logger.error(
- 'authentication_failed_in_batch_webhook_background',
- extra={
- 'conversation_id': conversation_id,
- 'user_id': user_id,
- 'path': batch_op.path,
- },
- )
- continue # Skip this operation but continue with others
-
- if user_id is None:
- logger.error(
- 'user_id_not_set_in_batch_webhook',
- extra={
- 'conversation_id': conversation_id,
- 'path': batch_op.path,
- },
- )
- continue
-
- if subpath == 'agent_state.pkl':
- update_agent_state(user_id, conversation_id, batch_op.get_content())
- continue
-
- if subpath == 'conversation_stats.pkl':
- update_conversation_stats(
- user_id, conversation_id, batch_op.get_content()
- )
- continue
-
- if subpath == 'metadata.json':
- update_conversation_metadata(
- conversation_id, batch_op.get_content_json()
- )
- continue
-
- if subpath.startswith('events/'):
- await process_event(
- user_id, conversation_id, subpath, batch_op.get_content_json()
- )
- continue
-
- if subpath.startswith('event_cache'):
- # No action required
- continue
-
- # Log unhandled paths for future implementation
- logger.warning(
- 'unknown_path_in_batch_webhook',
- extra={
- 'path': subpath,
- 'user_id': user_id,
- 'conversation_id': conversation_id,
- },
- )
- except Exception as e:
- logger.error(
- f'error_processing_batch_operation: {type(e).__name__}: {e}',
- extra={
- 'path': batch_op.path,
- 'method': str(batch_op.method),
- },
- exc_info=True,
- )
-
-
-@event_webhook_router.post('/batch')
-async def on_batch_write(
- batch_ops: list[BatchOperation],
- background_tasks: BackgroundTasks,
- x_session_api_key: Annotated[str | None, Header()],
-):
- """Handle batched webhook requests with multiple file operations in background"""
- # Add the batch processing to background tasks
- background_tasks.add_task(
- _process_batch_operations_background,
- batch_ops,
- x_session_api_key,
- )
-
- # Return immediately
- return Response(status_code=status.HTTP_202_ACCEPTED)
-
-
-@event_webhook_router.post('/{path:path}')
-async def on_write(
- path: str,
- request: Request,
- x_session_api_key: Annotated[str | None, Header()],
-):
- """Handle writing conversation events and metadata"""
- conversation_id, subpath = _parse_conversation_id_and_subpath(path)
- user_id = _get_user_id(conversation_id)
-
- # Check the session API key to make sure this is from the correct conversation
- session_api_key = await _get_session_api_key(user_id, conversation_id)
- if session_api_key != x_session_api_key:
- return Response(status_code=status.HTTP_403_FORBIDDEN)
-
- if subpath == 'agent_state.pkl':
- content = await request.body()
- update_agent_state(user_id, conversation_id, content)
- return Response(status_code=status.HTTP_200_OK)
-
- try:
- content = await request.json()
- except Exception as exc:
- return Response(status_code=status.HTTP_400_BAD_REQUEST, content=str(exc))
-
- if subpath == 'metadata.json':
- update_conversation_metadata(conversation_id, content)
- return Response(status_code=status.HTTP_200_OK)
-
- if subpath.startswith('events/'):
- await process_event(user_id, conversation_id, subpath, content)
- return Response(status_code=status.HTTP_200_OK)
-
- if subpath.startswith('event_cache'):
- # No actionr required
- return Response(status_code=status.HTTP_200_OK)
-
- logger.error(
- 'invalid_subpath_in_webhook',
- extra={
- 'path': path,
- 'user_id': user_id,
- },
- )
- return Response(status_code=status.HTTP_400_BAD_REQUEST)
-
-
-@event_webhook_router.delete('/{path:path}')
-async def on_delete(path: str, x_session_api_key: Annotated[str | None, Header()]):
- return Response(status_code=status.HTTP_200_OK)
-
-
-def _parse_conversation_id_and_subpath(path: str) -> Tuple[str, str]:
- try:
- items = path.split('/')
- assert items[0] == 'sessions'
- conversation_id = items[1]
- subpath = '/'.join(items[2:])
- return conversation_id, subpath
- except (AssertionError, IndexError) as e:
- raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST) from e
-
-
-def _get_user_id(conversation_id: str) -> str:
- with session_maker() as session:
- conversation_metadata_saas = (
- session.query(StoredConversationMetadataSaas)
- .filter(StoredConversationMetadataSaas.conversation_id == conversation_id)
- .first()
- )
- return str(conversation_metadata_saas.user_id)
-
-
-async def _get_session_api_key(user_id: str, conversation_id: str) -> str | None:
- agent_loop_info = await conversation_manager.get_agent_loop_info(
- user_id, filter_to_sids={conversation_id}
- )
- return agent_loop_info[0].session_api_key
diff --git a/enterprise/server/routes/integration/linear.py b/enterprise/server/routes/integration/linear.py
deleted file mode 100644
index 2e23325398..0000000000
--- a/enterprise/server/routes/integration/linear.py
+++ /dev/null
@@ -1,681 +0,0 @@
-import json
-import os
-import re
-import uuid
-from typing import cast
-
-import requests
-from fastapi import APIRouter, BackgroundTasks, HTTPException, Request, status
-from fastapi.responses import JSONResponse, RedirectResponse
-from integrations.linear.linear_manager import LinearManager
-from integrations.models import Message, SourceType
-from pydantic import BaseModel, Field, field_validator
-from server.auth.constants import LINEAR_CLIENT_ID, LINEAR_CLIENT_SECRET
-from server.auth.saas_user_auth import SaasUserAuth
-from server.auth.token_manager import TokenManager
-from server.constants import WEB_HOST
-from storage.redis import create_redis_client
-
-from openhands.core.logger import openhands_logger as logger
-from openhands.server.user_auth.user_auth import get_user_auth
-
-# Environment variable to disable Linear webhooks
-LINEAR_WEBHOOKS_ENABLED = os.environ.get('LINEAR_WEBHOOKS_ENABLED', '0') in (
- '1',
- 'true',
-)
-LINEAR_REDIRECT_URI = f'https://{WEB_HOST}/integration/linear/callback'
-LINEAR_SCOPES = 'read'
-LINEAR_AUTH_URL = 'https://linear.app/oauth/authorize'
-LINEAR_TOKEN_URL = 'https://api.linear.app/oauth/token'
-LINEAR_GRAPHQL_URL = 'https://api.linear.app/graphql'
-
-
-# Request/Response models
-class LinearWorkspaceCreate(BaseModel):
- workspace_name: str = Field(..., description='Workspace display name')
- webhook_secret: str = Field(..., description='Webhook secret for verification')
- svc_acc_email: str = Field(..., description='Service account email')
- svc_acc_api_key: str = Field(..., description='Service account API key')
- is_active: bool = Field(
- default=False,
- description='Indicates if the workspace integration is active',
- )
-
- @field_validator('workspace_name')
- @classmethod
- def validate_workspace_name(cls, v):
- if not re.match(r'^[a-zA-Z0-9_.-]+$', v):
- raise ValueError(
- 'workspace_name can only contain alphanumeric characters, hyphens, underscores, and periods'
- )
- return v
-
- @field_validator('svc_acc_email')
- @classmethod
- def validate_svc_acc_email(cls, v):
- email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
- if not re.match(email_pattern, v):
- raise ValueError('svc_acc_email must be a valid email address')
- return v
-
- @field_validator('webhook_secret')
- @classmethod
- def validate_webhook_secret(cls, v):
- if ' ' in v:
- raise ValueError('webhook_secret cannot contain spaces')
- return v
-
- @field_validator('svc_acc_api_key')
- @classmethod
- def validate_svc_acc_api_key(cls, v):
- if ' ' in v:
- raise ValueError('svc_acc_api_key cannot contain spaces')
- return v
-
-
-class LinearLinkCreate(BaseModel):
- workspace_name: str = Field(
- ..., description='Name of the Linear workspace to link to'
- )
-
- @field_validator('workspace_name')
- @classmethod
- def validate_workspace(cls, v):
- if not re.match(r'^[a-zA-Z0-9_.-]+$', v):
- raise ValueError(
- 'workspace can only contain alphanumeric characters, hyphens, underscores, and periods'
- )
- return v
-
-
-class LinearWorkspaceResponse(BaseModel):
- id: int
- name: str
- linear_org_id: str
- status: str
- editable: bool
- created_at: str
- updated_at: str
-
-
-class LinearUserResponse(BaseModel):
- id: int
- keycloak_user_id: str
- linear_workspace_id: int
- status: str
- created_at: str
- updated_at: str
- workspace: LinearWorkspaceResponse
-
-
-class LinearValidateWorkspaceResponse(BaseModel):
- name: str
- status: str
- message: str
-
-
-linear_integration_router = APIRouter(prefix='/integration/linear')
-token_manager = TokenManager()
-linear_manager = LinearManager(token_manager)
-redis_client = create_redis_client()
-
-
-async def _handle_workspace_link_creation(
- user_id: str, linear_user_id: str, target_workspace: str
-):
- """Handle the creation or reactivation of a workspace link for a user."""
- # Verify workspace exists and is active
- workspace = await linear_manager.integration_store.get_workspace_by_name(
- target_workspace
- )
- if not workspace:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f'Workspace "{target_workspace}" not found',
- )
-
- if workspace.status.lower() != 'active':
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail=f'Workspace "{target_workspace}" is not active',
- )
-
- # Check if user currently has an active workspace link
- existing_user = await linear_manager.integration_store.get_user_by_active_workspace(
- user_id
- )
-
- if existing_user:
- # User has an active link - check if it's to the same workspace
- if existing_user.linear_workspace_id == workspace.id:
- # Already linked to this workspace, nothing to do
- return
- else:
- # User is trying to link to a different workspace while having an active link
- # This is not allowed - they must unlink first
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail='You already have an active workspace link. Please unlink from your current workspace before linking to a different one.',
- )
-
- # Check if user had a previous link to this specific workspace
- existing_link = (
- await linear_manager.integration_store.get_user_by_keycloak_id_and_workspace(
- user_id, workspace.id
- )
- )
-
- if existing_link:
- # Reactivate previous link to this workspace
- await linear_manager.integration_store.update_user_integration_status(
- user_id, 'active'
- )
- else:
- # Create new workspace link
- await linear_manager.integration_store.create_workspace_link(
- keycloak_user_id=user_id,
- linear_user_id=linear_user_id,
- linear_workspace_id=workspace.id,
- )
-
-
-async def _validate_workspace_update_permissions(user_id: str, target_workspace: str):
- """Validate that user can update the target workspace."""
- workspace = await linear_manager.integration_store.get_workspace_by_name(
- target_workspace
- )
- if not workspace:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f'Workspace "{target_workspace}" not found',
- )
-
- # Check if user is the admin of the workspace
- if workspace.admin_user_id != user_id:
- raise HTTPException(
- status_code=status.HTTP_403_FORBIDDEN,
- detail='You do not have permission to update this workspace',
- )
-
- # Check if user's current link matches the workspace
- current_user_link = (
- await linear_manager.integration_store.get_user_by_active_workspace(user_id)
- )
- if current_user_link and current_user_link.linear_workspace_id != workspace.id:
- raise HTTPException(
- status_code=status.HTTP_403_FORBIDDEN,
- detail='You can only update the workspace you are currently linked to',
- )
-
- return workspace
-
-
-@linear_integration_router.post('/events')
-async def linear_events(
- request: Request,
- background_tasks: BackgroundTasks,
-):
- """Handle Linear webhook events."""
- # Check if Linear webhooks are enabled
- if not LINEAR_WEBHOOKS_ENABLED:
- logger.info(
- 'Linear webhooks are disabled by LINEAR_WEBHOOKS_ENABLED environment variable'
- )
- return JSONResponse(
- status_code=200,
- content={'message': 'Linear webhooks are currently disabled.'},
- )
-
- try:
- signature_valid, signature, payload = await linear_manager.validate_request(
- request
- )
-
- if not signature_valid:
- logger.warning('[Linear] Invalid webhook signature')
- raise HTTPException(status_code=403, detail='Invalid webhook signature!')
-
- # Check for duplicate requests using Redis
- key = f'linear:{signature}'
- keyExists = redis_client.exists(key)
- if keyExists:
- logger.info(f'Received duplicate Linear webhook event: {signature}')
- return JSONResponse({'success': True})
- else:
- redis_client.setex(key, 60, 1)
-
- # Process the webhook
- message_payload = {'payload': payload}
- message = Message(source=SourceType.LINEAR, message=message_payload)
-
- background_tasks.add_task(linear_manager.receive_message, message)
-
- return JSONResponse({'success': True})
-
- except HTTPException:
- # Re-raise HTTP exceptions (like signature verification failures)
- raise
- except Exception as e:
- logger.exception(f'Error processing Linear webhook: {e}')
- return JSONResponse(
- status_code=500,
- content={'error': 'Internal server error processing webhook.'},
- )
-
-
-@linear_integration_router.post('/workspaces')
-async def create_linear_workspace(
- request: Request, workspace_data: LinearWorkspaceCreate
-):
- """Create a new Linear workspace registration."""
- try:
- user_auth = cast(SaasUserAuth, await get_user_auth(request))
- user_id = await user_auth.get_user_id()
- user_email = await user_auth.get_user_email()
-
- state = str(uuid.uuid4())
-
- integration_session = {
- 'operation_type': 'workspace_integration',
- 'keycloak_user_id': user_id,
- 'user_email': user_email,
- 'target_workspace': workspace_data.workspace_name,
- 'webhook_secret': workspace_data.webhook_secret,
- 'svc_acc_email': workspace_data.svc_acc_email,
- 'svc_acc_api_key': workspace_data.svc_acc_api_key,
- 'is_active': workspace_data.is_active,
- 'state': state,
- }
-
- created = redis_client.setex(
- state,
- 60,
- json.dumps(integration_session),
- )
-
- if not created:
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail='Failed to create integration session',
- )
-
- auth_params = {
- 'client_id': LINEAR_CLIENT_ID,
- 'redirect_uri': LINEAR_REDIRECT_URI,
- 'scope': LINEAR_SCOPES,
- 'state': state,
- 'response_type': 'code',
- }
-
- auth_url = f"{LINEAR_AUTH_URL}?{'&'.join([f'{k}={v}' for k, v in auth_params.items()])}"
-
- return JSONResponse(
- content={
- 'success': True,
- 'redirect': True,
- 'authorizationUrl': auth_url,
- }
- )
-
- except HTTPException:
- raise
- except Exception as e:
- logger.exception(f'Error creating Linear workspace: {e}')
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail='Failed to create workspace',
- )
-
-
-@linear_integration_router.post('/workspaces/link')
-async def create_workspace_link(request: Request, link_data: LinearLinkCreate):
- """Register a user mapping to a Linear workspace."""
- try:
- user_auth = cast(SaasUserAuth, await get_user_auth(request))
- user_id = await user_auth.get_user_id()
- user_email = await user_auth.get_user_email()
-
- state = str(uuid.uuid4())
-
- integration_session = {
- 'operation_type': 'workspace_link',
- 'keycloak_user_id': user_id,
- 'user_email': user_email,
- 'target_workspace': link_data.workspace_name,
- 'state': state,
- }
-
- created = redis_client.setex(
- state,
- 60,
- json.dumps(integration_session),
- )
-
- if not created:
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail='Failed to create integration session',
- )
-
- auth_params = {
- 'client_id': LINEAR_CLIENT_ID,
- 'redirect_uri': LINEAR_REDIRECT_URI,
- 'scope': LINEAR_SCOPES,
- 'state': state,
- 'response_type': 'code',
- }
-
- auth_url = f"{LINEAR_AUTH_URL}?{'&'.join([f'{k}={v}' for k, v in auth_params.items()])}"
-
- return JSONResponse(
- content={
- 'success': True,
- 'redirect': True,
- 'authorizationUrl': auth_url,
- }
- )
-
- except HTTPException:
- raise
- except Exception as e:
- logger.exception(f'Error registering Linear user: {e}')
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail='Failed to register user',
- )
-
-
-@linear_integration_router.get('/callback')
-async def linear_callback(request: Request, code: str, state: str):
- integration_session_json = redis_client.get(state)
- if not integration_session_json:
- raise HTTPException(
- status_code=400, detail='No active integration session found.'
- )
-
- integration_session = json.loads(integration_session_json)
-
- # Security check: verify the state parameter
- if integration_session.get('state') != state:
- raise HTTPException(
- status_code=400, detail='State mismatch. Possible CSRF attack.'
- )
-
- token_payload = {
- 'grant_type': 'authorization_code',
- 'client_id': LINEAR_CLIENT_ID,
- 'client_secret': LINEAR_CLIENT_SECRET,
- 'code': code,
- 'redirect_uri': LINEAR_REDIRECT_URI,
- }
- response = requests.post(LINEAR_TOKEN_URL, data=token_payload)
- if response.status_code != 200:
- raise HTTPException(
- status_code=400, detail=f'Error fetching token: {response.text}'
- )
-
- token_data = response.json()
- access_token = token_data['access_token']
-
- # Query Linear API to get workspace information
- headers = {'Authorization': f'Bearer {access_token}'}
- graphql_query = {
- 'query': '{ viewer { id name email organization { id name urlKey } } }'
- }
- response = requests.post(LINEAR_GRAPHQL_URL, json=graphql_query, headers=headers)
-
- if response.status_code != 200:
- raise HTTPException(
- status_code=400, detail=f'Error fetching workspace: {response.text}'
- )
-
- workspace_data = response.json()
- workspace_info = (
- workspace_data.get('data', {}).get('viewer', {}).get('organization', {})
- )
- workspace_name = workspace_info.get('urlKey', '').lower()
- linear_org_id = workspace_info.get('id', '')
-
- target_workspace = integration_session.get('target_workspace')
-
- # Verify user has access to the target workspace
- if workspace_name != target_workspace.lower():
- raise HTTPException(
- status_code=401,
- detail=f'User is not authorized to access workspace: {target_workspace}',
- )
-
- user_id = integration_session['keycloak_user_id']
- linear_user_id = workspace_data.get('data', {}).get('viewer', {}).get('id')
-
- if integration_session.get('operation_type') == 'workspace_integration':
- workspace = await linear_manager.integration_store.get_workspace_by_name(
- target_workspace
- )
- if not workspace:
- # Create new workspace if it doesn't exist
- encrypted_webhook_secret = token_manager.encrypt_text(
- integration_session['webhook_secret']
- )
- encrypted_svc_acc_api_key = token_manager.encrypt_text(
- integration_session['svc_acc_api_key']
- )
-
- await linear_manager.integration_store.create_workspace(
- name=target_workspace,
- linear_org_id=linear_org_id,
- admin_user_id=integration_session['keycloak_user_id'],
- encrypted_webhook_secret=encrypted_webhook_secret,
- svc_acc_email=integration_session['svc_acc_email'],
- encrypted_svc_acc_api_key=encrypted_svc_acc_api_key,
- status='active' if integration_session['is_active'] else 'inactive',
- )
-
- # Create a workspace link for the user (admin automatically gets linked)
- await _handle_workspace_link_creation(
- user_id, linear_user_id, target_workspace
- )
- else:
- # Workspace exists - validate user can update it
- await _validate_workspace_update_permissions(user_id, target_workspace)
-
- encrypted_webhook_secret = token_manager.encrypt_text(
- integration_session['webhook_secret']
- )
- encrypted_svc_acc_api_key = token_manager.encrypt_text(
- integration_session['svc_acc_api_key']
- )
-
- # Update workspace details
- await linear_manager.integration_store.update_workspace(
- id=workspace.id,
- linear_org_id=linear_org_id,
- encrypted_webhook_secret=encrypted_webhook_secret,
- svc_acc_email=integration_session['svc_acc_email'],
- encrypted_svc_acc_api_key=encrypted_svc_acc_api_key,
- status='active' if integration_session['is_active'] else 'inactive',
- )
-
- await _handle_workspace_link_creation(
- user_id, linear_user_id, target_workspace
- )
-
- return RedirectResponse(
- url='/settings/integrations',
- status_code=status.HTTP_302_FOUND,
- )
- elif integration_session.get('operation_type') == 'workspace_link':
- await _handle_workspace_link_creation(user_id, linear_user_id, target_workspace)
- return RedirectResponse(
- url='/settings/integrations', status_code=status.HTTP_302_FOUND
- )
- else:
- raise HTTPException(status_code=400, detail='Invalid operation type')
-
-
-@linear_integration_router.get(
- '/workspaces/link',
- response_model=LinearUserResponse,
-)
-async def get_current_workspace_link(request: Request):
- """Get current user's Linear integration details."""
- try:
- user_auth = cast(SaasUserAuth, await get_user_auth(request))
- user_id = await user_auth.get_user_id()
- if not user_id:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail='User not authenticated',
- )
-
- user = await linear_manager.integration_store.get_user_by_active_workspace(
- user_id
- )
- if not user:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail='User is not registered for Linear integration',
- )
-
- workspace = await linear_manager.integration_store.get_workspace_by_id(
- user.linear_workspace_id
- )
- if not workspace:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail='Workspace not found for the user',
- )
-
- return LinearUserResponse(
- id=user.id,
- keycloak_user_id=user.keycloak_user_id,
- linear_workspace_id=user.linear_workspace_id,
- status=user.status,
- created_at=user.created_at.isoformat(),
- updated_at=user.updated_at.isoformat(),
- workspace=LinearWorkspaceResponse(
- id=workspace.id,
- name=workspace.name,
- linear_org_id=workspace.linear_org_id,
- status=workspace.status,
- editable=workspace.admin_user_id == user.keycloak_user_id,
- created_at=workspace.created_at.isoformat(),
- updated_at=workspace.updated_at.isoformat(),
- ),
- )
-
- except HTTPException:
- raise
- except Exception as e:
- logger.exception(f'Error retrieving Linear user: {e}')
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail='Failed to retrieve user',
- )
-
-
-@linear_integration_router.post('/workspaces/unlink')
-async def unlink_workspace(request: Request):
- """Unlink user from Linear integration by setting status to inactive."""
- try:
- user_auth = cast(SaasUserAuth, await get_user_auth(request))
- user_id = await user_auth.get_user_id()
- if not user_id:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail='User not authenticated',
- )
-
- user = await linear_manager.integration_store.get_user_by_active_workspace(
- user_id
- )
- if not user:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail='User is not registered for Linear integration',
- )
-
- workspace = await linear_manager.integration_store.get_workspace_by_id(
- user.linear_workspace_id
- )
- if not workspace:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail='Workspace not found for the user',
- )
-
- if workspace.admin_user_id == user_id:
- await linear_manager.integration_store.deactivate_workspace(
- workspace_id=workspace.id,
- )
- else:
- await linear_manager.integration_store.update_user_integration_status(
- user_id, 'inactive'
- )
-
- return JSONResponse({'success': True})
-
- except HTTPException:
- raise
- except Exception as e:
- logger.exception(f'Error unlinking Linear user: {e}')
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail='Failed to unlink user',
- )
-
-
-@linear_integration_router.get(
- '/workspaces/validate/{workspace_name}',
- response_model=LinearValidateWorkspaceResponse,
-)
-async def validate_workspace_integration(request: Request, workspace_name: str):
- """Validate if the workspace has an active Linear integration."""
- try:
- # Validate workspace_name format
- if not re.match(r'^[a-zA-Z0-9_.-]+$', workspace_name):
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail='workspace_name can only contain alphanumeric characters, hyphens, underscores, and periods',
- )
-
- user_auth = cast(SaasUserAuth, await get_user_auth(request))
- user_email = await user_auth.get_user_email()
- if not user_email:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail='Unable to retrieve user email',
- )
-
- # Check if workspace exists
- workspace = await linear_manager.integration_store.get_workspace_by_name(
- workspace_name
- )
- if not workspace:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Workspace with name '{workspace_name}' not found",
- )
-
- # Check if workspace is active
- if workspace.status.lower() != 'active':
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Workspace '{workspace.name}' is not active",
- )
-
- return LinearValidateWorkspaceResponse(
- name=workspace.name,
- status=workspace.status,
- message='Workspace integration is active',
- )
-
- except HTTPException:
- raise
- except Exception as e:
- logger.exception(f'Error validating Linear workspace: {e}')
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail='Failed to validate workspace',
- )
diff --git a/enterprise/server/saas_nested_conversation_manager.py b/enterprise/server/saas_nested_conversation_manager.py
deleted file mode 100644
index 1e3e26c9ac..0000000000
--- a/enterprise/server/saas_nested_conversation_manager.py
+++ /dev/null
@@ -1,1201 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-import contextlib
-import json
-import os
-from dataclasses import dataclass
-from datetime import UTC, datetime, timedelta
-from enum import Enum
-from types import MappingProxyType
-from typing import Any, cast
-
-import httpx
-import socketio
-from pydantic import SecretStr
-from server.auth.token_manager import TokenManager
-from server.constants import PERMITTED_CORS_ORIGINS, WEB_HOST
-from server.utils.conversation_callback_utils import (
- process_event,
- update_conversation_metadata,
-)
-from sqlalchemy import select
-from storage.api_key_store import ApiKeyStore
-from storage.database import a_session_maker
-from storage.stored_conversation_metadata import StoredConversationMetadata
-from storage.stored_conversation_metadata_saas import StoredConversationMetadataSaas
-
-from openhands.controller.agent import Agent
-from openhands.core.config import LLMConfig, OpenHandsConfig
-from openhands.core.config.mcp_config import MCPConfig, RemoteMCPServer
-from openhands.core.logger import openhands_logger as logger
-from openhands.events.action import MessageAction
-from openhands.events.event_store import EventStore
-from openhands.events.serialization.event import event_to_dict
-from openhands.integrations.provider import (
- PROVIDER_TOKEN_TYPE,
- ProviderHandler,
- ProviderToken,
-)
-from openhands.runtime.impl.remote.remote_runtime import RemoteRuntime
-from openhands.runtime.plugins.vscode import VSCodeRequirement
-from openhands.runtime.runtime_status import RuntimeStatus
-from openhands.server.config.server_config import ServerConfig
-from openhands.server.constants import ROOM_KEY
-from openhands.server.conversation_manager.conversation_manager import (
- ConversationManager,
-)
-from openhands.server.data_models.agent_loop_info import AgentLoopInfo
-from openhands.server.monitoring import MonitoringListener
-from openhands.server.session import Session
-from openhands.server.session.conversation import ServerConversation
-from openhands.server.session.conversation_init_data import ConversationInitData
-from openhands.storage.conversation.conversation_store import ConversationStore
-from openhands.storage.data_models.conversation_metadata import ConversationMetadata
-from openhands.storage.data_models.conversation_status import ConversationStatus
-from openhands.storage.data_models.settings import Settings
-from openhands.storage.files import FileStore
-from openhands.storage.locations import (
- get_conversation_event_filename,
- get_conversation_events_dir,
-)
-from openhands.utils.http_session import httpx_verify_option
-from openhands.utils.import_utils import get_impl
-from openhands.utils.shutdown_listener import should_continue
-from openhands.utils.utils import create_registry_and_conversation_stats
-
-# Pattern for accessing runtime pods externally
-RUNTIME_URL_PATTERN = os.getenv(
- 'RUNTIME_URL_PATTERN', 'https://{runtime_id}.prod-runtime.all-hands.dev'
-)
-RUNTIME_ROUTING_MODE = os.getenv('RUNTIME_ROUTING_MODE', 'subdomain').lower()
-
-# Pattern for base URL for the runtime
-RUNTIME_CONVERSATION_URL = RUNTIME_URL_PATTERN + (
- '/runtime/api/conversations/{conversation_id}'
- if RUNTIME_ROUTING_MODE == 'path'
- else '/api/conversations/{conversation_id}'
-)
-
-RUNTIME_USERNAME = os.getenv('RUNTIME_USERNAME')
-
-SU_TO_USER = os.getenv('SU_TO_USER', 'false')
-truthy = {'1', 'true', 't', 'yes', 'y', 'on'}
-SU_TO_USER = str(SU_TO_USER.lower() in truthy).lower()
-
-DISABLE_VSCODE_PLUGIN = os.getenv('DISABLE_VSCODE_PLUGIN', 'false').lower() == 'true'
-
-# Time in seconds before a Redis entry is considered expired if not refreshed
-_REDIS_ENTRY_TIMEOUT_SECONDS = 300
-
-# Time in seconds between pulls
-_POLLING_INTERVAL = 10
-
-# Timeout for http operations
-_HTTP_TIMEOUT = 15
-
-
-class EventRetrieval(Enum):
- """Determine mode for getting events out of the nested runtime back into the main app."""
-
- WEBHOOK_PUSH = 'WEBHOOK_PUSH'
- POLLING = 'POLLING'
- NONE = 'NONE'
-
-
-@dataclass
-class SaasNestedConversationManager(ConversationManager):
- """Conversation manager where the agent loops exist inside the remote containers."""
-
- sio: socketio.AsyncServer
- config: OpenHandsConfig
- server_config: ServerConfig
- file_store: FileStore
- event_retrieval: EventRetrieval
- _conversation_store_class: type[ConversationStore] | None = None
- _event_polling_task: asyncio.Task | None = None
- _runtime_container_image: str | None = None
-
- async def __aenter__(self):
- if self.event_retrieval == EventRetrieval.POLLING:
- self._event_polling_task = asyncio.create_task(self._poll_events())
- return self
-
- async def __aexit__(self, exc_type, exc_value, traceback):
- if self._event_polling_task:
- self._event_polling_task.cancel()
- self._event_polling_task = None
-
- async def attach_to_conversation(
- self, sid: str, user_id: str | None = None
- ) -> ServerConversation | None:
- # Not supported - clients should connect directly to the nested server!
- raise ValueError('unsupported_operation')
-
- async def detach_from_conversation(self, conversation: ServerConversation):
- # Not supported - clients should connect directly to the nested server!
- raise ValueError('unsupported_operation')
-
- async def join_conversation(
- self,
- sid: str,
- connection_id: str,
- settings: Settings,
- user_id: str | None,
- ) -> AgentLoopInfo:
- # Not supported - clients should connect directly to the nested server!
- raise ValueError('unsupported_operation')
-
- def get_agent_session(self, sid: str):
- raise ValueError('unsupported_operation')
-
- async def get_running_agent_loops(
- self, user_id: str | None = None, filter_to_sids: set[str] | None = None
- ) -> set[str]:
- """
- Get the running agent loops directly from the remote runtime.
- """
- conversation_ids = await self._get_all_running_conversation_ids()
-
- if filter_to_sids is not None:
- conversation_ids = {
- conversation_id
- for conversation_id in conversation_ids
- if conversation_id in filter_to_sids
- }
-
- if user_id:
- user_conversation_ids = await self._get_recent_conversation_ids_for_user(
- user_id
- )
- conversation_ids = conversation_ids.intersection(user_conversation_ids)
-
- return conversation_ids
-
- async def is_agent_loop_running(self, sid: str) -> bool:
- """Check if an agent loop is running for the given session ID."""
- runtime = await self._get_runtime(sid)
- if runtime is None:
- return False
- result = runtime.get('status') == 'running'
- return result
-
- async def get_connections(
- self, user_id: str | None = None, filter_to_sids: set[str] | None = None
- ) -> dict[str, str]:
- # We don't monitor connections outside the nested server, though we could introduce an API for this.
- results: dict[str, str] = {}
- return results
-
- async def maybe_start_agent_loop(
- self,
- sid: str,
- settings: Settings,
- user_id: str, # type: ignore[override]
- initial_user_msg: MessageAction | None = None,
- replay_json: str | None = None,
- ) -> AgentLoopInfo:
- # First we check redis to see if we are already starting - or the runtime will tell us the session is stopped
- redis = self._get_redis_client()
- key = self._get_redis_conversation_key(user_id, sid)
- starting = await redis.get(key)
-
- runtime = await self._get_runtime(sid)
-
- nested_url = None
- session_api_key = None
- status = ConversationStatus.STOPPED
- event_store = EventStore(sid, self.file_store, user_id)
- if runtime:
- nested_url = self._get_nested_url_for_runtime(runtime['runtime_id'], sid)
- session_api_key = runtime.get('session_api_key')
- status_str = (runtime.get('status') or 'stopped').upper()
- if status_str in ConversationStatus:
- status = ConversationStatus[status_str]
- if status is ConversationStatus.STOPPED and starting:
- status = ConversationStatus.STARTING
-
- if status is ConversationStatus.STOPPED:
- # Mark the agentloop as starting in redis
- await redis.set(key, 1, ex=_REDIS_ENTRY_TIMEOUT_SECONDS)
-
- # Start the agent loop in the background
- asyncio.create_task(
- self._start_agent_loop(
- sid, settings, user_id, initial_user_msg, replay_json
- )
- )
-
- return AgentLoopInfo(
- conversation_id=sid,
- url=nested_url,
- session_api_key=session_api_key,
- event_store=event_store,
- status=status,
- )
-
- async def _refresh_provider_tokens_after_runtime_init(
- self, settings: Settings, sid: str, user_id: str | None = None
- ) -> Settings:
- """Refresh provider tokens after runtime initialization.
-
- During runtime initialization, tokens may be refreshed by Runtime.__init__().
- This method retrieves the fresh tokens from the database and creates a new
- settings object with updated tokens to avoid sending stale tokens to the
- nested runtime.
-
- The method handles two scenarios:
- 1. ProviderToken has user_id (IDP user ID, e.g., GitLab user ID)
- β†’ Uses get_idp_token_from_idp_user_id()
- 2. ProviderToken has no user_id but Keycloak user_id is available
- β†’ Uses load_offline_token() + get_idp_token_from_offline_token()
-
- Args:
- settings: The conversation settings that may contain provider tokens
- sid: The session ID for logging purposes
- user_id: The Keycloak user ID (optional, used as fallback when
- ProviderToken.user_id is not available)
-
- Returns:
- Updated settings with fresh provider tokens, or original settings
- if no update is needed
- """
- if not isinstance(settings, ConversationInitData):
- return settings
-
- if not settings.git_provider_tokens:
- return settings
-
- token_manager = TokenManager()
- updated_tokens = {}
- tokens_refreshed = 0
- tokens_failed = 0
-
- for provider_type, provider_token in settings.git_provider_tokens.items():
- fresh_token = None
-
- try:
- if provider_token.user_id:
- # Case 1: We have IDP user ID (e.g., GitLab user ID '32546706')
- # Get the token that was just refreshed during runtime initialization
- fresh_token = await token_manager.get_idp_token_from_idp_user_id(
- provider_token.user_id, provider_type
- )
- elif user_id:
- # Case 2: We have Keycloak user ID but no IDP user ID
- # This happens in web UI flow where ProviderToken.user_id is None
- offline_token = await token_manager.load_offline_token(user_id)
- if offline_token:
- fresh_token = (
- await token_manager.get_idp_token_from_offline_token(
- offline_token, provider_type
- )
- )
-
- if fresh_token:
- updated_tokens[provider_type] = ProviderToken(
- token=SecretStr(fresh_token),
- user_id=provider_token.user_id,
- host=provider_token.host,
- )
- tokens_refreshed += 1
- else:
- # Keep original token if we couldn't get a fresh one
- updated_tokens[provider_type] = provider_token
-
- except Exception as e:
- # If refresh fails, use original token to prevent conversation startup failure
- logger.warning(
- f'Failed to refresh {provider_type.value} token: {e}',
- extra={'session_id': sid, 'provider': provider_type.value},
- exc_info=True,
- )
- updated_tokens[provider_type] = provider_token
- tokens_failed += 1
-
- # Create new ConversationInitData with updated tokens
- # We cannot modify the frozen field directly, so we create a new object
- updated_settings = settings.model_copy(
- update={'git_provider_tokens': MappingProxyType(updated_tokens)}
- )
-
- logger.info(
- 'Updated provider tokens after runtime creation',
- extra={
- 'session_id': sid,
- 'providers': [p.value for p in updated_tokens.keys()],
- 'refreshed': tokens_refreshed,
- 'failed': tokens_failed,
- },
- )
- return updated_settings
-
- async def _start_agent_loop(
- self, sid, settings, user_id, initial_user_msg=None, replay_json=None
- ):
- try:
- logger.info(f'starting_agent_loop:{sid}', extra={'session_id': sid})
- await self.ensure_num_conversations_below_limit(sid, user_id)
- provider_handler = self._get_provider_handler(settings)
- runtime = await self._create_runtime(
- sid, user_id, settings, provider_handler
- )
- await runtime.connect()
-
- if not self._runtime_container_image:
- self._runtime_container_image = getattr(
- runtime,
- 'container_image',
- self.config.sandbox.runtime_container_image,
- )
-
- session_api_key = runtime.session.headers['X-Session-API-Key']
-
- # Update provider tokens with fresh ones after runtime creation
- settings = await self._refresh_provider_tokens_after_runtime_init(
- settings, sid, user_id
- )
-
- await self._start_conversation(
- sid,
- user_id,
- settings,
- initial_user_msg,
- replay_json,
- runtime.runtime_url,
- session_api_key,
- )
- finally:
- # remove the starting entry from redis
- redis = self._get_redis_client()
- key = self._get_redis_conversation_key(user_id, sid)
- await redis.delete(key)
-
- async def _start_conversation(
- self,
- sid: str,
- user_id: str,
- settings: Settings,
- initial_user_msg: MessageAction | None,
- replay_json: str | None,
- api_url: str,
- session_api_key: str,
- ):
- logger.info('starting_nested_conversation', extra={'sid': sid})
- async with httpx.AsyncClient(
- verify=httpx_verify_option(),
- headers={
- 'X-Session-API-Key': session_api_key,
- },
- ) as client:
- await self._setup_nested_settings(client, api_url, settings)
- await self._setup_provider_tokens(client, api_url, settings)
- await self._setup_custom_secrets(client, api_url, settings.custom_secrets) # type: ignore
- await self._create_nested_conversation(
- client, api_url, sid, user_id, settings, initial_user_msg, replay_json
- )
- await self._wait_for_conversation_ready(client, api_url, sid)
-
- async def _setup_nested_settings(
- self, client: httpx.AsyncClient, api_url: str, settings: Settings
- ) -> None:
- """Setup the settings for the nested conversation."""
- settings_json = settings.model_dump(context={'expose_secrets': True})
- settings_json.pop('custom_secrets', None)
- settings_json.pop('git_provider_tokens', None)
- if settings_json.get('git_provider'):
- settings_json['git_provider'] = settings_json['git_provider'].value
- settings_json.pop('secrets_store', None)
- response = await client.post(f'{api_url}/api/settings', json=settings_json)
- response.raise_for_status()
-
- async def _setup_provider_tokens(
- self, client: httpx.AsyncClient, api_url: str, settings: Settings
- ):
- """Setup provider tokens for the nested conversation.
-
- Note: Token validation happens in the nested runtime. If tokens are revoked,
- the nested runtime will return 401. The caller should handle token refresh
- and retry if needed.
- """
- provider_handler = self._get_provider_handler(settings)
- provider_tokens = provider_handler.provider_tokens
- if provider_tokens:
- provider_tokens_json = {
- k.value: {
- 'token': v.token.get_secret_value(),
- 'user_id': v.user_id,
- 'host': v.host,
- }
- for k, v in provider_tokens.items()
- if v.token
- }
- response = await client.post(
- f'{api_url}/api/add-git-providers',
- json={
- 'provider_tokens': provider_tokens_json,
- },
- )
- response.raise_for_status()
-
- async def _setup_custom_secrets(
- self,
- client: httpx.AsyncClient,
- api_url: str,
- custom_secrets: MappingProxyType[str, Any] | None,
- ):
- """Setup custom secrets for the nested conversation.
-
- Note: When resuming conversations, secrets may already exist in the runtime.
- We check for specific duplicate error messages to handle this case gracefully.
- """
- if custom_secrets:
- for key, secret in custom_secrets.items():
- try:
- response = await client.post(
- f'{api_url}/api/secrets',
- json={
- 'name': key,
- 'description': secret.description,
- 'value': secret.secret.get_secret_value(),
- },
- )
- response.raise_for_status()
- logger.debug(f'Successfully created secret: {key}')
- except httpx.HTTPStatusError as e:
- if e.response.status_code == 400:
- # Only ignore if it's actually a duplicate error
- try:
- error_data = e.response.json()
- error_msg = error_data.get('message', '')
- # The API returns: "Secret {secret_name} already exists"
- if 'already exists' in error_msg:
- logger.info(
- f'Secret "{key}" already exists, continuing - ignoring duplicate',
- extra={'api_url': api_url},
- )
- continue
- except (KeyError, ValueError, TypeError):
- pass # If we can't parse JSON, fall through to re-raise
- # Re-raise all other errors (including non-duplicate 400s)
- logger.error(
- f'Failed to setup secret "{key}": HTTP {e.response.status_code}',
- extra={
- 'api_url': api_url,
- 'response_text': e.response.text[:200],
- },
- )
- raise
-
- async def _get_mcp_config(self, user_id: str) -> MCPConfig | None:
- api_key_store = ApiKeyStore.get_instance()
- mcp_api_key = await api_key_store.retrieve_mcp_api_key(user_id)
- if not mcp_api_key:
- mcp_api_key = await api_key_store.create_api_key(
- user_id, 'MCP_API_KEY', None
- )
- if not mcp_api_key:
- return None
- web_host = os.environ.get('WEB_HOST', 'app.all-hands.dev')
- return MCPConfig(
- mcpServers={
- 'openhands': RemoteMCPServer(
- url=f'https://{web_host}/mcp/mcp',
- transport='http',
- auth=mcp_api_key,
- timeout=60,
- )
- }
- )
-
- async def _create_nested_conversation(
- self,
- client: httpx.AsyncClient,
- api_url: str,
- sid: str,
- user_id: str,
- settings: Settings,
- initial_user_msg: MessageAction | None,
- replay_json: str | None,
- ):
- """Create the nested conversation."""
- init_conversation: dict[str, Any] = {
- 'initial_user_msg': initial_user_msg.content if initial_user_msg else None,
- 'image_urls': [],
- 'replay_json': replay_json,
- 'conversation_id': sid,
- }
-
- mcp_config = await self._get_mcp_config(user_id)
- if mcp_config:
- # Merge with any MCP config from settings
- sdk_mcp = settings.agent_settings.mcp_config
- if sdk_mcp and sdk_mcp.mcpServers:
- from openhands.core.config.mcp_config import merge_mcp_configs
-
- mcp_config = merge_mcp_configs(mcp_config, sdk_mcp)
- if mcp_config:
- init_conversation['mcp_config'] = mcp_config.model_dump()
-
- if isinstance(settings, ConversationInitData):
- init_conversation['repository'] = settings.selected_repository
- init_conversation['selected_branch'] = settings.selected_branch
- init_conversation['git_provider'] = (
- settings.git_provider.value if settings.git_provider else None
- )
- init_conversation['conversation_instructions'] = (
- settings.conversation_instructions
- )
-
- response = await client.post(
- f'{api_url}/api/conversations', json=init_conversation
- )
- logger.info(f'_start_agent_loop:{response.status_code}:{response.json()}')
- response.raise_for_status()
-
- async def _wait_for_conversation_ready(
- self, client: httpx.AsyncClient, api_url: str, sid: str
- ):
- """Wait for the conversation to be ready by checking the events endpoint."""
- # TODO: Find out why /api/conversations/{sid} returns RUNNING when events are not available
- for _ in range(5):
- try:
- logger.info('checking_events_endpoint_running', extra={'sid': sid})
- response = await client.get(f'{api_url}/api/conversations/{sid}/events')
- if response.is_success:
- logger.info('events_endpoint_is_running', extra={'sid': sid})
- break
- except Exception:
- logger.warning('events_endpoint_not_ready', extra={'sid': sid})
- await asyncio.sleep(5)
-
- async def send_to_event_stream(self, connection_id: str, data: dict):
- # Not supported - clients should connect directly to the nested server!
- raise ValueError('unsupported_operation')
-
- async def request_llm_completion(
- self,
- sid: str,
- service_id: str,
- llm_config: LLMConfig,
- messages: list[dict[str, str]],
- ) -> str:
- # Not supported - clients should connect directly to the nested server!
- raise ValueError('unsupported_operation')
-
- async def send_event_to_conversation(self, sid: str, data: dict):
- runtime = await self._get_runtime(sid)
- if runtime is None:
- raise ValueError(f'no_such_conversation:{sid}')
- nested_url = self._get_nested_url_for_runtime(runtime['runtime_id'], sid)
- async with httpx.AsyncClient(
- verify=httpx_verify_option(),
- headers={
- 'X-Session-API-Key': runtime['session_api_key'],
- },
- ) as client:
- response = await client.post(f'{nested_url}/events', json=data)
- response.raise_for_status()
-
- async def disconnect_from_session(self, connection_id: str):
- # Not supported - clients should connect directly to the nested server!
- raise ValueError('unsupported_operation')
-
- async def close_session(self, sid: str):
- logger.info('close_session', extra={'sid': sid})
- runtime = await self._get_runtime(sid)
- if runtime is None:
- logger.info('no_session_to_close', extra={'sid': sid})
- return
- async with self._httpx_client() as client:
- response = await client.post(
- f'{self.remote_runtime_api_url}/pause',
- json={'runtime_id': runtime['runtime_id']},
- )
- if not response.is_success:
- logger.info(
- 'failed_to_close_session',
- {
- 'sid': sid,
- 'status_code': response.status_code,
- 'detail': (response.content or b'').decode(),
- },
- )
-
- async def _get_user_id_from_conversation(self, conversation_id: str) -> str:
- """
- Get user_id from conversation_id.
- """
-
- async with a_session_maker() as session:
- result = await session.execute(
- select(StoredConversationMetadataSaas).where(
- StoredConversationMetadataSaas.conversation_id == conversation_id
- )
- )
- conversation_metadata_saas = result.scalars().first()
-
- if not conversation_metadata_saas:
- raise ValueError(f'No conversation found {conversation_id}')
-
- return str(conversation_metadata_saas.user_id)
-
- async def _get_runtime_status_from_nested_runtime(
- self, session_api_key: Any | None, nested_url: str, conversation_id: str
- ) -> RuntimeStatus | None:
- """Get runtime status from the nested runtime via API call.
-
- Args:
- session_api_key: The session API key for authentication
- nested_url: The base URL of the nested runtime
- conversation_id: The conversation ID for logging purposes
-
- Returns:
- The runtime status if available, None otherwise
- """
- try:
- if not session_api_key:
- return None
-
- async with httpx.AsyncClient(
- verify=httpx_verify_option(),
- headers={
- 'X-Session-API-Key': session_api_key,
- },
- ) as client:
- # Query the nested runtime for conversation info
- response = await client.get(nested_url)
- if response.status_code == 200:
- conversation_data = response.json()
- runtime_status_str = conversation_data.get('runtime_status')
- if runtime_status_str:
- # Convert string back to RuntimeStatus enum
- return RuntimeStatus(runtime_status_str)
- else:
- logger.debug(
- f'Failed to get conversation info for {conversation_id}: {response.status_code}'
- )
- except ValueError:
- logger.debug(f'Invalid runtime status value: {runtime_status_str}')
- except Exception as e:
- logger.debug(f'Could not get runtime status for {conversation_id}: {e}')
-
- return None
-
- async def get_agent_loop_info(
- self, user_id: str | None = None, filter_to_sids: set[str] | None = None
- ) -> list[AgentLoopInfo]:
- if filter_to_sids is not None and not filter_to_sids:
- return []
-
- results = []
- conversation_ids = set()
-
- # Get starting agent loops from redis...
- if user_id:
- pattern = self._get_redis_conversation_key(user_id, '*')
- else:
- pattern = self._get_redis_conversation_key('*', '*')
- redis = self._get_redis_client()
- async for key in redis.scan_iter(pattern):
- conversation_user_id, conversation_id = key.decode().split(':')[1:]
- conversation_ids.add(conversation_id)
- if filter_to_sids is None or conversation_id in filter_to_sids:
- results.append(
- AgentLoopInfo(
- conversation_id=conversation_id,
- url=None,
- session_api_key=None,
- event_store=EventStore(
- conversation_id, self.file_store, conversation_user_id
- ),
- status=ConversationStatus.STARTING,
- )
- )
-
- # Get running agent loops from runtime api
- if filter_to_sids and len(filter_to_sids) == 1:
- runtimes = []
- runtime = await self._get_runtime(next(iter(filter_to_sids)))
- if runtime:
- runtimes.append(runtime)
- else:
- runtimes = await self._get_runtimes()
- for runtime in runtimes:
- conversation_id = runtime['session_id']
- if conversation_id in conversation_ids:
- continue
- if filter_to_sids is not None and conversation_id not in filter_to_sids:
- continue
-
- user_id_for_convo = user_id
- if not user_id_for_convo:
- try:
- user_id_for_convo = await self._get_user_id_from_conversation(
- conversation_id
- )
- except Exception:
- continue
-
- nested_url = self._get_nested_url_for_runtime(
- runtime['runtime_id'], conversation_id
- )
- session_api_key = runtime.get('session_api_key')
-
- # Get runtime status from nested runtime
- runtime_status = await self._get_runtime_status_from_nested_runtime(
- session_api_key, nested_url, conversation_id
- )
-
- agent_loop_info = AgentLoopInfo(
- conversation_id=conversation_id,
- url=nested_url,
- session_api_key=session_api_key,
- event_store=EventStore(
- sid=conversation_id,
- file_store=self.file_store,
- user_id=user_id_for_convo,
- ),
- status=self._parse_status(runtime),
- runtime_status=runtime_status,
- )
- results.append(agent_loop_info)
-
- return results
-
- @classmethod
- def get_instance(
- cls,
- sio: socketio.AsyncServer,
- config: OpenHandsConfig,
- file_store: FileStore,
- server_config: ServerConfig,
- monitoring_listener: MonitoringListener,
- ) -> ConversationManager:
- if 'localhost' in WEB_HOST:
- event_retrieval = EventRetrieval.POLLING
- else:
- event_retrieval = EventRetrieval.WEBHOOK_PUSH
- return SaasNestedConversationManager(
- sio=sio,
- config=config,
- server_config=server_config,
- file_store=file_store,
- event_retrieval=event_retrieval,
- )
-
- @property
- def remote_runtime_api_url(self):
- return self.config.sandbox.remote_runtime_api_url
-
- async def _get_conversation_store(self, user_id: str | None) -> ConversationStore:
- conversation_store_class = self._conversation_store_class
- if not conversation_store_class:
- self._conversation_store_class = conversation_store_class = get_impl(
- ConversationStore, # type: ignore
- self.server_config.conversation_store_class,
- )
- store = await conversation_store_class.get_instance(self.config, user_id) # type: ignore
- return store
-
- async def ensure_num_conversations_below_limit(self, sid: str, user_id: str):
- response_ids = await self.get_running_agent_loops(user_id)
- if len(response_ids) >= self.config.max_concurrent_conversations:
- logger.info(
- f'too_many_sessions_for:{user_id or ""}',
- extra={'session_id': sid, 'user_id': user_id},
- )
- # Get the conversations sorted (oldest first)
- conversation_store = await self._get_conversation_store(user_id)
- conversations = await conversation_store.get_all_metadata(response_ids)
- conversations.sort(key=_last_updated_at_key, reverse=True)
-
- while len(conversations) >= self.config.max_concurrent_conversations:
- oldest_conversation_id = conversations.pop().conversation_id
- logger.debug(
- f'closing_from_too_many_sessions:{user_id or ""}:{oldest_conversation_id}',
- extra={'session_id': oldest_conversation_id, 'user_id': user_id},
- )
- # Send status message to client and close session.
- status_update_dict = {
- 'status_update': True,
- 'type': 'error',
- 'id': 'AGENT_ERROR$TOO_MANY_CONVERSATIONS',
- 'message': 'Too many conversations at once. If you are still using this one, try reactivating it by prompting the agent to continue',
- }
- await self.sio.emit(
- 'oh_event',
- status_update_dict,
- to=ROOM_KEY.format(sid=oldest_conversation_id),
- )
- await self.close_session(oldest_conversation_id)
-
- def _get_provider_handler(self, settings: Settings):
- provider_tokens = None
- if isinstance(settings, ConversationInitData):
- provider_tokens = settings.git_provider_tokens
- provider_handler = ProviderHandler(
- provider_tokens=provider_tokens
- or cast(PROVIDER_TOKEN_TYPE, MappingProxyType({}))
- )
- return provider_handler
-
- async def _create_runtime(
- self,
- sid: str,
- user_id: str,
- settings: Settings,
- provider_handler: ProviderHandler,
- ):
- llm_registry, conversation_stats, config = (
- create_registry_and_conversation_stats(self.config, sid, user_id, settings)
- )
-
- # This session is created here only because it is the easiest way to get a runtime, which
- # is the easiest way to create the needed docker container
- session = Session(
- sid=sid,
- llm_registry=llm_registry,
- conversation_stats=conversation_stats,
- file_store=self.file_store,
- config=self.config,
- sio=self.sio,
- user_id=user_id,
- )
- llm_registry.retry_listner = session._notify_on_llm_retry
- agent_cls = settings.agent_settings.agent or self.config.default_agent
- agent_config = self.config.get_agent_config(agent_cls)
- agent = Agent.get_cls(agent_cls)(agent_config, llm_registry)
-
- config = self.config.model_copy(deep=True)
- env_vars = config.sandbox.runtime_startup_env_vars
- env_vars['CONVERSATION_MANAGER_CLASS'] = (
- 'openhands.server.conversation_manager.standalone_conversation_manager.StandaloneConversationManager'
- )
- env_vars['LOG_JSON'] = '1'
- env_vars['SERVE_FRONTEND'] = '0'
- env_vars['RUNTIME'] = 'local'
- # TODO: In the long term we may come up with a more secure strategy for user management within the nested runtime.
- env_vars['USER'] = (
- RUNTIME_USERNAME
- if RUNTIME_USERNAME
- else ('openhands' if config.run_as_openhands else 'root')
- )
- env_vars['PERMITTED_CORS_ORIGINS'] = ','.join(PERMITTED_CORS_ORIGINS)
- env_vars['port'] = '60000'
- # TODO: These values are static in the runtime-api project, but do not get copied into the runtime ENV
- env_vars['VSCODE_PORT'] = '60001'
- env_vars['WORK_PORT_1'] = '12000'
- env_vars['WORK_PORT_2'] = '12001'
- # We need to be able to specify the nested conversation id within the nested runtime
- env_vars['ALLOW_SET_CONVERSATION_ID'] = '1'
- env_vars['FILE_STORE_PATH'] = '/workspace/.openhands/file_store'
- env_vars['WORKSPACE_BASE'] = '/workspace/project'
- env_vars['WORKSPACE_MOUNT_PATH_IN_SANDBOX'] = '/workspace/project'
- env_vars['SANDBOX_CLOSE_DELAY'] = '0'
- env_vars['SKIP_DEPENDENCY_CHECK'] = '1'
- env_vars['INITIAL_NUM_WARM_SERVERS'] = '1'
- env_vars['INIT_GIT_IN_EMPTY_WORKSPACE'] = '1'
- env_vars['ENABLE_V1'] = '0'
- env_vars['SU_TO_USER'] = SU_TO_USER
- env_vars['DISABLE_VSCODE_PLUGIN'] = str(DISABLE_VSCODE_PLUGIN).lower()
- env_vars['BROWSERGYM_DOWNLOAD_DIR'] = '/workspace/.downloads/'
- env_vars['PLAYWRIGHT_BROWSERS_PATH'] = '/opt/playwright-browsers'
-
- # We need this for LLM traces tracking to identify the source of the LLM calls
- env_vars['WEB_HOST'] = WEB_HOST
- if self.event_retrieval == EventRetrieval.WEBHOOK_PUSH:
- # If we are retrieving events using push, we tell the nested runtime about the webhook.
- # The nested runtime will automatically authenticate using the SESSION_API_KEY
- env_vars['FILE_STORE_WEB_HOOK_URL'] = (
- f'{PERMITTED_CORS_ORIGINS[0]}/event-webhook/batch'
- )
- # Enable batched webhook mode for better performance
- env_vars['FILE_STORE_WEB_HOOK_BATCH'] = '1'
-
- if self._runtime_container_image:
- config.sandbox.runtime_container_image = self._runtime_container_image
-
- plugins = [
- plugin
- for plugin in agent.sandbox_plugins
- if not (DISABLE_VSCODE_PLUGIN and isinstance(plugin, VSCodeRequirement))
- ]
- logger.info(f'Loaded plugins for runtime {sid}: {plugins}')
-
- runtime = RemoteRuntime(
- config=config,
- event_stream=None, # type: ignore[arg-type]
- sid=sid,
- plugins=plugins,
- # env_vars=env_vars,
- # status_callback: Callable[..., None] | None = None,
- attach_to_existing=False,
- headless_mode=False,
- user_id=user_id,
- # git_provider_tokens: PROVIDER_TOKEN_TYPE | None = None,
- main_module='openhands.server',
- llm_registry=llm_registry,
- )
-
- # TODO: This is a hack. The setup_initial_env method directly calls the methods on the action
- # execution server, even though there are not any variables to set. In the nested env, there
- # is currently no direct access to the action execution server, so we should either add a
- # check and not invoke the endpoint if there are no variables, or find a way to access the
- # action execution server directly (e.g.: Merge the action execution server with the app
- # server for local runtimes)
- runtime.setup_initial_env = lambda: None # type:ignore
-
- return runtime
-
- @contextlib.asynccontextmanager
- async def _httpx_client(self):
- async with httpx.AsyncClient(
- verify=httpx_verify_option(),
- headers={'X-API-Key': self.config.sandbox.api_key or ''},
- timeout=_HTTP_TIMEOUT,
- ) as client:
- yield client
-
- async def _get_runtimes(self) -> list[dict]:
- async with self._httpx_client() as client:
- response = await client.get(f'{self.remote_runtime_api_url}/list')
- response_json = response.json()
- runtimes = response_json['runtimes']
- return runtimes
-
- async def _get_all_running_conversation_ids(self) -> set[str]:
- runtimes = await self._get_runtimes()
- conversation_ids = {
- runtime['session_id']
- for runtime in runtimes
- if runtime.get('status') == 'running'
- }
- return conversation_ids
-
- async def _get_recent_conversation_ids_for_user(self, user_id: str) -> set[str]:
- async with a_session_maker() as session:
- # Only include conversations updated in the past week
- one_week_ago = datetime.now(UTC) - timedelta(days=7)
- result = await session.execute(
- select(StoredConversationMetadata.conversation_id)
- .join(
- StoredConversationMetadataSaas,
- StoredConversationMetadata.conversation_id
- == StoredConversationMetadataSaas.conversation_id,
- )
- .where(
- StoredConversationMetadataSaas.user_id == user_id,
- StoredConversationMetadata.last_updated_at >= one_week_ago,
- )
- )
- user_conversation_ids = set(result.scalars().all())
- return user_conversation_ids
-
- async def _get_runtime(self, sid: str) -> dict | None:
- async with self._httpx_client() as client:
- response = await client.get(f'{self.remote_runtime_api_url}/sessions/{sid}')
- if not response.is_success:
- return None
- response_json = response.json()
-
- # Hack: This endpoint doesn't return the session_id
- response_json['session_id'] = sid
-
- return response_json
-
- def _parse_status(self, runtime: dict):
- # status is one of running, stoppped, paused, error, starting
- status = (runtime.get('status') or '').upper()
- if status == 'PAUSED':
- return ConversationStatus.STOPPED
- elif status == 'STOPPED':
- return ConversationStatus.ARCHIVED
- if status in ConversationStatus:
- return ConversationStatus[status]
- return ConversationStatus.STOPPED
-
- def _get_nested_url_for_runtime(self, runtime_id: str, conversation_id: str):
- return RUNTIME_CONVERSATION_URL.format(
- runtime_id=runtime_id, conversation_id=conversation_id
- )
-
- def _get_redis_client(self):
- return getattr(self.sio.manager, 'redis', None)
-
- def _get_redis_conversation_key(self, user_id: str, conversation_id: str):
- return f'ohcnv:{user_id}:{conversation_id}'
-
- async def _poll_events(self):
- """Poll events in nested runtimes. This is primarily used in debug / single server environments"""
- while should_continue():
- try:
- await asyncio.sleep(_POLLING_INTERVAL)
- agent_loop_infos = await self.get_agent_loop_info()
-
- for agent_loop_info in agent_loop_infos:
- if agent_loop_info.status != ConversationStatus.RUNNING:
- continue
- try:
- await self._poll_agent_loop_events(agent_loop_info)
- except Exception as e:
- logger.exception(f'error_polling_events:{str(e)}')
- except Exception as e:
- try:
- asyncio.get_running_loop()
- logger.exception(f'error_polling_events:{str(e)}')
- except RuntimeError:
- # Loop has been shut down, exit gracefully
- return
-
- async def _poll_agent_loop_events(self, agent_loop_info: AgentLoopInfo):
- """This method is typically only run in localhost, where the webhook callbacks from the remote runtime are unavailable"""
- if agent_loop_info.status != ConversationStatus.RUNNING:
- return
- conversation_id = agent_loop_info.conversation_id
-
- async with a_session_maker() as session:
- result = await session.execute(
- select(StoredConversationMetadata).where(
- StoredConversationMetadata.conversation_id == conversation_id
- )
- )
- conversation_metadata = result.scalars().first()
-
- result = await session.execute(
- select(StoredConversationMetadataSaas).where(
- StoredConversationMetadataSaas.conversation_id == conversation_id
- )
- )
- conversation_metadata_saas = result.scalars().first()
-
- if conversation_metadata is None or conversation_metadata_saas is None:
- # Conversation is running in different server
- return
-
- user_id = conversation_metadata_saas.user_id
-
- # Get the id of the next event which is not present
- events_dir = get_conversation_events_dir(
- agent_loop_info.conversation_id, user_id
- )
- try:
- event_file_names = self.file_store.list(events_dir)
- except FileNotFoundError:
- event_file_names = []
- start_id = (
- max(
- (
- _get_id_from_filename(event_file_name)
- for event_file_name in event_file_names
- ),
- default=-1,
- )
- + 1
- )
-
- # Copy over any missing events and update the conversation metadata
- last_updated_at = conversation_metadata.last_updated_at
- if agent_loop_info.event_store:
- for event in agent_loop_info.event_store.search_events(start_id=start_id):
- # What would the handling be if no event.timestamp? Can that happen?
- if event.timestamp:
- timestamp = datetime.fromisoformat(event.timestamp)
- last_updated_at = max(last_updated_at, timestamp)
- contents = json.dumps(event_to_dict(event))
- path = get_conversation_event_filename(
- conversation_id, event.id, user_id
- )
- self.file_store.write(path, contents)
-
- # Process the event using shared logic from event_webhook
- subpath = f'events/{event.id}.json'
- await process_event(
- user_id, conversation_id, subpath, event_to_dict(event)
- )
-
- # Update conversation metadata using shared logic
- metadata_content = {
- 'last_updated_at': last_updated_at.isoformat() if last_updated_at else None,
- }
- update_conversation_metadata(conversation_id, metadata_content)
-
- async def list_files(self, sid: str, path: str | None = None) -> list[str]:
- """List files in the workspace for a conversation.
-
- Delegates to the nested container's list-files endpoint.
-
- Args:
- sid: The session/conversation ID.
- path: Optional path to list files from. If None, lists from workspace root.
-
- Returns:
- A list of file paths.
-
- Raises:
- ValueError: If the conversation is not running.
- httpx.HTTPError: If there's an error communicating with the nested runtime.
- """
- runtime = await self._get_runtime(sid)
- if runtime is None or runtime.get('status') != 'running':
- raise ValueError(f'Conversation {sid} is not running')
-
- nested_url = self._get_nested_url_for_runtime(runtime['runtime_id'], sid)
- session_api_key = runtime.get('session_api_key')
-
- return await self._fetch_list_files_from_nested(
- sid, nested_url, session_api_key, path
- )
-
- async def select_file(self, sid: str, file: str) -> tuple[str | None, str | None]:
- """Read a file from the workspace via nested container.
-
- Raises:
- ValueError: If the conversation is not running.
- httpx.HTTPError: If there's an error communicating with the nested runtime.
- """
- runtime = await self._get_runtime(sid)
- if runtime is None or runtime.get('status') != 'running':
- raise ValueError(f'Conversation {sid} is not running')
-
- nested_url = self._get_nested_url_for_runtime(runtime['runtime_id'], sid)
- session_api_key = runtime.get('session_api_key')
-
- return await self._fetch_select_file_from_nested(
- sid, nested_url, session_api_key, file
- )
-
- async def upload_files(
- self, sid: str, files: list[tuple[str, bytes]]
- ) -> tuple[list[str], list[dict[str, str]]]:
- """Upload files to the workspace via nested container.
-
- Raises:
- ValueError: If the conversation is not running.
- httpx.HTTPError: If there's an error communicating with the nested runtime.
- """
- runtime = await self._get_runtime(sid)
- if runtime is None or runtime.get('status') != 'running':
- raise ValueError(f'Conversation {sid} is not running')
-
- nested_url = self._get_nested_url_for_runtime(runtime['runtime_id'], sid)
- session_api_key = runtime.get('session_api_key')
-
- return await self._fetch_upload_files_to_nested(
- sid, nested_url, session_api_key, files
- )
-
-
-def _last_updated_at_key(conversation: ConversationMetadata) -> float:
- last_updated_at = conversation.last_updated_at
- if last_updated_at is None:
- return 0.0
- return last_updated_at.timestamp()
-
-
-def _get_id_from_filename(filename: str) -> int:
- try:
- return int(filename.split('/')[-1].split('.')[0])
- except ValueError:
- logger.warning(f'get id from filename ({filename}) failed.')
- return -1
diff --git a/enterprise/server/utils/conversation_utils.py b/enterprise/server/utils/conversation_utils.py
new file mode 100644
index 0000000000..ffe6cdaf5d
--- /dev/null
+++ b/enterprise/server/utils/conversation_utils.py
@@ -0,0 +1,72 @@
+"""Utility functions for conversation operations."""
+
+from uuid import UUID
+
+from storage.database import session_maker
+from storage.stored_conversation_metadata_saas import StoredConversationMetadataSaas
+
+
+def get_user_id(conversation_id: str) -> str:
+ """Get the user ID for a conversation from the metadata.
+
+ Args:
+ conversation_id: The conversation ID
+
+ Returns:
+ The user ID as a string
+ """
+ with session_maker() as session:
+ conversation_metadata_saas = (
+ session.query(StoredConversationMetadataSaas)
+ .filter(StoredConversationMetadataSaas.conversation_id == conversation_id)
+ .first()
+ )
+ if not conversation_metadata_saas:
+ raise ValueError(f'Conversation not found: {conversation_id}')
+ return str(conversation_metadata_saas.user_id)
+
+
+async def get_session_api_key(conversation_id: str) -> str | None:
+ """Get the session API key for a conversation.
+
+ This retrieves the session API key from the V1 sandbox system.
+
+ Args:
+ conversation_id: The conversation ID
+
+ Returns:
+ The session API key, or None if not available
+ """
+ from openhands.app_server.config import (
+ get_app_conversation_info_service,
+ get_sandbox_service,
+ )
+ from openhands.app_server.services.injector import InjectorState
+ from openhands.app_server.user.specifiy_user_context import (
+ ADMIN,
+ USER_CONTEXT_ATTR,
+ )
+
+ # Create injector state for dependency injection
+ state = InjectorState()
+ setattr(state, USER_CONTEXT_ATTR, ADMIN)
+
+ async with (
+ get_app_conversation_info_service(state) as app_conversation_info_service,
+ get_sandbox_service(state) as sandbox_service,
+ ):
+ # Get the conversation info to find the sandbox_id
+ app_conversation_info = (
+ await app_conversation_info_service.get_app_conversation_info(
+ UUID(conversation_id)
+ )
+ )
+ if not app_conversation_info:
+ return None
+
+ # Get the sandbox to retrieve the session API key
+ sandbox = await sandbox_service.get_sandbox(app_conversation_info.sandbox_id)
+ if not sandbox:
+ return None
+
+ return sandbox.session_api_key
diff --git a/enterprise/tests/unit/integrations/gitlab/test_gitlab_manager.py b/enterprise/tests/unit/integrations/gitlab/test_gitlab_manager.py
index 535f44a0e1..458c6d5076 100644
--- a/enterprise/tests/unit/integrations/gitlab/test_gitlab_manager.py
+++ b/enterprise/tests/unit/integrations/gitlab/test_gitlab_manager.py
@@ -1,9 +1,7 @@
"""
-Tests for GitlabManager V0/V1 conditional job creation flow.
+Tests for GitlabManager job creation flow.
-Covers:
-- V0 path: register_callback_processor is called
-- V1 path: register_callback_processor is NOT called (V1 uses event callbacks instead)
+All conversations now use V1 app conversation system.
"""
from unittest.mock import AsyncMock, MagicMock, patch
@@ -16,8 +14,8 @@ from openhands.storage.data_models.conversation_metadata import ConversationMeta
@pytest.fixture
-def mock_gitlab_view_v0():
- """Create a mock GitlabIssue view with V1 disabled (V0 path)."""
+def mock_gitlab_view():
+ """Create a mock GitlabIssue view."""
return GitlabIssue(
installation_id='test_installation',
issue_number=42,
@@ -30,33 +28,7 @@ def mock_gitlab_view_v0():
keycloak_user_id='keycloak_test_user',
),
raw_payload={'source': 'gitlab', 'message': {'test': 'data'}},
- conversation_id='test_conversation_v0',
- should_extract=True,
- send_summary_instruction=True,
- title='Test Issue',
- description='Test description',
- previous_comments=[],
- is_mr=False,
- v1_enabled=False,
- )
-
-
-def mock_gitlab_view_v1():
- """Create a mock GitlabIssue view with V1 enabled."""
- return GitlabIssue(
- installation_id='test_installation',
- issue_number=42,
- project_id=12345,
- full_repo_name='test-group/test-repo',
- is_public_repo=True,
- user_info=UserData(
- user_id='123',
- username='test_user',
- keycloak_user_id='keycloak_test_user',
- ),
- raw_payload={'source': 'gitlab', 'message': {'test': 'data'}},
- conversation_id='test_conversation_v1',
+ conversation_id='test_conversation',
should_extract=True,
send_summary_instruction=True,
title='Test Issue',
@@ -93,194 +65,48 @@ def mock_convo_metadata():
)
-class TestGitlabManagerV0V1ConditionalJobCreation:
- """Test the conditional V0/V1 job creation flow in GitlabManager.start_job()."""
+class TestGitlabManagerJobCreation:
+ """Test job creation flow in GitlabManager.start_job()."""
@pytest.mark.asyncio
- @patch('integrations.gitlab.gitlab_manager.register_callback_processor')
@patch('integrations.gitlab.gitlab_manager.get_saas_user_auth')
@patch(
'integrations.gitlab.gitlab_manager.GitlabManager.send_message',
new_callable=AsyncMock,
)
- async def test_v0_path_registers_callback_processor(
+ async def test_start_job_creates_conversation_and_sends_message(
self,
mock_send_message,
mock_get_saas_user_auth,
- mock_register_callback_processor,
mock_token_manager,
- mock_gitlab_view_v0,
+ mock_gitlab_view,
mock_saas_user_auth,
mock_convo_metadata,
):
- """Test that V0 path calls register_callback_processor for legacy callback handling."""
+ """Test that start_job creates a conversation and sends acknowledgment message."""
from integrations.gitlab.gitlab_manager import GitlabManager
# Setup mocks
mock_get_saas_user_auth.return_value = mock_saas_user_auth
# Mock the view's methods
- mock_gitlab_view_v0.initialize_new_conversation = AsyncMock(
+ mock_gitlab_view.initialize_new_conversation = AsyncMock(
return_value=mock_convo_metadata
)
- mock_gitlab_view_v0.create_new_conversation = AsyncMock()
+ mock_gitlab_view.create_new_conversation = AsyncMock()
# Create manager instance
manager = GitlabManager(token_manager=mock_token_manager, data_collector=None)
# Call start_job
- await manager.start_job(mock_gitlab_view_v0)
-
- # Assert: V0 path should register callback processor
- mock_register_callback_processor.assert_called_once()
+ await manager.start_job(mock_gitlab_view)
- # Verify the callback processor was created with correct conversation_id
- call_args = mock_register_callback_processor.call_args
- assert call_args[0][0] == 'test_conversation_v0'
+ # Assert: conversation should be created
+ mock_gitlab_view.initialize_new_conversation.assert_called_once()
+ mock_gitlab_view.create_new_conversation.assert_called_once()
# Verify acknowledgment message was sent
mock_send_message.assert_called_once()
-
- @pytest.mark.asyncio
- @patch('integrations.gitlab.gitlab_manager.register_callback_processor')
- @patch('integrations.gitlab.gitlab_manager.get_saas_user_auth')
- @patch(
- 'integrations.gitlab.gitlab_manager.GitlabManager.send_message',
- new_callable=AsyncMock,
- )
- async def test_v1_path_does_not_register_callback_processor(
- self,
- mock_send_message,
- mock_get_saas_user_auth,
- mock_register_callback_processor,
- mock_token_manager,
- mock_gitlab_view_v1,
- mock_saas_user_auth,
- mock_convo_metadata,
- ):
- """Test that V1 path does NOT call register_callback_processor.
-
- V1 uses the new event callback system instead of the legacy
- register_callback_processor mechanism.
- """
- from integrations.gitlab.gitlab_manager import GitlabManager
-
- # Setup mocks
- mock_get_saas_user_auth.return_value = mock_saas_user_auth
-
- # Mock the view's methods
- mock_gitlab_view_v1.initialize_new_conversation = AsyncMock(
- return_value=mock_convo_metadata
- )
- mock_gitlab_view_v1.create_new_conversation = AsyncMock()
-
- # Create manager instance
- manager = GitlabManager(token_manager=mock_token_manager, data_collector=None)
-
- # Call start_job
- await manager.start_job(mock_gitlab_view_v1)
-
- # Assert: V1 path should NOT register callback processor
- mock_register_callback_processor.assert_not_called()
-
- # Verify acknowledgment message was still sent
- mock_send_message.assert_called_once()
-
- @pytest.mark.asyncio
- @patch('integrations.gitlab.gitlab_manager.register_callback_processor')
- @patch('integrations.gitlab.gitlab_manager.get_saas_user_auth')
- @patch(
- 'integrations.gitlab.gitlab_manager.GitlabManager.send_message',
- new_callable=AsyncMock,
- )
- async def test_v1_enabled_flag_determines_callback_registration(
- self,
- mock_send_message,
- mock_get_saas_user_auth,
- mock_register_callback_processor,
- mock_token_manager,
- mock_gitlab_view_v0,
- mock_saas_user_auth,
- mock_convo_metadata,
- ):
- """Test that the v1_enabled flag on the view determines the callback registration path.
-
- This test verifies the conditional logic:
- - if not gitlab_view.v1_enabled: register_callback_processor is called
- - else: register_callback_processor is NOT called
- """
- from integrations.gitlab.gitlab_manager import GitlabManager
-
- # Setup mocks
- mock_get_saas_user_auth.return_value = mock_saas_user_auth
- mock_gitlab_view_v0.initialize_new_conversation = AsyncMock(
- return_value=mock_convo_metadata
- )
- mock_gitlab_view_v0.create_new_conversation = AsyncMock()
-
- manager = GitlabManager(token_manager=mock_token_manager, data_collector=None)
-
- # Test with v1_enabled = False (V0 path)
- mock_gitlab_view_v0.v1_enabled = False
- await manager.start_job(mock_gitlab_view_v0)
- assert mock_register_callback_processor.call_count == 1
-
- # Reset mocks
- mock_register_callback_processor.reset_mock()
- mock_send_message.reset_mock()
-
- # Test with v1_enabled = True (V1 path)
- mock_gitlab_view_v0.v1_enabled = True
- mock_gitlab_view_v0.conversation_id = 'test_conversation_v1_toggled'
- await manager.start_job(mock_gitlab_view_v0)
- assert mock_register_callback_processor.call_count == 0
-
- @pytest.mark.asyncio
- @patch('integrations.gitlab.gitlab_manager.register_callback_processor')
- @patch('integrations.gitlab.gitlab_manager.get_saas_user_auth')
- @patch(
- 'integrations.gitlab.gitlab_manager.GitlabManager.send_message',
- new_callable=AsyncMock,
- )
- async def test_callback_processor_receives_correct_gitlab_view(
- self,
- mock_send_message,
- mock_get_saas_user_auth,
- mock_register_callback_processor,
- mock_token_manager,
- mock_gitlab_view_v0,
- mock_saas_user_auth,
- mock_convo_metadata,
- ):
- """Test that the GitlabCallbackProcessor receives the correct gitlab_view."""
- from integrations.gitlab.gitlab_manager import GitlabManager
- from server.conversation_callback_processor.gitlab_callback_processor import (
- GitlabCallbackProcessor,
- )
-
- # Setup mocks
- mock_get_saas_user_auth.return_value = mock_saas_user_auth
- mock_gitlab_view_v0.initialize_new_conversation = AsyncMock(
- return_value=mock_convo_metadata
- )
- mock_gitlab_view_v0.create_new_conversation = AsyncMock()
-
- manager = GitlabManager(token_manager=mock_token_manager, data_collector=None)
-
- # Call start_job
- await manager.start_job(mock_gitlab_view_v0)
-
- # Verify register_callback_processor was called with correct arguments
- mock_register_callback_processor.assert_called_once()
- call_args = mock_register_callback_processor.call_args
-
- # First argument should be conversation_id
- conversation_id = call_args[0][0]
- assert conversation_id == 'test_conversation_v0'
-
- # Second argument should be a GitlabCallbackProcessor instance
- processor = call_args[0][1]
- assert isinstance(processor, GitlabCallbackProcessor)
- assert processor.gitlab_view.issue_number == mock_gitlab_view_v0.issue_number
- assert processor.gitlab_view.project_id == mock_gitlab_view_v0.project_id
- assert processor.send_summary_instruction is True
+ msg_arg = mock_send_message.call_args[0][0]
+ assert "I'm on it!" in msg_arg
+ assert 'test_user' in msg_arg
diff --git a/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_manager.py b/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_manager.py
index e4c5025165..7b68118223 100644
--- a/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_manager.py
+++ b/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_manager.py
@@ -663,7 +663,7 @@ class TestStartJob:
async def test_start_job_success_new_conversation(
self, jira_dc_manager, sample_jira_dc_workspace
):
- """Test successful job start for new conversation."""
+ """Test successful job start for new conversation using V1 app conversation system."""
mock_view = MagicMock(spec=JiraDcNewConversationView)
mock_view.jira_dc_user = MagicMock()
mock_view.jira_dc_user.keycloak_user_id = 'test_user'
@@ -676,17 +676,11 @@ class TestStartJob:
jira_dc_manager.send_message = AsyncMock()
jira_dc_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
- with patch(
- 'integrations.jira_dc.jira_dc_manager.register_callback_processor'
- ) as mock_register:
- with patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.JiraDcCallbackProcessor'
- ):
- await jira_dc_manager.start_job(mock_view)
+ await jira_dc_manager.start_job(mock_view)
- mock_view.create_or_update_conversation.assert_called_once()
- mock_register.assert_called_once()
- jira_dc_manager.send_message.assert_called_once()
+ # V1 callback processors are registered by the view during conversation creation
+ mock_view.create_or_update_conversation.assert_called_once()
+ jira_dc_manager.send_message.assert_called_once()
@pytest.mark.asyncio
async def test_start_job_success_existing_conversation(
@@ -705,15 +699,10 @@ class TestStartJob:
jira_dc_manager.send_message = AsyncMock()
jira_dc_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
- with patch(
- 'integrations.jira_dc.jira_dc_manager.register_callback_processor'
- ) as mock_register:
- await jira_dc_manager.start_job(mock_view)
+ await jira_dc_manager.start_job(mock_view)
- mock_view.create_or_update_conversation.assert_called_once()
- # Should not register callback for existing conversation
- mock_register.assert_not_called()
- jira_dc_manager.send_message.assert_called_once()
+ mock_view.create_or_update_conversation.assert_called_once()
+ jira_dc_manager.send_message.assert_called_once()
@pytest.mark.asyncio
async def test_start_job_missing_settings_error(
@@ -833,9 +822,8 @@ class TestStartJob:
jira_dc_manager.send_message = AsyncMock(side_effect=Exception('Send failed'))
jira_dc_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
- with patch('integrations.jira_dc.jira_dc_manager.register_callback_processor'):
- # Should not raise exception even if send_message fails
- await jira_dc_manager.start_job(mock_view)
+ # Should not raise exception even if send_message fails
+ await jira_dc_manager.start_job(mock_view)
class TestGetIssueDetails:
diff --git a/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_view.py b/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_view.py
deleted file mode 100644
index 33d019871e..0000000000
--- a/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_view.py
+++ /dev/null
@@ -1,425 +0,0 @@
-"""
-Tests for Jira DC view classes and factory.
-"""
-
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pytest
-from integrations.jira_dc.jira_dc_types import StartingConvoException
-from integrations.jira_dc.jira_dc_view import (
- JiraDcExistingConversationView,
- JiraDcFactory,
- JiraDcNewConversationView,
-)
-
-from openhands.core.schema.agent import AgentState
-
-
-class TestJiraDcNewConversationView:
- """Tests for JiraDcNewConversationView"""
-
- async def test_get_instructions(self, new_conversation_view, mock_jinja_env):
- """Test _get_instructions method"""
- instructions, user_msg = await new_conversation_view._get_instructions(
- mock_jinja_env
- )
-
- assert instructions == 'Test Jira DC instructions template'
- assert 'PROJ-123' in user_msg
- assert 'Test Issue' in user_msg
- assert 'Fix this bug @openhands' in user_msg
-
- @patch('integrations.jira_dc.jira_dc_view.create_new_conversation')
- @patch('integrations.jira_dc.jira_dc_view.integration_store')
- async def test_create_or_update_conversation_success(
- self,
- mock_store,
- mock_create_conversation,
- new_conversation_view,
- mock_jinja_env,
- mock_agent_loop_info,
- ):
- """Test successful conversation creation"""
- mock_create_conversation.return_value = mock_agent_loop_info
- mock_store.create_conversation = AsyncMock()
-
- result = await new_conversation_view.create_or_update_conversation(
- mock_jinja_env
- )
-
- assert result == 'conv-123'
- mock_create_conversation.assert_called_once()
- mock_store.create_conversation.assert_called_once()
-
- async def test_create_or_update_conversation_no_repo(
- self, new_conversation_view, mock_jinja_env
- ):
- """Test conversation creation without selected repo"""
- new_conversation_view.selected_repo = None
-
- with pytest.raises(StartingConvoException, match='No repository selected'):
- await new_conversation_view.create_or_update_conversation(mock_jinja_env)
-
- @patch('integrations.jira_dc.jira_dc_view.create_new_conversation')
- async def test_create_or_update_conversation_failure(
- self, mock_create_conversation, new_conversation_view, mock_jinja_env
- ):
- """Test conversation creation failure"""
- mock_create_conversation.side_effect = Exception('Creation failed')
-
- with pytest.raises(
- StartingConvoException, match='Failed to create conversation'
- ):
- await new_conversation_view.create_or_update_conversation(mock_jinja_env)
-
- def test_get_response_msg(self, new_conversation_view):
- """Test get_response_msg method"""
- response = new_conversation_view.get_response_msg()
-
- assert "I'm on it!" in response
- assert 'Test User' in response
- assert 'track my progress here' in response
- assert 'conv-123' in response
-
-
-class TestJiraDcExistingConversationView:
- """Tests for JiraDcExistingConversationView"""
-
- async def test_get_instructions(self, existing_conversation_view, mock_jinja_env):
- """Test _get_instructions method"""
- instructions, user_msg = await existing_conversation_view._get_instructions(
- mock_jinja_env
- )
-
- assert instructions == ''
- assert 'PROJ-123' in user_msg
- assert 'Test Issue' in user_msg
- assert 'Fix this bug @openhands' in user_msg
-
- @patch('integrations.jira_dc.jira_dc_view.ConversationStoreImpl.get_instance')
- @patch('integrations.jira_dc.jira_dc_view.setup_init_conversation_settings')
- @patch('integrations.jira_dc.jira_dc_view.conversation_manager')
- @patch('integrations.jira_dc.jira_dc_view.get_final_agent_observation')
- async def test_create_or_update_conversation_success(
- self,
- mock_get_observation,
- mock_conversation_manager,
- mock_setup_init,
- mock_store_impl,
- existing_conversation_view,
- mock_jinja_env,
- mock_conversation_store,
- mock_conversation_init_data,
- mock_agent_loop_info,
- ):
- """Test successful existing conversation update"""
- # Setup mocks
- mock_store_impl.return_value = mock_conversation_store
- mock_setup_init.return_value = mock_conversation_init_data
- mock_conversation_manager.maybe_start_agent_loop = AsyncMock(
- return_value=mock_agent_loop_info
- )
- mock_conversation_manager.send_event_to_conversation = AsyncMock()
-
- # Mock agent observation with RUNNING state
- mock_observation = MagicMock()
- mock_observation.agent_state = AgentState.RUNNING
- mock_get_observation.return_value = [mock_observation]
-
- result = await existing_conversation_view.create_or_update_conversation(
- mock_jinja_env
- )
-
- assert result == 'conv-123'
- mock_conversation_manager.send_event_to_conversation.assert_called_once()
-
- @patch('integrations.jira_dc.jira_dc_view.ConversationStoreImpl.get_instance')
- async def test_create_or_update_conversation_no_metadata(
- self, mock_store_impl, existing_conversation_view, mock_jinja_env
- ):
- """Test conversation update with no metadata"""
- mock_store = AsyncMock()
- mock_store.get_metadata.side_effect = FileNotFoundError(
- 'No such file or directory'
- )
- mock_store_impl.return_value = mock_store
-
- with pytest.raises(
- StartingConvoException, match='Conversation no longer exists'
- ):
- await existing_conversation_view.create_or_update_conversation(
- mock_jinja_env
- )
-
- @patch('integrations.jira_dc.jira_dc_view.ConversationStoreImpl.get_instance')
- @patch('integrations.jira_dc.jira_dc_view.setup_init_conversation_settings')
- @patch('integrations.jira_dc.jira_dc_view.conversation_manager')
- @patch('integrations.jira_dc.jira_dc_view.get_final_agent_observation')
- async def test_create_or_update_conversation_loading_state(
- self,
- mock_get_observation,
- mock_conversation_manager,
- mock_setup_init,
- mock_store_impl,
- existing_conversation_view,
- mock_jinja_env,
- mock_conversation_store,
- mock_conversation_init_data,
- mock_agent_loop_info,
- ):
- """Test conversation update with loading state"""
- mock_store_impl.return_value = mock_conversation_store
- mock_setup_init.return_value = mock_conversation_init_data
- mock_conversation_manager.maybe_start_agent_loop = AsyncMock(
- return_value=mock_agent_loop_info
- )
-
- # Mock agent observation with LOADING state
- mock_observation = MagicMock()
- mock_observation.agent_state = AgentState.LOADING
- mock_get_observation.return_value = [mock_observation]
-
- with pytest.raises(
- StartingConvoException, match='Conversation is still starting'
- ):
- await existing_conversation_view.create_or_update_conversation(
- mock_jinja_env
- )
-
- @patch('integrations.jira_dc.jira_dc_view.ConversationStoreImpl.get_instance')
- async def test_create_or_update_conversation_failure(
- self, mock_store_impl, existing_conversation_view, mock_jinja_env
- ):
- """Test conversation update failure"""
- mock_store_impl.side_effect = Exception('Store error')
-
- with pytest.raises(
- StartingConvoException, match='Failed to create conversation'
- ):
- await existing_conversation_view.create_or_update_conversation(
- mock_jinja_env
- )
-
- def test_get_response_msg(self, existing_conversation_view):
- """Test get_response_msg method"""
- response = existing_conversation_view.get_response_msg()
-
- assert "I'm on it!" in response
- assert 'Test User' in response
- assert 'continue tracking my progress here' in response
- assert 'conv-123' in response
-
-
-class TestJiraDcFactory:
- """Tests for JiraDcFactory"""
-
- @patch('integrations.jira_dc.jira_dc_view.integration_store')
- async def test_create_jira_dc_view_from_payload_existing_conversation(
- self,
- mock_store,
- sample_job_context,
- sample_user_auth,
- sample_jira_dc_user,
- sample_jira_dc_workspace,
- jira_dc_conversation,
- ):
- """Test factory creating existing conversation view"""
- mock_store.get_user_conversations_by_issue_id = AsyncMock(
- return_value=jira_dc_conversation
- )
-
- view = await JiraDcFactory.create_jira_dc_view_from_payload(
- sample_job_context,
- sample_user_auth,
- sample_jira_dc_user,
- sample_jira_dc_workspace,
- )
-
- assert isinstance(view, JiraDcExistingConversationView)
- assert view.conversation_id == 'conv-123'
-
- @patch('integrations.jira_dc.jira_dc_view.integration_store')
- async def test_create_jira_dc_view_from_payload_new_conversation(
- self,
- mock_store,
- sample_job_context,
- sample_user_auth,
- sample_jira_dc_user,
- sample_jira_dc_workspace,
- ):
- """Test factory creating new conversation view"""
- mock_store.get_user_conversations_by_issue_id = AsyncMock(return_value=None)
-
- view = await JiraDcFactory.create_jira_dc_view_from_payload(
- sample_job_context,
- sample_user_auth,
- sample_jira_dc_user,
- sample_jira_dc_workspace,
- )
-
- assert isinstance(view, JiraDcNewConversationView)
- assert view.conversation_id == ''
-
- async def test_create_jira_dc_view_from_payload_no_user(
- self, sample_job_context, sample_user_auth, sample_jira_dc_workspace
- ):
- """Test factory with no Jira DC user"""
- with pytest.raises(StartingConvoException, match='User not authenticated'):
- await JiraDcFactory.create_jira_dc_view_from_payload(
- sample_job_context,
- sample_user_auth,
- None,
- sample_jira_dc_workspace, # type: ignore
- )
-
- async def test_create_jira_dc_view_from_payload_no_auth(
- self, sample_job_context, sample_jira_dc_user, sample_jira_dc_workspace
- ):
- """Test factory with no SaaS auth"""
- with pytest.raises(StartingConvoException, match='User not authenticated'):
- await JiraDcFactory.create_jira_dc_view_from_payload(
- sample_job_context,
- None,
- sample_jira_dc_user,
- sample_jira_dc_workspace, # type: ignore
- )
-
- async def test_create_jira_dc_view_from_payload_no_workspace(
- self, sample_job_context, sample_user_auth, sample_jira_dc_user
- ):
- """Test factory with no workspace"""
- with pytest.raises(StartingConvoException, match='User not authenticated'):
- await JiraDcFactory.create_jira_dc_view_from_payload(
- sample_job_context,
- sample_user_auth,
- sample_jira_dc_user,
- None, # type: ignore
- )
-
-
-class TestJiraDcViewEdgeCases:
- """Tests for edge cases and error scenarios"""
-
- @patch('integrations.jira_dc.jira_dc_view.create_new_conversation')
- @patch('integrations.jira_dc.jira_dc_view.integration_store')
- async def test_conversation_creation_with_no_user_secrets(
- self,
- mock_store,
- mock_create_conversation,
- new_conversation_view,
- mock_jinja_env,
- mock_agent_loop_info,
- ):
- """Test conversation creation when user has no secrets"""
- new_conversation_view.saas_user_auth.get_secrets.return_value = None
- mock_create_conversation.return_value = mock_agent_loop_info
- mock_store.create_conversation = AsyncMock()
-
- result = await new_conversation_view.create_or_update_conversation(
- mock_jinja_env
- )
-
- assert result == 'conv-123'
- # Verify create_new_conversation was called with custom_secrets=None
- call_kwargs = mock_create_conversation.call_args[1]
- assert call_kwargs['custom_secrets'] is None
-
- @patch('integrations.jira_dc.jira_dc_view.create_new_conversation')
- @patch('integrations.jira_dc.jira_dc_view.integration_store')
- async def test_conversation_creation_store_failure(
- self,
- mock_store,
- mock_create_conversation,
- new_conversation_view,
- mock_jinja_env,
- mock_agent_loop_info,
- ):
- """Test conversation creation when store creation fails"""
- mock_create_conversation.return_value = mock_agent_loop_info
- mock_store.create_conversation = AsyncMock(side_effect=Exception('Store error'))
-
- with pytest.raises(
- StartingConvoException, match='Failed to create conversation'
- ):
- await new_conversation_view.create_or_update_conversation(mock_jinja_env)
-
- @patch('integrations.jira_dc.jira_dc_view.ConversationStoreImpl.get_instance')
- @patch('integrations.jira_dc.jira_dc_view.setup_init_conversation_settings')
- @patch('integrations.jira_dc.jira_dc_view.conversation_manager')
- @patch('integrations.jira_dc.jira_dc_view.get_final_agent_observation')
- async def test_existing_conversation_empty_observations(
- self,
- mock_get_observation,
- mock_conversation_manager,
- mock_setup_init,
- mock_store_impl,
- existing_conversation_view,
- mock_jinja_env,
- mock_conversation_store,
- mock_conversation_init_data,
- mock_agent_loop_info,
- ):
- """Test existing conversation with empty observations"""
- mock_store_impl.return_value = mock_conversation_store
- mock_setup_init.return_value = mock_conversation_init_data
- mock_conversation_manager.maybe_start_agent_loop = AsyncMock(
- return_value=mock_agent_loop_info
- )
- mock_get_observation.return_value = [] # Empty observations
-
- with pytest.raises(
- StartingConvoException, match='Conversation is still starting'
- ):
- await existing_conversation_view.create_or_update_conversation(
- mock_jinja_env
- )
-
- def test_new_conversation_view_attributes(self, new_conversation_view):
- """Test new conversation view attribute access"""
- assert new_conversation_view.job_context.issue_key == 'PROJ-123'
- assert new_conversation_view.selected_repo == 'company/repo1'
- assert new_conversation_view.conversation_id == 'conv-123'
-
- def test_existing_conversation_view_attributes(self, existing_conversation_view):
- """Test existing conversation view attribute access"""
- assert existing_conversation_view.job_context.issue_key == 'PROJ-123'
- assert existing_conversation_view.selected_repo == 'company/repo1'
- assert existing_conversation_view.conversation_id == 'conv-123'
-
- @patch('integrations.jira_dc.jira_dc_view.ConversationStoreImpl.get_instance')
- @patch('integrations.jira_dc.jira_dc_view.setup_init_conversation_settings')
- @patch('integrations.jira_dc.jira_dc_view.conversation_manager')
- @patch('integrations.jira_dc.jira_dc_view.get_final_agent_observation')
- async def test_existing_conversation_message_send_failure(
- self,
- mock_get_observation,
- mock_conversation_manager,
- mock_setup_init,
- mock_store_impl,
- existing_conversation_view,
- mock_jinja_env,
- mock_conversation_store,
- mock_conversation_init_data,
- mock_agent_loop_info,
- ):
- """Test existing conversation when message sending fails"""
- mock_store_impl.return_value = mock_conversation_store
- mock_setup_init.return_value = mock_conversation_init_data
- mock_conversation_manager.maybe_start_agent_loop = AsyncMock(
- return_value=mock_agent_loop_info
- )
- mock_conversation_manager.send_event_to_conversation = AsyncMock(
- side_effect=Exception('Send error')
- )
-
- # Mock agent observation with RUNNING state
- mock_observation = MagicMock()
- mock_observation.agent_state = AgentState.RUNNING
- mock_get_observation.return_value = [mock_observation]
-
- with pytest.raises(
- StartingConvoException, match='Failed to create conversation'
- ):
- await existing_conversation_view.create_or_update_conversation(
- mock_jinja_env
- )
diff --git a/enterprise/tests/unit/integrations/linear/__init__.py b/enterprise/tests/unit/integrations/linear/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/enterprise/tests/unit/integrations/linear/conftest.py b/enterprise/tests/unit/integrations/linear/conftest.py
deleted file mode 100644
index 158fa5f8f0..0000000000
--- a/enterprise/tests/unit/integrations/linear/conftest.py
+++ /dev/null
@@ -1,220 +0,0 @@
-"""
-Shared fixtures for Linear integration tests.
-"""
-
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pytest
-from integrations.linear.linear_manager import LinearManager
-from integrations.linear.linear_view import (
- LinearExistingConversationView,
- LinearNewConversationView,
-)
-from integrations.models import JobContext
-from jinja2 import DictLoader, Environment
-from storage.linear_conversation import LinearConversation
-from storage.linear_user import LinearUser
-from storage.linear_workspace import LinearWorkspace
-
-from openhands.integrations.service_types import ProviderType, Repository
-from openhands.server.user_auth.user_auth import UserAuth
-
-
-def mock_token_manager():
- """Create a mock TokenManager for testing."""
- token_manager = MagicMock()
- token_manager.get_user_id_from_user_email = AsyncMock()
- token_manager.decrypt_text = MagicMock()
- return token_manager
-
-
-def linear_manager(mock_token_manager):
- """Create a LinearManager instance for testing."""
- with patch(
- 'integrations.linear.linear_manager.LinearIntegrationStore.get_instance'
- ) as mock_store_class:
- mock_store = MagicMock()
- mock_store.get_active_user = AsyncMock()
- mock_store.get_workspace_by_name = AsyncMock()
- mock_store_class.return_value = mock_store
- manager = LinearManager(mock_token_manager)
- return manager
-
-
-def sample_linear_user():
- """Create a sample LinearUser for testing."""
- user = MagicMock(spec=LinearUser)
- user.id = 1
- user.keycloak_user_id = 'test_keycloak_id'
- user.linear_workspace_id = 1
- user.status = 'active'
- return user
-
-
-def sample_linear_workspace():
- """Create a sample LinearWorkspace for testing."""
- workspace = MagicMock(spec=LinearWorkspace)
- workspace.id = 1
- workspace.name = 'test-workspace'
- workspace.admin_user_id = 'admin_id'
- workspace.webhook_secret = 'encrypted_secret'
- workspace.svc_acc_email = '[email protected]'
- workspace.svc_acc_api_key = 'encrypted_api_key'
- workspace.status = 'active'
- return workspace
-
-
-def sample_user_auth():
- """Create a mock UserAuth for testing."""
- user_auth = MagicMock(spec=UserAuth)
- user_auth.get_provider_tokens = AsyncMock(return_value={})
- user_auth.get_secrets = AsyncMock(return_value=MagicMock(custom_secrets={}))
- user_auth.get_access_token = AsyncMock(return_value='test_token')
- user_auth.get_user_id = AsyncMock(return_value='test_user_id')
- return user_auth
-
-
-def sample_job_context():
- """Create a sample JobContext for testing."""
- return JobContext(
- issue_id='test_issue_id',
- issue_key='TEST-123',
- user_msg='Fix this bug @openhands',
- user_email='[email protected]',
- display_name='Test User',
- workspace_name='test-workspace',
- issue_title='Test Issue',
- issue_description='This is a test issue',
- )
-
-
-def sample_webhook_payload():
- """Create a sample webhook payload for testing."""
- return {
- 'action': 'create',
- 'type': 'Comment',
- 'data': {
- 'body': 'Please fix this @openhands',
- 'issue': {
- 'id': 'test_issue_id',
- 'identifier': 'TEST-123',
- },
- },
- 'actor': {
- 'id': 'user123',
- 'name': 'Test User',
- 'email': '[email protected]',
- 'url': 'https://linear.app/test-workspace/profiles/user123',
- },
- }
-
-
-def sample_repositories():
- """Create sample repositories for testing."""
- return [
- Repository(
- id='1',
- full_name='test/repo1',
- stargazers_count=10,
- git_provider=ProviderType.GITHUB,
- is_public=True,
- ),
- Repository(
- id='2',
- full_name='test/repo2',
- stargazers_count=5,
- git_provider=ProviderType.GITHUB,
- is_public=False,
- ),
- ]
-
-
-def mock_jinja_env():
- """Mock Jinja2 environment with templates"""
- templates = {
- 'linear_instructions.j2': 'Test instructions template',
- 'linear_new_conversation.j2': 'New conversation: {{issue_key}} - {{issue_title}}\n{{issue_description}}\nUser: {{user_message}}',
- 'linear_existing_conversation.j2': 'Existing conversation: {{issue_key}} - {{issue_title}}\n{{issue_description}}\nUser: {{user_message}}',
- }
- return Environment(loader=DictLoader(templates))
-
-
-def linear_conversation():
- """Sample Linear conversation for testing"""
- return LinearConversation(
- conversation_id='conv-123',
- issue_id='test_issue_id',
- issue_key='TEST-123',
- linear_user_id='linear-user-123',
- )
-
-
-def new_conversation_view(
- sample_job_context, sample_user_auth, sample_linear_user, sample_linear_workspace
-):
- """LinearNewConversationView instance for testing"""
- return LinearNewConversationView(
- job_context=sample_job_context,
- saas_user_auth=sample_user_auth,
- linear_user=sample_linear_user,
- linear_workspace=sample_linear_workspace,
- selected_repo='test/repo1',
- conversation_id='conv-123',
- )
-
-
-def existing_conversation_view(
- sample_job_context, sample_user_auth, sample_linear_user, sample_linear_workspace
-):
- """LinearExistingConversationView instance for testing"""
- return LinearExistingConversationView(
- job_context=sample_job_context,
- saas_user_auth=sample_user_auth,
- linear_user=sample_linear_user,
- linear_workspace=sample_linear_workspace,
- selected_repo='test/repo1',
- conversation_id='conv-123',
- )
-
-
-def mock_agent_loop_info():
- """Mock agent loop info"""
- mock_info = MagicMock()
- mock_info.conversation_id = 'conv-123'
- mock_info.event_store = []
- return mock_info
-
-
-def mock_conversation_metadata():
- """Mock conversation metadata"""
- metadata = MagicMock()
- metadata.conversation_id = 'conv-123'
- return metadata
-
-
-def mock_conversation_store():
- """Mock conversation store"""
- store = AsyncMock()
- store.get_metadata.return_value = MagicMock()
- return store
-
-
-def mock_conversation_init_data():
- """Mock conversation initialization data"""
- return MagicMock()
diff --git a/enterprise/tests/unit/integrations/linear/test_linear_manager.py b/enterprise/tests/unit/integrations/linear/test_linear_manager.py
deleted file mode 100644
index c10fd7c507..0000000000
--- a/enterprise/tests/unit/integrations/linear/test_linear_manager.py
+++ /dev/null
@@ -1,1135 +0,0 @@
-"""
-Unit tests for LinearManager.
-"""
-
-import hashlib
-import hmac
-import json
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pytest
-from fastapi import Request
-from integrations.linear.linear_manager import LinearManager
-from integrations.linear.linear_types import LinearViewInterface
-from integrations.linear.linear_view import (
- LinearExistingConversationView,
- LinearNewConversationView,
-)
-from integrations.models import Message, SourceType
-
-from openhands.integrations.service_types import ProviderType, Repository
-from openhands.server.types import (
- LLMAuthenticationError,
- MissingSettingsError,
- SessionExpiredError,
-)
-
-
-class TestLinearManagerInit:
- """Test LinearManager initialization."""
-
- def test_init(self, mock_token_manager):
- """Test LinearManager initialization."""
- with patch(
- 'integrations.linear.linear_manager.LinearIntegrationStore.get_instance'
- ) as mock_store:
- mock_store.return_value = MagicMock()
- manager = LinearManager(mock_token_manager)
-
- assert manager.token_manager == mock_token_manager
- assert manager.api_url == 'https://api.linear.app/graphql'
- assert manager.integration_store is not None
- assert manager.jinja_env is not None
-
-
-class TestAuthenticateUser:
- """Test user authentication functionality."""
-
- @pytest.mark.asyncio
- async def test_authenticate_user_success(
- self, linear_manager, mock_token_manager, sample_linear_user, sample_user_auth
- ):
- """Test successful user authentication."""
- # Setup mocks
- linear_manager.integration_store.get_active_user.return_value = (
- sample_linear_user
- )
-
- with patch(
- 'integrations.linear.linear_manager.get_user_auth_from_keycloak_id',
- return_value=sample_user_auth,
- ):
- linear_user, user_auth = await linear_manager.authenticate_user(
- 'linear_user_123', 1
- )
-
- assert linear_user == sample_linear_user
- assert user_auth == sample_user_auth
- linear_manager.integration_store.get_active_user.assert_called_once_with(
- 'linear_user_123', 1
- )
-
- @pytest.mark.asyncio
- async def test_authenticate_user_no_keycloak_user(
- self, linear_manager, mock_token_manager
- ):
- """Test authentication when no Keycloak user is found."""
- linear_manager.integration_store.get_active_user.return_value = None
-
- linear_user, user_auth = await linear_manager.authenticate_user(
- 'linear_user_123', 1
- )
-
- assert linear_user is None
- assert user_auth is None
-
- @pytest.mark.asyncio
- async def test_authenticate_user_no_linear_user(
- self, linear_manager, mock_token_manager
- ):
- """Test authentication when no Linear user is found."""
- mock_token_manager.get_user_id_from_user_email.return_value = 'test_keycloak_id'
- linear_manager.integration_store.get_active_user.return_value = None
-
- linear_user, user_auth = await linear_manager.authenticate_user(
- )
-
- assert linear_user is None
- assert user_auth is None
-
-
-class TestGetRepositories:
- """Test repository retrieval functionality."""
-
- @pytest.mark.asyncio
- async def test_get_repositories_success(self, linear_manager, sample_user_auth):
- """Test successful repository retrieval."""
- mock_repos = [
- Repository(
- id='1',
- full_name='test/repo1',
- stargazers_count=10,
- git_provider=ProviderType.GITHUB,
- is_public=True,
- ),
- Repository(
- id='2',
- full_name='test/repo2',
- stargazers_count=5,
- git_provider=ProviderType.GITHUB,
- is_public=False,
- ),
- ]
-
- with patch(
- 'integrations.linear.linear_manager.ProviderHandler'
- ) as mock_provider:
- mock_client = MagicMock()
- mock_client.get_repositories = AsyncMock(return_value=mock_repos)
- mock_provider.return_value = mock_client
-
- repos = await linear_manager._get_repositories(sample_user_auth)
-
- assert repos == mock_repos
- mock_client.get_repositories.assert_called_once()
-
-
-class TestValidateRequest:
- """Test webhook request validation."""
-
- @pytest.mark.asyncio
- async def test_validate_request_success(
- self,
- linear_manager,
- mock_token_manager,
- sample_linear_workspace,
- sample_webhook_payload,
- ):
- """Test successful webhook validation."""
- # Setup mocks
- mock_token_manager.decrypt_text.return_value = 'test_secret'
- linear_manager.integration_store.get_workspace_by_name.return_value = (
- sample_linear_workspace
- )
-
- # Create mock request
- body = json.dumps(sample_webhook_payload).encode()
- signature = hmac.new('test_secret'.encode(), body, hashlib.sha256).hexdigest()
-
- mock_request = MagicMock(spec=Request)
- mock_request.headers = {'linear-signature': signature}
- mock_request.body = AsyncMock(return_value=body)
- mock_request.json = AsyncMock(return_value=sample_webhook_payload)
-
- is_valid, returned_signature, payload = await linear_manager.validate_request(
- mock_request
- )
-
- assert is_valid is True
- assert returned_signature == signature
- assert payload == sample_webhook_payload
-
- @pytest.mark.asyncio
- async def test_validate_request_missing_signature(
- self, linear_manager, sample_webhook_payload
- ):
- """Test webhook validation with missing signature."""
- mock_request = MagicMock(spec=Request)
- mock_request.headers = {}
- mock_request.body = AsyncMock(return_value=b'{}')
- mock_request.json = AsyncMock(return_value=sample_webhook_payload)
-
- is_valid, signature, payload = await linear_manager.validate_request(
- mock_request
- )
-
- assert is_valid is False
- assert signature is None
- assert payload is None
-
- @pytest.mark.asyncio
- async def test_validate_request_invalid_actor_url(self, linear_manager):
- """Test webhook validation with invalid actor URL."""
- invalid_payload = {
- 'actor': {
- 'url': 'https://invalid.com/user',
- 'name': 'Test User',
- 'email': '[email protected]',
- }
- }
-
- mock_request = MagicMock(spec=Request)
- mock_request.headers = {'linear-signature': 'test_signature'}
- mock_request.body = AsyncMock(return_value=b'{}')
- mock_request.json = AsyncMock(return_value=invalid_payload)
-
- is_valid, signature, payload = await linear_manager.validate_request(
- mock_request
- )
-
- assert is_valid is False
- assert signature is None
- assert payload is None
-
- @pytest.mark.asyncio
- async def test_validate_request_workspace_not_found(
- self, linear_manager, sample_webhook_payload
- ):
- """Test webhook validation when workspace is not found."""
- linear_manager.integration_store.get_workspace_by_name.return_value = None
-
- mock_request = MagicMock(spec=Request)
- mock_request.headers = {'linear-signature': 'test_signature'}
- mock_request.body = AsyncMock(return_value=b'{}')
- mock_request.json = AsyncMock(return_value=sample_webhook_payload)
-
- is_valid, signature, payload = await linear_manager.validate_request(
- mock_request
- )
-
- assert is_valid is False
- assert signature is None
- assert payload is None
-
- @pytest.mark.asyncio
- async def test_validate_request_workspace_inactive(
- self,
- linear_manager,
- mock_token_manager,
- sample_linear_workspace,
- sample_webhook_payload,
- ):
- """Test webhook validation when workspace is inactive."""
- sample_linear_workspace.status = 'inactive'
- linear_manager.integration_store.get_workspace_by_name.return_value = (
- sample_linear_workspace
- )
-
- mock_request = MagicMock(spec=Request)
- mock_request.headers = {'linear-signature': 'test_signature'}
- mock_request.body = AsyncMock(return_value=b'{}')
- mock_request.json = AsyncMock(return_value=sample_webhook_payload)
-
- is_valid, signature, payload = await linear_manager.validate_request(
- mock_request
- )
-
- assert is_valid is False
- assert signature is None
- assert payload is None
-
- @pytest.mark.asyncio
- async def test_validate_request_invalid_signature(
- self,
- linear_manager,
- mock_token_manager,
- sample_linear_workspace,
- sample_webhook_payload,
- ):
- """Test webhook validation with invalid signature."""
- mock_token_manager.decrypt_text.return_value = 'test_secret'
- linear_manager.integration_store.get_workspace_by_name.return_value = (
- sample_linear_workspace
- )
-
- mock_request = MagicMock(spec=Request)
- mock_request.headers = {'linear-signature': 'invalid_signature'}
- mock_request.body = AsyncMock(return_value=b'{}')
- mock_request.json = AsyncMock(return_value=sample_webhook_payload)
-
- is_valid, signature, payload = await linear_manager.validate_request(
- mock_request
- )
-
- assert is_valid is False
- assert signature is None
- assert payload is None
-
-
-class TestParseWebhook:
- """Test webhook parsing functionality."""
-
- def test_parse_webhook_comment_create(self, linear_manager, sample_webhook_payload):
- """Test parsing comment creation webhook."""
- job_context = linear_manager.parse_webhook(sample_webhook_payload)
-
- assert job_context is not None
- assert job_context.issue_id == 'test_issue_id'
- assert job_context.issue_key == 'TEST-123'
- assert job_context.user_msg == 'Please fix this @openhands'
- assert job_context.user_email == '[email protected]'
- assert job_context.display_name == 'Test User'
- assert job_context.workspace_name == 'test-workspace'
-
- def test_parse_webhook_comment_without_mention(self, linear_manager):
- """Test parsing comment without @openhands mention."""
- payload = {
- 'action': 'create',
- 'type': 'Comment',
- 'data': {
- 'body': 'Regular comment without mention',
- 'issue': {
- 'id': 'test_issue_id',
- 'identifier': 'TEST-123',
- },
- },
- 'actor': {
- 'name': 'Test User',
- 'email': '[email protected]',
- 'url': 'https://linear.app/test-workspace/profiles/user123',
- },
- }
-
- job_context = linear_manager.parse_webhook(payload)
- assert job_context is None
-
- def test_parse_webhook_issue_update_with_openhands_label(self, linear_manager):
- """Test parsing issue update with openhands label."""
- payload = {
- 'action': 'update',
- 'type': 'Issue',
- 'data': {
- 'id': 'test_issue_id',
- 'identifier': 'TEST-123',
- 'labels': [
- {'id': 'label1', 'name': 'bug'},
- {'id': 'label2', 'name': 'openhands'},
- ],
- 'updatedFrom': {
- 'labelIds': [] # Label was not added previously
- },
- },
- 'actor': {
- 'id': 'user123',
- 'name': 'Test User',
- 'email': '[email protected]',
- 'url': 'https://linear.app/test-workspace/profiles/user123',
- },
- }
-
- job_context = linear_manager.parse_webhook(payload)
-
- assert job_context is not None
- assert job_context.issue_id == 'test_issue_id'
- assert job_context.issue_key == 'TEST-123'
- assert job_context.user_msg == ''
-
- def test_parse_webhook_issue_update_without_openhands_label(self, linear_manager):
- """Test parsing issue update without openhands label."""
- payload = {
- 'action': 'update',
- 'type': 'Issue',
- 'data': {
- 'id': 'test_issue_id',
- 'identifier': 'TEST-123',
- 'labels': [
- {'id': 'label1', 'name': 'bug'},
- ],
- },
- 'actor': {
- 'name': 'Test User',
- 'email': '[email protected]',
- 'url': 'https://linear.app/test-workspace/profiles/user123',
- },
- }
-
- job_context = linear_manager.parse_webhook(payload)
- assert job_context is None
-
- def test_parse_webhook_issue_update_label_previously_added(self, linear_manager):
- """Test parsing issue update where openhands label was previously added."""
- payload = {
- 'action': 'update',
- 'type': 'Issue',
- 'data': {
- 'id': 'test_issue_id',
- 'identifier': 'TEST-123',
- 'labels': [
- {'id': 'label2', 'name': 'openhands'},
- ],
- 'updatedFrom': {
- 'labelIds': ['label2'] # Label was added previously
- },
- },
- 'actor': {
- 'name': 'Test User',
- 'email': '[email protected]',
- 'url': 'https://linear.app/test-workspace/profiles/user123',
- },
- }
-
- job_context = linear_manager.parse_webhook(payload)
- assert job_context is None
-
- def test_parse_webhook_unsupported_action(self, linear_manager):
- """Test parsing webhook with unsupported action."""
- payload = {
- 'action': 'delete',
- 'type': 'Comment',
- 'data': {},
- 'actor': {
- 'name': 'Test User',
- 'email': '[email protected]',
- 'url': 'https://linear.app/test-workspace/profiles/user123',
- },
- }
-
- job_context = linear_manager.parse_webhook(payload)
- assert job_context is None
-
- def test_parse_webhook_missing_required_fields(self, linear_manager):
- """Test parsing webhook with missing required fields."""
- payload = {
- 'action': 'create',
- 'type': 'Comment',
- 'data': {
- 'body': 'Please fix this @openhands',
- 'issue': {
- 'id': 'test_issue_id',
- # Missing identifier
- },
- },
- 'actor': {
- 'name': 'Test User',
- 'email': '[email protected]',
- 'url': 'https://linear.app/test-workspace/profiles/user123',
- },
- }
-
- job_context = linear_manager.parse_webhook(payload)
- assert job_context is None
-
-
-class TestReceiveMessage:
- """Test message receiving functionality."""
-
- @pytest.mark.asyncio
- async def test_receive_message_success(
- self,
- linear_manager,
- sample_webhook_payload,
- sample_linear_workspace,
- sample_linear_user,
- sample_user_auth,
- ):
- """Test successful message processing."""
- # Setup mocks
- linear_manager.integration_store.get_workspace_by_name.return_value = (
- sample_linear_workspace
- )
- linear_manager.authenticate_user = AsyncMock(
- return_value=(sample_linear_user, sample_user_auth)
- )
- linear_manager.get_issue_details = AsyncMock(
- return_value=('Test Title', 'Test Description')
- )
- linear_manager.is_job_requested = AsyncMock(return_value=True)
- linear_manager.start_job = AsyncMock()
-
- with patch(
- 'integrations.linear.linear_manager.LinearFactory.create_linear_view_from_payload'
- ) as mock_factory:
- mock_view = MagicMock(spec=LinearViewInterface)
- mock_factory.return_value = mock_view
-
- message = Message(
- source=SourceType.LINEAR, message={'payload': sample_webhook_payload}
- )
-
- await linear_manager.receive_message(message)
-
- linear_manager.start_job.assert_called_once_with(mock_view)
-
- @pytest.mark.asyncio
- async def test_receive_message_no_job_context(self, linear_manager):
- """Test message processing when no job context is parsed."""
- message = Message(
- source=SourceType.LINEAR, message={'payload': {'action': 'unsupported'}}
- )
-
- with patch.object(linear_manager, 'parse_webhook', return_value=None):
- await linear_manager.receive_message(message)
- # Should return early without processing
-
- @pytest.mark.asyncio
- async def test_receive_message_workspace_not_found(
- self, linear_manager, sample_webhook_payload
- ):
- """Test message processing when workspace is not found."""
- linear_manager.integration_store.get_workspace_by_name.return_value = None
- linear_manager._send_error_comment = AsyncMock()
-
- message = Message(
- source=SourceType.LINEAR, message={'payload': sample_webhook_payload}
- )
-
- await linear_manager.receive_message(message)
-
- linear_manager._send_error_comment.assert_called_once()
-
- @pytest.mark.asyncio
- async def test_receive_message_service_account_user(
- self, linear_manager, sample_webhook_payload, sample_linear_workspace
- ):
- """Test message processing from service account user (should be ignored)."""
- sample_linear_workspace.svc_acc_email = '[email protected]' # Same as webhook user
- linear_manager.integration_store.get_workspace_by_name.return_value = (
- sample_linear_workspace
- )
-
- message = Message(
- source=SourceType.LINEAR, message={'payload': sample_webhook_payload}
- )
-
- await linear_manager.receive_message(message)
- # Should return early without further processing
-
- @pytest.mark.asyncio
- async def test_receive_message_workspace_inactive(
- self, linear_manager, sample_webhook_payload, sample_linear_workspace
- ):
- """Test message processing when workspace is inactive."""
- sample_linear_workspace.status = 'inactive'
- linear_manager.integration_store.get_workspace_by_name.return_value = (
- sample_linear_workspace
- )
- linear_manager._send_error_comment = AsyncMock()
-
- message = Message(
- source=SourceType.LINEAR, message={'payload': sample_webhook_payload}
- )
-
- await linear_manager.receive_message(message)
-
- linear_manager._send_error_comment.assert_called_once()
-
- @pytest.mark.asyncio
- async def test_receive_message_authentication_failed(
- self, linear_manager, sample_webhook_payload, sample_linear_workspace
- ):
- """Test message processing when user authentication fails."""
- linear_manager.integration_store.get_workspace_by_name.return_value = (
- sample_linear_workspace
- )
- linear_manager.authenticate_user = AsyncMock(return_value=(None, None))
- linear_manager._send_error_comment = AsyncMock()
-
- message = Message(
- source=SourceType.LINEAR, message={'payload': sample_webhook_payload}
- )
-
- await linear_manager.receive_message(message)
-
- linear_manager._send_error_comment.assert_called_once()
-
- @pytest.mark.asyncio
- async def test_receive_message_get_issue_details_failed(
- self,
- linear_manager,
- sample_webhook_payload,
- sample_linear_workspace,
- sample_linear_user,
- sample_user_auth,
- ):
- """Test message processing when getting issue details fails."""
- linear_manager.integration_store.get_workspace_by_name.return_value = (
- sample_linear_workspace
- )
- linear_manager.authenticate_user = AsyncMock(
- return_value=(sample_linear_user, sample_user_auth)
- )
- linear_manager.get_issue_details = AsyncMock(side_effect=Exception('API Error'))
- linear_manager._send_error_comment = AsyncMock()
-
- message = Message(
- source=SourceType.LINEAR, message={'payload': sample_webhook_payload}
- )
-
- await linear_manager.receive_message(message)
-
- linear_manager._send_error_comment.assert_called_once()
-
- @pytest.mark.asyncio
- async def test_receive_message_create_view_failed(
- self,
- linear_manager,
- sample_webhook_payload,
- sample_linear_workspace,
- sample_linear_user,
- sample_user_auth,
- ):
- """Test message processing when creating Linear view fails."""
- linear_manager.integration_store.get_workspace_by_name.return_value = (
- sample_linear_workspace
- )
- linear_manager.authenticate_user = AsyncMock(
- return_value=(sample_linear_user, sample_user_auth)
- )
- linear_manager.get_issue_details = AsyncMock(
- return_value=('Test Title', 'Test Description')
- )
- linear_manager._send_error_comment = AsyncMock()
-
- with patch(
- 'integrations.linear.linear_manager.LinearFactory.create_linear_view_from_payload'
- ) as mock_factory:
- mock_factory.side_effect = Exception('View creation failed')
-
- message = Message(
- source=SourceType.LINEAR, message={'payload': sample_webhook_payload}
- )
-
- await linear_manager.receive_message(message)
-
- linear_manager._send_error_comment.assert_called_once()
-
-
-class TestIsJobRequested:
- """Test job request validation."""
-
- @pytest.mark.asyncio
- async def test_is_job_requested_existing_conversation(self, linear_manager):
- """Test job request validation for existing conversation."""
- mock_view = MagicMock(spec=LinearExistingConversationView)
- message = Message(source=SourceType.LINEAR, message={})
-
- result = await linear_manager.is_job_requested(message, mock_view)
- assert result is True
-
- @pytest.mark.asyncio
- async def test_is_job_requested_new_conversation_with_repo_match(
- self, linear_manager, sample_job_context, sample_user_auth
- ):
- """Test job request validation for new conversation with repository match."""
- mock_view = MagicMock(spec=LinearNewConversationView)
- mock_view.saas_user_auth = sample_user_auth
- mock_view.job_context = sample_job_context
-
- mock_repos = [
- Repository(
- id='1',
- full_name='test/repo',
- stargazers_count=10,
- git_provider=ProviderType.GITHUB,
- is_public=True,
- )
- ]
- linear_manager._get_repositories = AsyncMock(return_value=mock_repos)
-
- with patch(
- 'integrations.linear.linear_manager.filter_potential_repos_by_user_msg'
- ) as mock_filter:
- mock_filter.return_value = (True, mock_repos)
-
- message = Message(source=SourceType.LINEAR, message={})
- result = await linear_manager.is_job_requested(message, mock_view)
-
- assert result is True
- assert mock_view.selected_repo == 'test/repo'
-
- @pytest.mark.asyncio
- async def test_is_job_requested_new_conversation_no_repo_match(
- self, linear_manager, sample_job_context, sample_user_auth
- ):
- """Test job request validation for new conversation without repository match."""
- mock_view = MagicMock(spec=LinearNewConversationView)
- mock_view.saas_user_auth = sample_user_auth
- mock_view.job_context = sample_job_context
-
- mock_repos = [
- Repository(
- id='1',
- full_name='test/repo',
- stargazers_count=10,
- git_provider=ProviderType.GITHUB,
- is_public=True,
- )
- ]
- linear_manager._get_repositories = AsyncMock(return_value=mock_repos)
- linear_manager._send_repo_selection_comment = AsyncMock()
-
- with patch(
- 'integrations.linear.linear_manager.filter_potential_repos_by_user_msg'
- ) as mock_filter:
- mock_filter.return_value = (False, [])
-
- message = Message(source=SourceType.LINEAR, message={})
- result = await linear_manager.is_job_requested(message, mock_view)
-
- assert result is False
- linear_manager._send_repo_selection_comment.assert_called_once_with(
- mock_view
- )
-
- @pytest.mark.asyncio
- async def test_is_job_requested_exception(self, linear_manager, sample_user_auth):
- """Test job request validation when an exception occurs."""
- mock_view = MagicMock(spec=LinearNewConversationView)
- mock_view.saas_user_auth = sample_user_auth
- linear_manager._get_repositories = AsyncMock(
- side_effect=Exception('Repository error')
- )
-
- message = Message(source=SourceType.LINEAR, message={})
- result = await linear_manager.is_job_requested(message, mock_view)
-
- assert result is False
-
-
-class TestStartJob:
- """Test job starting functionality."""
-
- @pytest.mark.asyncio
- async def test_start_job_success_new_conversation(
- self, linear_manager, sample_linear_workspace
- ):
- """Test successful job start for new conversation."""
- mock_view = MagicMock(spec=LinearNewConversationView)
- mock_view.linear_user = MagicMock()
- mock_view.linear_user.keycloak_user_id = 'test_user'
- mock_view.job_context = MagicMock()
- mock_view.job_context.issue_key = 'TEST-123'
- mock_view.job_context.issue_id = 'issue_id'
- mock_view.linear_workspace = sample_linear_workspace
- mock_view.create_or_update_conversation = AsyncMock(return_value='conv_123')
- mock_view.get_response_msg = MagicMock(return_value='Job started successfully')
-
- linear_manager.send_message = AsyncMock()
- linear_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
-
- with patch(
- 'integrations.linear.linear_manager.register_callback_processor'
- ) as mock_register:
- with patch(
- 'server.conversation_callback_processor.linear_callback_processor.LinearCallbackProcessor'
- ):
- await linear_manager.start_job(mock_view)
-
- mock_view.create_or_update_conversation.assert_called_once()
- mock_register.assert_called_once()
- linear_manager.send_message.assert_called_once()
-
- @pytest.mark.asyncio
- async def test_start_job_success_existing_conversation(
- self, linear_manager, sample_linear_workspace
- ):
- """Test successful job start for existing conversation."""
- mock_view = MagicMock(spec=LinearExistingConversationView)
- mock_view.linear_user = MagicMock()
- mock_view.linear_user.keycloak_user_id = 'test_user'
- mock_view.job_context = MagicMock()
- mock_view.job_context.issue_key = 'TEST-123'
- mock_view.job_context.issue_id = 'issue_id'
- mock_view.linear_workspace = sample_linear_workspace
- mock_view.create_or_update_conversation = AsyncMock(return_value='conv_123')
- mock_view.get_response_msg = MagicMock(return_value='Job started successfully')
-
- linear_manager.send_message = AsyncMock()
- linear_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
-
- with patch(
- 'integrations.linear.linear_manager.register_callback_processor'
- ) as mock_register:
- await linear_manager.start_job(mock_view)
-
- mock_view.create_or_update_conversation.assert_called_once()
- # Should not register callback for existing conversation
- mock_register.assert_not_called()
- linear_manager.send_message.assert_called_once()
-
- @pytest.mark.asyncio
- async def test_start_job_missing_settings_error(
- self, linear_manager, sample_linear_workspace
- ):
- """Test job start with missing settings error."""
- mock_view = MagicMock(spec=LinearNewConversationView)
- mock_view.linear_user = MagicMock()
- mock_view.linear_user.keycloak_user_id = 'test_user'
- mock_view.job_context = MagicMock()
- mock_view.job_context.issue_key = 'TEST-123'
- mock_view.job_context.issue_id = 'issue_id'
- mock_view.linear_workspace = sample_linear_workspace
- mock_view.create_or_update_conversation = AsyncMock(
- side_effect=MissingSettingsError('Missing settings')
- )
-
- linear_manager.send_message = AsyncMock()
- linear_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
-
- await linear_manager.start_job(mock_view)
-
- # Should send error message about re-login
- linear_manager.send_message.assert_called_once()
- call_args = linear_manager.send_message.call_args[0]
- assert 'Please re-login' in call_args[0]
-
- @pytest.mark.asyncio
- async def test_start_job_llm_authentication_error(
- self, linear_manager, sample_linear_workspace
- ):
- """Test job start with LLM authentication error."""
- mock_view = MagicMock(spec=LinearNewConversationView)
- mock_view.linear_user = MagicMock()
- mock_view.linear_user.keycloak_user_id = 'test_user'
- mock_view.job_context = MagicMock()
- mock_view.job_context.issue_key = 'TEST-123'
- mock_view.job_context.issue_id = 'issue_id'
- mock_view.linear_workspace = sample_linear_workspace
- mock_view.create_or_update_conversation = AsyncMock(
- side_effect=LLMAuthenticationError('LLM auth failed')
- )
-
- linear_manager.send_message = AsyncMock()
- linear_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
-
- await linear_manager.start_job(mock_view)
-
- # Should send error message about LLM API key
- linear_manager.send_message.assert_called_once()
- call_args = linear_manager.send_message.call_args[0]
- assert 'valid LLM API key' in call_args[0]
-
- @pytest.mark.asyncio
- async def test_start_job_session_expired_error(
- self, linear_manager, sample_linear_workspace
- ):
- """Test job start with session expired error."""
- mock_view = MagicMock(spec=LinearNewConversationView)
- mock_view.linear_user = MagicMock()
- mock_view.linear_user.keycloak_user_id = 'test_user'
- mock_view.job_context = MagicMock()
- mock_view.job_context.issue_key = 'TEST-123'
- mock_view.job_context.issue_id = 'issue_id'
- mock_view.linear_workspace = sample_linear_workspace
- mock_view.create_or_update_conversation = AsyncMock(
- side_effect=SessionExpiredError('Session expired')
- )
-
- linear_manager.send_message = AsyncMock()
- linear_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
-
- await linear_manager.start_job(mock_view)
-
- # Should send error message about session expired
- linear_manager.send_message.assert_called_once()
- call_args = linear_manager.send_message.call_args[0]
- assert 'session has expired' in call_args[0]
- assert 'login again' in call_args[0]
-
- @pytest.mark.asyncio
- async def test_start_job_unexpected_error(
- self, linear_manager, sample_linear_workspace
- ):
- """Test job start with unexpected error."""
- mock_view = MagicMock(spec=LinearNewConversationView)
- mock_view.linear_user = MagicMock()
- mock_view.linear_user.keycloak_user_id = 'test_user'
- mock_view.job_context = MagicMock()
- mock_view.job_context.issue_key = 'TEST-123'
- mock_view.job_context.issue_id = 'issue_id'
- mock_view.linear_workspace = sample_linear_workspace
- mock_view.create_or_update_conversation = AsyncMock(
- side_effect=Exception('Unexpected error')
- )
-
- linear_manager.send_message = AsyncMock()
- linear_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
-
- await linear_manager.start_job(mock_view)
-
- # Should send generic error message
- linear_manager.send_message.assert_called_once()
- call_args = linear_manager.send_message.call_args[0]
- assert 'unexpected error' in call_args[0]
-
- @pytest.mark.asyncio
- async def test_start_job_send_message_fails(
- self, linear_manager, sample_linear_workspace
- ):
- """Test job start when sending message fails."""
- mock_view = MagicMock(spec=LinearNewConversationView)
- mock_view.linear_user = MagicMock()
- mock_view.linear_user.keycloak_user_id = 'test_user'
- mock_view.job_context = MagicMock()
- mock_view.job_context.issue_key = 'TEST-123'
- mock_view.job_context.issue_id = 'issue_id'
- mock_view.linear_workspace = sample_linear_workspace
- mock_view.create_or_update_conversation = AsyncMock(return_value='conv_123')
- mock_view.get_response_msg = MagicMock(return_value='Job started successfully')
-
- linear_manager.send_message = AsyncMock(side_effect=Exception('Send failed'))
- linear_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
-
- with patch('integrations.linear.linear_manager.register_callback_processor'):
- # Should not raise exception even if send_message fails
- await linear_manager.start_job(mock_view)
-
-
-class TestQueryApi:
- """Test API query functionality."""
-
- @pytest.mark.asyncio
- async def test_query_api_success(self, linear_manager):
- """Test successful API query."""
- mock_response = MagicMock()
- mock_response.json.return_value = {'data': {'test': 'result'}}
- mock_response.raise_for_status = MagicMock()
-
- with patch('httpx.AsyncClient') as mock_client:
- mock_client.return_value.__aenter__.return_value.post = AsyncMock(
- return_value=mock_response
- )
-
- result = await linear_manager._query_api(
- 'query Test { test }', {'var': 'value'}, 'test_api_key'
- )
-
- assert result == {'data': {'test': 'result'}}
- mock_response.raise_for_status.assert_called_once()
-
-
-class TestGetIssueDetails:
- """Test issue details retrieval."""
-
- @pytest.mark.asyncio
- async def test_get_issue_details_success(self, linear_manager):
- """Test successful issue details retrieval."""
- mock_response = {
- 'data': {
- 'issue': {
- 'id': 'test_id',
- 'identifier': 'TEST-123',
- 'title': 'Test Issue',
- 'description': 'Test description',
- 'syncedWith': [],
- }
- }
- }
-
- linear_manager._query_api = AsyncMock(return_value=mock_response)
-
- title, description = await linear_manager.get_issue_details(
- 'test_id', 'api_key'
- )
-
- assert title == 'Test Issue'
- assert description == 'Test description'
-
- @pytest.mark.asyncio
- async def test_get_issue_details_with_synced_repo(self, linear_manager):
- """Test issue details retrieval with synced GitHub repository."""
- mock_response = {
- 'data': {
- 'issue': {
- 'id': 'test_id',
- 'identifier': 'TEST-123',
- 'title': 'Test Issue',
- 'description': 'Test description',
- 'syncedWith': [
- {'metadata': {'owner': 'test-owner', 'repo': 'test-repo'}}
- ],
- }
- }
- }
-
- linear_manager._query_api = AsyncMock(return_value=mock_response)
-
- title, description = await linear_manager.get_issue_details(
- 'test_id', 'api_key'
- )
-
- assert title == 'Test Issue'
- assert 'Git Repo: test-owner/test-repo' in description
-
- @pytest.mark.asyncio
- async def test_get_issue_details_no_issue(self, linear_manager):
- """Test issue details retrieval when issue is not found."""
- linear_manager._query_api = AsyncMock(return_value=None)
-
- with pytest.raises(ValueError, match='Issue with ID test_id not found'):
- await linear_manager.get_issue_details('test_id', 'api_key')
-
- @pytest.mark.asyncio
- async def test_get_issue_details_no_title(self, linear_manager):
- """Test issue details retrieval when issue has no title."""
- mock_response = {
- 'data': {
- 'issue': {
- 'id': 'test_id',
- 'identifier': 'TEST-123',
- 'title': '',
- 'description': 'Test description',
- 'syncedWith': [],
- }
- }
- }
-
- linear_manager._query_api = AsyncMock(return_value=mock_response)
-
- with pytest.raises(
- ValueError, match='Issue with ID test_id does not have a title'
- ):
- await linear_manager.get_issue_details('test_id', 'api_key')
-
- @pytest.mark.asyncio
- async def test_get_issue_details_no_description(self, linear_manager):
- """Test issue details retrieval when issue has no description."""
- mock_response = {
- 'data': {
- 'issue': {
- 'id': 'test_id',
- 'identifier': 'TEST-123',
- 'title': 'Test Issue',
- 'description': '',
- 'syncedWith': [],
- }
- }
- }
-
- linear_manager._query_api = AsyncMock(return_value=mock_response)
-
- with pytest.raises(
- ValueError, match='Issue with ID test_id does not have a description'
- ):
- await linear_manager.get_issue_details('test_id', 'api_key')
-
-
-class TestSendMessage:
- """Test message sending functionality."""
-
- @pytest.mark.asyncio
- async def test_send_message_success(self, linear_manager):
- """Test successful message sending."""
- mock_response = {
- 'data': {
- 'commentCreate': {'success': True, 'comment': {'id': 'comment_id'}}
- }
- }
-
- linear_manager._query_api = AsyncMock(return_value=mock_response)
-
- result = await linear_manager.send_message(
- 'Test message', 'issue_id', 'api_key'
- )
-
- assert result == mock_response
- linear_manager._query_api.assert_called_once()
-
-
-class TestSendErrorComment:
- """Test error comment sending."""
-
- @pytest.mark.asyncio
- async def test_send_error_comment_success(
- self, linear_manager, sample_linear_workspace
- ):
- """Test successful error comment sending."""
- linear_manager.send_message = AsyncMock()
- linear_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
-
- await linear_manager._send_error_comment(
- 'issue_id', 'Error message', sample_linear_workspace
- )
-
- linear_manager.send_message.assert_called_once()
-
- @pytest.mark.asyncio
- async def test_send_error_comment_no_workspace(self, linear_manager):
- """Test error comment sending when no workspace is provided."""
- await linear_manager._send_error_comment('issue_id', 'Error message', None)
- # Should not raise exception
-
- @pytest.mark.asyncio
- async def test_send_error_comment_send_fails(
- self, linear_manager, sample_linear_workspace
- ):
- """Test error comment sending when send_message fails."""
- linear_manager.send_message = AsyncMock(side_effect=Exception('Send failed'))
- linear_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
-
- # Should not raise exception even if send_message fails
- await linear_manager._send_error_comment(
- 'issue_id', 'Error message', sample_linear_workspace
- )
-
-
-class TestSendRepoSelectionComment:
- """Test repository selection comment sending."""
-
- @pytest.mark.asyncio
- async def test_send_repo_selection_comment_success(
- self, linear_manager, sample_linear_workspace
- ):
- """Test successful repository selection comment sending."""
- mock_view = MagicMock(spec=LinearViewInterface)
- mock_view.linear_workspace = sample_linear_workspace
- mock_view.job_context = MagicMock()
- mock_view.job_context.issue_id = 'issue_id'
- mock_view.job_context.issue_key = 'TEST-123'
-
- linear_manager.send_message = AsyncMock()
- linear_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
-
- await linear_manager._send_repo_selection_comment(mock_view)
-
- linear_manager.send_message.assert_called_once()
- call_args = linear_manager.send_message.call_args[0]
- assert 'which repository to work with' in call_args[0]
-
- @pytest.mark.asyncio
- async def test_send_repo_selection_comment_send_fails(
- self, linear_manager, sample_linear_workspace
- ):
- """Test repository selection comment sending when send_message fails."""
- mock_view = MagicMock(spec=LinearViewInterface)
- mock_view.linear_workspace = sample_linear_workspace
- mock_view.job_context = MagicMock()
- mock_view.job_context.issue_id = 'issue_id'
- mock_view.job_context.issue_key = 'TEST-123'
-
- linear_manager.send_message = AsyncMock(side_effect=Exception('Send failed'))
- linear_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
-
- # Should not raise exception even if send_message fails
- await linear_manager._send_repo_selection_comment(mock_view)
diff --git a/enterprise/tests/unit/integrations/linear/test_linear_view.py b/enterprise/tests/unit/integrations/linear/test_linear_view.py
deleted file mode 100644
index 537f31dd97..0000000000
--- a/enterprise/tests/unit/integrations/linear/test_linear_view.py
+++ /dev/null
@@ -1,456 +0,0 @@
-"""
-Tests for Linear view classes and factory.
-"""
-
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pytest
-from integrations.linear.linear_types import StartingConvoException
-from integrations.linear.linear_view import (
- LinearExistingConversationView,
- LinearFactory,
- LinearNewConversationView,
-)
-
-from openhands.core.schema.agent import AgentState
-
-
-class TestLinearNewConversationView:
- """Tests for LinearNewConversationView"""
-
- async def test_get_instructions(self, new_conversation_view, mock_jinja_env):
- """Test _get_instructions method"""
- instructions, user_msg = await new_conversation_view._get_instructions(
- mock_jinja_env
- )
-
- assert instructions == 'Test instructions template'
- assert 'TEST-123' in user_msg
- assert 'Test Issue' in user_msg
- assert 'Fix this bug @openhands' in user_msg
-
- @patch(
- 'integrations.linear.linear_view.SaasConversationStore.get_resolver_instance',
- new_callable=AsyncMock,
- )
- @patch('integrations.linear.linear_view.start_conversation', new_callable=AsyncMock)
- @patch('integrations.linear.linear_view.integration_store')
- async def test_create_or_update_conversation_success(
- self,
- mock_integration_store,
- mock_start_convo,
- mock_get_resolver_instance,
- new_conversation_view,
- mock_jinja_env,
- ):
- """Test successful conversation creation"""
- mock_store = MagicMock()
- mock_store.save_metadata = AsyncMock()
- mock_get_resolver_instance.return_value = mock_store
- mock_integration_store.create_conversation = AsyncMock()
-
- result = await new_conversation_view.create_or_update_conversation(
- mock_jinja_env
- )
-
- assert result is not None
- mock_start_convo.assert_called_once()
- mock_integration_store.create_conversation.assert_called_once()
-
- async def test_create_or_update_conversation_no_repo(
- self, new_conversation_view, mock_jinja_env
- ):
- """Test conversation creation without selected repo"""
- new_conversation_view.selected_repo = None
-
- with pytest.raises(StartingConvoException, match='No repository selected'):
- await new_conversation_view.create_or_update_conversation(mock_jinja_env)
-
- @patch(
- 'integrations.linear.linear_view.SaasConversationStore.get_resolver_instance',
- new_callable=AsyncMock,
- )
- @patch('integrations.linear.linear_view.start_conversation', new_callable=AsyncMock)
- async def test_create_or_update_conversation_failure(
- self,
- mock_start_convo,
- mock_get_resolver_instance,
- new_conversation_view,
- mock_jinja_env,
- ):
- """Test conversation creation failure"""
- mock_store = MagicMock()
- mock_store.save_metadata = AsyncMock()
- mock_get_resolver_instance.return_value = mock_store
- mock_start_convo.side_effect = Exception('Creation failed')
-
- with pytest.raises(
- StartingConvoException, match='Failed to create conversation'
- ):
- await new_conversation_view.create_or_update_conversation(mock_jinja_env)
-
- def test_get_response_msg(self, new_conversation_view):
- """Test get_response_msg method"""
- response = new_conversation_view.get_response_msg()
-
- assert "I'm on it!" in response
- assert 'Test User' in response
- assert 'track my progress here' in response
- assert 'conv-123' in response
-
-
-class TestLinearExistingConversationView:
- """Tests for LinearExistingConversationView"""
-
- async def test_get_instructions(self, existing_conversation_view, mock_jinja_env):
- """Test _get_instructions method"""
- instructions, user_msg = await existing_conversation_view._get_instructions(
- mock_jinja_env
- )
-
- assert instructions == ''
- assert 'TEST-123' in user_msg
- assert 'Test Issue' in user_msg
- assert 'Fix this bug @openhands' in user_msg
-
- @patch('integrations.linear.linear_view.ConversationStoreImpl.get_instance')
- @patch('integrations.linear.linear_view.setup_init_conversation_settings')
- @patch('integrations.linear.linear_view.conversation_manager')
- @patch('integrations.linear.linear_view.get_final_agent_observation')
- async def test_create_or_update_conversation_success(
- self,
- mock_get_observation,
- mock_conversation_manager,
- mock_setup_init,
- mock_store_impl,
- existing_conversation_view,
- mock_jinja_env,
- mock_conversation_store,
- mock_conversation_init_data,
- mock_agent_loop_info,
- ):
- """Test successful existing conversation update"""
- # Setup mocks
- mock_store_impl.return_value = mock_conversation_store
- mock_setup_init.return_value = mock_conversation_init_data
- mock_conversation_manager.maybe_start_agent_loop = AsyncMock(
- return_value=mock_agent_loop_info
- )
- mock_conversation_manager.send_event_to_conversation = AsyncMock()
-
- # Mock agent observation with RUNNING state
- mock_observation = MagicMock()
- mock_observation.agent_state = AgentState.RUNNING
- mock_get_observation.return_value = [mock_observation]
-
- result = await existing_conversation_view.create_or_update_conversation(
- mock_jinja_env
- )
-
- assert result == 'conv-123'
- mock_conversation_manager.send_event_to_conversation.assert_called_once()
-
- @patch('integrations.linear.linear_view.ConversationStoreImpl.get_instance')
- async def test_create_or_update_conversation_no_metadata(
- self, mock_store_impl, existing_conversation_view, mock_jinja_env
- ):
- """Test conversation update with no metadata"""
- mock_store = AsyncMock()
- mock_store.get_metadata.side_effect = FileNotFoundError(
- 'No such file or directory'
- )
- mock_store_impl.return_value = mock_store
-
- with pytest.raises(
- StartingConvoException, match='Conversation no longer exists'
- ):
- await existing_conversation_view.create_or_update_conversation(
- mock_jinja_env
- )
-
- @patch('integrations.linear.linear_view.ConversationStoreImpl.get_instance')
- @patch('integrations.linear.linear_view.setup_init_conversation_settings')
- @patch('integrations.linear.linear_view.conversation_manager')
- @patch('integrations.linear.linear_view.get_final_agent_observation')
- async def test_create_or_update_conversation_loading_state(
- self,
- mock_get_observation,
- mock_conversation_manager,
- mock_setup_init,
- mock_store_impl,
- existing_conversation_view,
- mock_jinja_env,
- mock_conversation_store,
- mock_conversation_init_data,
- mock_agent_loop_info,
- ):
- """Test conversation update with loading state"""
- mock_store_impl.return_value = mock_conversation_store
- mock_setup_init.return_value = mock_conversation_init_data
- mock_conversation_manager.maybe_start_agent_loop = AsyncMock(
- return_value=mock_agent_loop_info
- )
-
- # Mock agent observation with LOADING state
- mock_observation = MagicMock()
- mock_observation.agent_state = AgentState.LOADING
- mock_get_observation.return_value = [mock_observation]
-
- with pytest.raises(
- StartingConvoException, match='Conversation is still starting'
- ):
- await existing_conversation_view.create_or_update_conversation(
- mock_jinja_env
- )
-
- @patch('integrations.linear.linear_view.ConversationStoreImpl.get_instance')
- async def test_create_or_update_conversation_failure(
- self, mock_store_impl, existing_conversation_view, mock_jinja_env
- ):
- """Test conversation update failure"""
- mock_store_impl.side_effect = Exception('Store error')
-
- with pytest.raises(
- StartingConvoException, match='Failed to create conversation'
- ):
- await existing_conversation_view.create_or_update_conversation(
- mock_jinja_env
- )
-
- def test_get_response_msg(self, existing_conversation_view):
- """Test get_response_msg method"""
- response = existing_conversation_view.get_response_msg()
-
- assert "I'm on it!" in response
- assert 'Test User' in response
- assert 'continue tracking my progress here' in response
- assert 'conv-123' in response
-
-
-class TestLinearFactory:
- """Tests for LinearFactory"""
-
- @patch('integrations.linear.linear_view.integration_store')
- async def test_create_linear_view_from_payload_existing_conversation(
- self,
- mock_store,
- sample_job_context,
- sample_user_auth,
- sample_linear_user,
- sample_linear_workspace,
- linear_conversation,
- ):
- """Test factory creating existing conversation view"""
- mock_store.get_user_conversations_by_issue_id = AsyncMock(
- return_value=linear_conversation
- )
-
- view = await LinearFactory.create_linear_view_from_payload(
- sample_job_context,
- sample_user_auth,
- sample_linear_user,
- sample_linear_workspace,
- )
-
- assert isinstance(view, LinearExistingConversationView)
- assert view.conversation_id == 'conv-123'
-
- @patch('integrations.linear.linear_view.integration_store')
- async def test_create_linear_view_from_payload_new_conversation(
- self,
- mock_store,
- sample_job_context,
- sample_user_auth,
- sample_linear_user,
- sample_linear_workspace,
- ):
- """Test factory creating new conversation view"""
- mock_store.get_user_conversations_by_issue_id = AsyncMock(return_value=None)
-
- view = await LinearFactory.create_linear_view_from_payload(
- sample_job_context,
- sample_user_auth,
- sample_linear_user,
- sample_linear_workspace,
- )
-
- assert isinstance(view, LinearNewConversationView)
- assert view.conversation_id == ''
-
- async def test_create_linear_view_from_payload_no_user(
- self, sample_job_context, sample_user_auth, sample_linear_workspace
- ):
- """Test factory with no Linear user"""
- with pytest.raises(StartingConvoException, match='User not authenticated'):
- await LinearFactory.create_linear_view_from_payload(
- sample_job_context,
- sample_user_auth,
- None,
- sample_linear_workspace, # type: ignore
- )
-
- async def test_create_linear_view_from_payload_no_auth(
- self, sample_job_context, sample_linear_user, sample_linear_workspace
- ):
- """Test factory with no SaaS auth"""
- with pytest.raises(StartingConvoException, match='User not authenticated'):
- await LinearFactory.create_linear_view_from_payload(
- sample_job_context,
- None,
- sample_linear_user,
- sample_linear_workspace, # type: ignore
- )
-
- async def test_create_linear_view_from_payload_no_workspace(
- self, sample_job_context, sample_user_auth, sample_linear_user
- ):
- """Test factory with no workspace"""
- with pytest.raises(StartingConvoException, match='User not authenticated'):
- await LinearFactory.create_linear_view_from_payload(
- sample_job_context,
- sample_user_auth,
- sample_linear_user,
- None, # type: ignore
- )
-
-
-class TestLinearViewEdgeCases:
- """Tests for edge cases and error scenarios"""
-
- @patch(
- 'integrations.linear.linear_view.SaasConversationStore.get_resolver_instance',
- new_callable=AsyncMock,
- )
- @patch('integrations.linear.linear_view.start_conversation', new_callable=AsyncMock)
- @patch('integrations.linear.linear_view.integration_store')
- async def test_conversation_creation_with_no_user_secrets(
- self,
- mock_integration_store,
- mock_start_convo,
- mock_get_resolver_instance,
- new_conversation_view,
- mock_jinja_env,
- ):
- """Test conversation creation when user has no secrets"""
- new_conversation_view.saas_user_auth.get_secrets = AsyncMock(return_value=None)
- mock_store = MagicMock()
- mock_store.save_metadata = AsyncMock()
- mock_get_resolver_instance.return_value = mock_store
- mock_integration_store.create_conversation = AsyncMock()
-
- result = await new_conversation_view.create_or_update_conversation(
- mock_jinja_env
- )
-
- assert result is not None
- # Verify start_conversation was called with custom_secrets=None
- call_kwargs = mock_start_convo.call_args[1]
- assert call_kwargs['custom_secrets'] is None
-
- @patch(
- 'integrations.linear.linear_view.SaasConversationStore.get_resolver_instance',
- new_callable=AsyncMock,
- )
- @patch('integrations.linear.linear_view.start_conversation', new_callable=AsyncMock)
- @patch('integrations.linear.linear_view.integration_store')
- async def test_conversation_creation_store_failure(
- self,
- mock_integration_store,
- mock_start_convo,
- mock_get_resolver_instance,
- new_conversation_view,
- mock_jinja_env,
- ):
- """Test conversation creation when store creation fails"""
- mock_store = MagicMock()
- mock_store.save_metadata = AsyncMock()
- mock_get_resolver_instance.return_value = mock_store
- mock_integration_store.create_conversation = AsyncMock(
- side_effect=Exception('Store error')
- )
-
- with pytest.raises(
- StartingConvoException, match='Failed to create conversation'
- ):
- await new_conversation_view.create_or_update_conversation(mock_jinja_env)
-
- @patch('integrations.linear.linear_view.ConversationStoreImpl.get_instance')
- @patch('integrations.linear.linear_view.setup_init_conversation_settings')
- @patch('integrations.linear.linear_view.conversation_manager')
- @patch('integrations.linear.linear_view.get_final_agent_observation')
- async def test_existing_conversation_empty_observations(
- self,
- mock_get_observation,
- mock_conversation_manager,
- mock_setup_init,
- mock_store_impl,
- existing_conversation_view,
- mock_jinja_env,
- mock_conversation_store,
- mock_conversation_init_data,
- mock_agent_loop_info,
- ):
- """Test existing conversation with empty observations"""
- mock_store_impl.return_value = mock_conversation_store
- mock_setup_init.return_value = mock_conversation_init_data
- mock_conversation_manager.maybe_start_agent_loop = AsyncMock(
- return_value=mock_agent_loop_info
- )
- mock_get_observation.return_value = [] # Empty observations
-
- with pytest.raises(
- StartingConvoException, match='Conversation is still starting'
- ):
- await existing_conversation_view.create_or_update_conversation(
- mock_jinja_env
- )
-
- def test_new_conversation_view_attributes(self, new_conversation_view):
- """Test new conversation view attribute access"""
- assert new_conversation_view.job_context.issue_key == 'TEST-123'
- assert new_conversation_view.selected_repo == 'test/repo1'
- assert new_conversation_view.conversation_id == 'conv-123'
-
- def test_existing_conversation_view_attributes(self, existing_conversation_view):
- """Test existing conversation view attribute access"""
- assert existing_conversation_view.job_context.issue_key == 'TEST-123'
- assert existing_conversation_view.selected_repo == 'test/repo1'
- assert existing_conversation_view.conversation_id == 'conv-123'
-
- @patch('integrations.linear.linear_view.ConversationStoreImpl.get_instance')
- @patch('integrations.linear.linear_view.setup_init_conversation_settings')
- @patch('integrations.linear.linear_view.conversation_manager')
- @patch('integrations.linear.linear_view.get_final_agent_observation')
- async def test_existing_conversation_message_send_failure(
- self,
- mock_get_observation,
- mock_conversation_manager,
- mock_setup_init,
- mock_store_impl,
- existing_conversation_view,
- mock_jinja_env,
- mock_conversation_store,
- mock_conversation_init_data,
- mock_agent_loop_info,
- ):
- """Test existing conversation when message sending fails"""
- mock_store_impl.return_value = mock_conversation_store
- mock_setup_init.return_value = mock_conversation_init_data
- mock_conversation_manager.maybe_start_agent_loop.return_value = (
- mock_agent_loop_info
- )
- mock_conversation_manager.send_event_to_conversation = AsyncMock(
- side_effect=Exception('Send error')
- )
-
- # Mock agent observation with RUNNING state
- mock_observation = MagicMock()
- mock_observation.agent_state = AgentState.RUNNING
- mock_get_observation.return_value = [mock_observation]
-
- with pytest.raises(
- StartingConvoException, match='Failed to create conversation'
- ):
- await existing_conversation_view.create_or_update_conversation(
- mock_jinja_env
- )
diff --git a/enterprise/tests/unit/integrations/slack/test_slack_view.py b/enterprise/tests/unit/integrations/slack/test_slack_view.py
index fb1cc6193f..8a84448b65 100644
--- a/enterprise/tests/unit/integrations/slack/test_slack_view.py
+++ b/enterprise/tests/unit/integrations/slack/test_slack_view.py
@@ -1,9 +1,8 @@
-"""Tests for the Slack view classes and their v1 vs v0 conversation handling.
+"""Tests for the Slack view classes and V1 conversation handling.
-Focuses on the 3 essential scenarios:
-1. V1 vs V0 decision logic based on user setting
-2. Message routing to correct method based on conversation v1 flag
-3. Paused sandbox resumption for V1 conversations
+Focuses on V1 conversation scenarios:
+1. V1 conversation creation
+2. Paused sandbox resumption for V1 conversations
"""
from unittest.mock import AsyncMock, MagicMock, patch
@@ -70,37 +69,7 @@ def slack_new_conversation_view(mock_slack_user, mock_user_auth):
send_summary_instruction=True,
conversation_id='',
team_id='T1234567890',
- v1_enabled=False,
- )
-
-
-def slack_update_conversation_view_v0(mock_slack_user, mock_user_auth):
- """Create a SlackUpdateExistingConversationView instance for V0."""
- conversation_id = '87654321-4321-8765-4321-876543218765'
- mock_conversation = SlackConversation(
- conversation_id=conversation_id,
- channel_id='C1234567890',
- keycloak_user_id='test-user-123',
- parent_id='1234567890.123456',
- v1_enabled=False,
- )
- return SlackUpdateExistingConversationView(
- bot_access_token='xoxb-test-token',
- user_msg='Follow up message',
- slack_user_id='U1234567890',
- slack_to_openhands_user=mock_slack_user,
- saas_user_auth=mock_user_auth,
- channel_id='C1234567890',
- message_ts='1234567890.123457',
- thread_ts='1234567890.123456',
- selected_repo=None,
- should_extract=True,
- send_summary_instruction=True,
- conversation_id=conversation_id,
- slack_conversation=mock_conversation,
- team_id='T1234567890',
- v1_enabled=False,
+ v1_enabled=True,
)
@@ -135,38 +104,26 @@ def slack_update_conversation_view_v1(mock_slack_user, mock_user_auth):
# ---------------------------------------------------------------------------
-# Test 1: V1 vs V0 Decision Logic Based on User Setting
+# Test: V1 Conversation Creation
# ---------------------------------------------------------------------------
-class TestV1V0DecisionLogic:
- """Test the decision logic for choosing between V1 and V0 conversations based on user setting."""
+class TestV1ConversationCreation:
+ """Test V1 conversation creation in Slack integration."""
- @pytest.mark.parametrize(
- 'v1_enabled,expected_v1_flag',
- [
- (True, True), # V1 enabled, use V1
- (False, False), # V1 disabled, use V0
- ],
- )
@patch('integrations.slack.slack_view.is_v1_enabled_for_slack_resolver')
@patch.object(SlackNewConversationView, '_create_v1_conversation')
- @patch.object(SlackNewConversationView, '_create_v0_conversation')
- async def test_v1_v0_decision_logic(
+ async def test_v1_conversation_creation(
self,
- mock_create_v0,
mock_create_v1,
mock_is_v1_enabled,
slack_new_conversation_view,
mock_jinja_env,
- v1_enabled,
- expected_v1_flag,
):
- """Test the decision logic for V1 vs V0 conversation creation based on user setting."""
+ """Test that V1 conversations are created correctly."""
# Setup mocks
- mock_is_v1_enabled.return_value = v1_enabled
+ mock_is_v1_enabled.return_value = True
mock_create_v1.return_value = None
- mock_create_v0.return_value = None
# Execute
result = await slack_new_conversation_view.create_or_update_conversation(
@@ -175,40 +132,29 @@ class TestV1V0DecisionLogic:
# Verify
assert result == slack_new_conversation_view.conversation_id
- assert slack_new_conversation_view.v1_enabled == expected_v1_flag
-
- if v1_enabled:
- mock_create_v1.assert_called_once()
- mock_create_v0.assert_not_called()
- else:
- mock_create_v1.assert_not_called()
- mock_create_v0.assert_called_once()
+ assert slack_new_conversation_view.v1_enabled is True
+ mock_create_v1.assert_called_once()
# ---------------------------------------------------------------------------
-# Test 2: Message Routing Based on Conversation V1 Flag
+# Test: Message Routing to V1
# ---------------------------------------------------------------------------
class TestMessageRouting:
- """Test that message sending routes to correct method based on conversation v1 flag."""
+ """Test that message sending routes to V1 method."""
@patch.object(
SlackUpdateExistingConversationView, 'send_message_to_v1_conversation'
)
- @patch.object(
- SlackUpdateExistingConversationView, 'send_message_to_v0_conversation'
- )
async def test_message_routing_to_v1(
self,
- mock_send_v0,
mock_send_v1,
slack_update_conversation_view_v1,
mock_jinja_env,
):
"""Test that V1 conversations route to V1 message sending method."""
# Setup
- mock_send_v0.return_value = None
mock_send_v1.return_value = None
# Execute
@@ -219,39 +165,10 @@ class TestMessageRouting:
# Verify
assert result == slack_update_conversation_view_v1.conversation_id
mock_send_v1.assert_called_once_with(mock_jinja_env)
- mock_send_v0.assert_not_called()
-
- @patch.object(
- SlackUpdateExistingConversationView, 'send_message_to_v1_conversation'
- )
- @patch.object(
- SlackUpdateExistingConversationView, 'send_message_to_v0_conversation'
- )
- async def test_message_routing_to_v0(
- self,
- mock_send_v0,
- mock_send_v1,
- slack_update_conversation_view_v0,
- mock_jinja_env,
- ):
- """Test that V0 conversations route to V0 message sending method."""
- # Setup
- mock_send_v0.return_value = None
- mock_send_v1.return_value = None
-
- # Execute
- result = await slack_update_conversation_view_v0.create_or_update_conversation(
- mock_jinja_env
- )
-
- # Verify
- assert result == slack_update_conversation_view_v0.conversation_id
- mock_send_v0.assert_called_once_with(mock_jinja_env)
- mock_send_v1.assert_not_called()
# ---------------------------------------------------------------------------
-# Test 3: Paused Sandbox Resumption for V1 Conversations
+# Test: Paused Sandbox Resumption for V1 Conversations
# ---------------------------------------------------------------------------
diff --git a/enterprise/tests/unit/server/conversation_callback_processor/__init__.py b/enterprise/tests/unit/server/conversation_callback_processor/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/enterprise/tests/unit/server/conversation_callback_processor/test_jira_callback_processor.py b/enterprise/tests/unit/server/conversation_callback_processor/test_jira_callback_processor.py
deleted file mode 100644
index ea635334e1..0000000000
--- a/enterprise/tests/unit/server/conversation_callback_processor/test_jira_callback_processor.py
+++ /dev/null
@@ -1,396 +0,0 @@
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pytest
-from server.conversation_callback_processor.jira_callback_processor import (
- JiraCallbackProcessor,
-)
-
-from openhands.core.schema.agent import AgentState
-from openhands.events.action import MessageAction
-from openhands.events.observation.agent import AgentStateChangedObservation
-
-
-def processor():
- processor = JiraCallbackProcessor(
- issue_key='TEST-123',
- workspace_name='test-workspace',
- )
- return processor
-
-
-@patch('server.conversation_callback_processor.jira_callback_processor.jira_manager')
-async def test_send_comment_to_jira_success(mock_jira_manager, processor):
- # Setup
- mock_workspace = MagicMock(
- status='active',
- svc_acc_api_key='encrypted_key',
- jira_cloud_id='cloud123',
- svc_acc_email='[email protected]',
- )
- mock_jira_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=mock_workspace
- )
- mock_jira_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
- mock_jira_manager.send_message = AsyncMock()
-
- # Action
- await processor._send_comment_to_jira('This is a summary.')
-
- # Assert
- mock_jira_manager.integration_store.get_workspace_by_name.assert_called_once_with(
- 'test-workspace'
- )
- mock_jira_manager.send_message.assert_called_once()
-
-
-async def test_call_ignores_irrelevant_state(processor):
- callback = MagicMock()
- observation = AgentStateChangedObservation(
- agent_state=AgentState.RUNNING, content=''
- )
-
- with patch(
- 'server.conversation_callback_processor.jira_callback_processor.conversation_manager'
- ) as mock_conv_manager:
- await processor(callback, observation)
- mock_conv_manager.send_event_to_conversation.assert_not_called()
-
-
-@patch(
- 'server.conversation_callback_processor.jira_callback_processor.get_summary_instruction',
- return_value='Summarize this.',
-)
-@patch(
- 'server.conversation_callback_processor.jira_callback_processor.get_last_user_msg_from_conversation_manager',
- new_callable=AsyncMock,
-)
-@patch(
- 'server.conversation_callback_processor.jira_callback_processor.conversation_manager',
- new_callable=AsyncMock,
-)
-async def test_call_sends_summary_instruction(
- mock_conv_manager, mock_get_last_msg, mock_get_summary_instruction, processor
-):
- callback = MagicMock(conversation_id='conv1')
- observation = AgentStateChangedObservation(
- agent_state=AgentState.FINISHED, content=''
- )
- mock_get_last_msg.return_value = [
- MessageAction(content='Not a summary instruction')
- ]
-
- await processor(callback, observation)
-
- mock_conv_manager.send_event_to_conversation.assert_called_once()
- call_args = mock_conv_manager.send_event_to_conversation.call_args[0]
- assert call_args[0] == 'conv1'
- assert call_args[1]['action'] == 'message'
- assert call_args[1]['args']['content'] == 'Summarize this.'
-
-
-@patch('server.conversation_callback_processor.jira_callback_processor.jira_manager')
-@patch(
- 'server.conversation_callback_processor.jira_callback_processor.extract_summary_from_conversation_manager',
- new_callable=AsyncMock,
-)
-@patch(
- 'server.conversation_callback_processor.jira_callback_processor.get_last_user_msg_from_conversation_manager',
- new_callable=AsyncMock,
-)
-@patch(
- 'server.conversation_callback_processor.jira_callback_processor.get_summary_instruction',
- return_value='Summarize this.',
-)
-async def test_call_sends_summary_to_jira(
- mock_get_summary_instruction,
- mock_get_last_msg,
- mock_extract_summary,
- mock_jira_manager,
- processor,
-):
- callback = MagicMock(conversation_id='conv1')
- observation = AgentStateChangedObservation(
- agent_state=AgentState.AWAITING_USER_INPUT, content=''
- )
- mock_get_last_msg.return_value = [MessageAction(content='Summarize this.')]
- mock_extract_summary.return_value = 'Extracted summary.'
- mock_workspace = MagicMock(
- status='active',
- svc_acc_api_key='encrypted_key',
- jira_cloud_id='cloud123',
- svc_acc_email='[email protected]',
- )
- mock_jira_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=mock_workspace
- )
- mock_jira_manager.send_message = AsyncMock()
-
- with patch(
- 'server.conversation_callback_processor.jira_callback_processor.asyncio.create_task'
- ) as mock_create_task, patch(
- 'server.conversation_callback_processor.jira_callback_processor.conversation_manager'
- ) as mock_conv_manager:
- await processor(callback, observation)
- mock_create_task.assert_called_once()
- # To ensure the coro is awaited in test
- await mock_create_task.call_args[0][0]
-
- mock_extract_summary.assert_called_once_with(mock_conv_manager, 'conv1')
- mock_jira_manager.send_message.assert_called_once()
-
-
-@patch('server.conversation_callback_processor.jira_callback_processor.jira_manager')
-async def test_send_comment_to_jira_workspace_not_found(mock_jira_manager, processor):
- """Test behavior when workspace is not found"""
- # Setup
- mock_jira_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=None
- )
-
- # Action
- await processor._send_comment_to_jira('This is a summary.')
-
- # Assert
- mock_jira_manager.integration_store.get_workspace_by_name.assert_called_once_with(
- 'test-workspace'
- )
- # Should not attempt to send message when workspace not found
- mock_jira_manager.send_message.assert_not_called()
-
-
-@patch('server.conversation_callback_processor.jira_callback_processor.jira_manager')
-async def test_send_comment_to_jira_inactive_workspace(mock_jira_manager, processor):
- """Test behavior when workspace is inactive"""
- # Setup
- mock_workspace = MagicMock(status='inactive', svc_acc_api_key='encrypted_key')
- mock_jira_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=mock_workspace
- )
-
- # Action
- await processor._send_comment_to_jira('This is a summary.')
-
- # Assert
- # Should not attempt to send message when workspace is inactive
- mock_jira_manager.send_message.assert_not_called()
-
-
-@patch('server.conversation_callback_processor.jira_callback_processor.jira_manager')
-async def test_send_comment_to_jira_api_error(mock_jira_manager, processor):
- """Test behavior when API call fails"""
- # Setup
- mock_workspace = MagicMock(
- status='active',
- svc_acc_api_key='encrypted_key',
- jira_cloud_id='cloud123',
- svc_acc_email='[email protected]',
- )
- mock_jira_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=mock_workspace
- )
- mock_jira_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
- mock_jira_manager.send_message = AsyncMock(side_effect=Exception('API Error'))
-
- # Action - should not raise exception, but handle it gracefully
- await processor._send_comment_to_jira('This is a summary.')
-
- # Assert
- mock_jira_manager.send_message.assert_called_once()
-
-
-# Test with various agent states
- 'agent_state',
- [
- AgentState.LOADING,
- AgentState.RUNNING,
- AgentState.PAUSED,
- AgentState.STOPPED,
- AgentState.ERROR,
- ],
-)
-async def test_call_ignores_irrelevant_states(processor, agent_state):
- """Test that processor ignores irrelevant agent states"""
- callback = MagicMock()
- observation = AgentStateChangedObservation(agent_state=agent_state, content='')
-
- with patch(
- 'server.conversation_callback_processor.jira_callback_processor.conversation_manager'
- ) as mock_conv_manager:
- await processor(callback, observation)
- mock_conv_manager.send_event_to_conversation.assert_not_called()
-
-
- 'agent_state',
- [
- AgentState.AWAITING_USER_INPUT,
- AgentState.FINISHED,
- ],
-)
-async def test_call_processes_relevant_states(processor, agent_state):
- """Test that processor handles relevant agent states"""
- callback = MagicMock(conversation_id='conv1')
- observation = AgentStateChangedObservation(agent_state=agent_state, content='')
-
- with patch(
- 'server.conversation_callback_processor.jira_callback_processor.get_summary_instruction',
- return_value='Summarize this.',
- ), patch(
- 'server.conversation_callback_processor.jira_callback_processor.get_last_user_msg_from_conversation_manager',
- new_callable=AsyncMock,
- return_value=[MessageAction(content='Not a summary instruction')],
- ), patch(
- 'server.conversation_callback_processor.jira_callback_processor.conversation_manager',
- new_callable=AsyncMock,
- ) as mock_conv_manager:
- await processor(callback, observation)
- mock_conv_manager.send_event_to_conversation.assert_called_once()
-
-
-# Test empty last messages
-@patch(
- 'server.conversation_callback_processor.jira_callback_processor.get_summary_instruction',
- return_value='Summarize this.',
-)
-@patch(
- 'server.conversation_callback_processor.jira_callback_processor.get_last_user_msg_from_conversation_manager',
- new_callable=AsyncMock,
-)
-@patch(
- 'server.conversation_callback_processor.jira_callback_processor.conversation_manager',
- new_callable=AsyncMock,
-)
-async def test_call_handles_empty_last_messages(
- mock_conv_manager, mock_get_last_msg, mock_get_summary_instruction, processor
-):
- """Test behavior when there are no last user messages"""
- callback = MagicMock(conversation_id='conv1')
- observation = AgentStateChangedObservation(
- agent_state=AgentState.FINISHED, content=''
- )
- mock_get_last_msg.return_value = [] # Empty list
-
- await processor(callback, observation)
-
- # Should send summary instruction when no previous messages
- mock_conv_manager.send_event_to_conversation.assert_called_once()
-
-
-# Test exception handling in main callback
-@patch(
- 'server.conversation_callback_processor.jira_callback_processor.get_summary_instruction',
- side_effect=Exception('Unexpected error'),
-)
-async def test_call_handles_exceptions_gracefully(
- mock_get_summary_instruction, processor
-):
- """Test that exceptions in callback processing are handled gracefully"""
- callback = MagicMock(conversation_id='conv1')
- observation = AgentStateChangedObservation(
- agent_state=AgentState.FINISHED, content=''
- )
-
- # Should not raise exception
- await processor(callback, observation)
-
-
-# Test correct message construction
-@patch('server.conversation_callback_processor.jira_callback_processor.jira_manager')
-async def test_send_comment_to_jira_message_construction(mock_jira_manager, processor):
- """Test that outgoing message is constructed correctly"""
- # Setup
- mock_workspace = MagicMock(
- status='active',
- svc_acc_api_key='encrypted_key',
- id='workspace_123',
- jira_cloud_id='cloud123',
- svc_acc_email='[email protected]',
- )
- mock_jira_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=mock_workspace
- )
- mock_jira_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
- mock_jira_manager.send_message = AsyncMock()
-
- test_message = 'This is a test summary message.'
-
- # Action
- await processor._send_comment_to_jira(test_message)
-
- # Assert - send_message now receives the string directly
- mock_jira_manager.send_message.assert_called_once_with(
- test_message,
- issue_key='TEST-123',
- jira_cloud_id='cloud123',
- svc_acc_email='[email protected]',
- svc_acc_api_key='decrypted_key',
- )
-
-
-# Test asyncio.create_task usage
-@patch('server.conversation_callback_processor.jira_callback_processor.jira_manager')
-@patch(
- 'server.conversation_callback_processor.jira_callback_processor.extract_summary_from_conversation_manager',
- new_callable=AsyncMock,
-)
-@patch(
- 'server.conversation_callback_processor.jira_callback_processor.get_last_user_msg_from_conversation_manager',
- new_callable=AsyncMock,
-)
-@patch(
- 'server.conversation_callback_processor.jira_callback_processor.get_summary_instruction',
- return_value='Summarize this.',
-)
-async def test_call_creates_background_task_for_sending(
- mock_get_summary_instruction,
- mock_get_last_msg,
- mock_extract_summary,
- mock_jira_manager,
- processor,
-):
- """Test that summary sending is done in background task"""
- callback = MagicMock(conversation_id='conv1')
- observation = AgentStateChangedObservation(
- agent_state=AgentState.AWAITING_USER_INPUT, content=''
- )
- mock_get_last_msg.return_value = [MessageAction(content='Summarize this.')]
- mock_extract_summary.return_value = 'Extracted summary.'
- mock_workspace = MagicMock(
- status='active',
- svc_acc_api_key='encrypted_key',
- jira_cloud_id='cloud123',
- svc_acc_email='[email protected]',
- )
- mock_jira_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=mock_workspace
- )
- mock_jira_manager.send_message = AsyncMock()
-
- with patch(
- 'server.conversation_callback_processor.jira_callback_processor.asyncio.create_task'
- ) as mock_create_task, patch(
- 'server.conversation_callback_processor.jira_callback_processor.conversation_manager'
- ):
- await processor(callback, observation)
-
- # Verify that create_task was called
- mock_create_task.assert_called_once()
-
- # Verify the task is for sending comment
- task_coro = mock_create_task.call_args[0][0]
- assert task_coro.__class__.__name__ == 'coroutine'
diff --git a/enterprise/tests/unit/server/conversation_callback_processor/test_jira_dc_callback_processor.py b/enterprise/tests/unit/server/conversation_callback_processor/test_jira_dc_callback_processor.py
deleted file mode 100644
index 6e5e490c68..0000000000
--- a/enterprise/tests/unit/server/conversation_callback_processor/test_jira_dc_callback_processor.py
+++ /dev/null
@@ -1,392 +0,0 @@
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pytest
-from server.conversation_callback_processor.jira_dc_callback_processor import (
- JiraDcCallbackProcessor,
-)
-
-from openhands.core.schema.agent import AgentState
-from openhands.events.action import MessageAction
-from openhands.events.observation.agent import AgentStateChangedObservation
-
-
-def processor():
- processor = JiraDcCallbackProcessor(
- issue_key='TEST-123',
- workspace_name='test-workspace',
- base_api_url='https://test-jira-dc.company.com',
- )
- return processor
-
-
-@patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.jira_dc_manager'
-)
-async def test_send_comment_to_jira_dc_success(mock_jira_dc_manager, processor):
- # Setup
- mock_workspace = MagicMock(status='active', svc_acc_api_key='encrypted_key')
- mock_jira_dc_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=mock_workspace
- )
- mock_jira_dc_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
- mock_jira_dc_manager.send_message = AsyncMock()
-
- # Action
- await processor._send_comment_to_jira_dc('This is a summary.')
-
- # Assert
- mock_jira_dc_manager.integration_store.get_workspace_by_name.assert_called_once_with(
- 'test-workspace'
- )
- mock_jira_dc_manager.send_message.assert_called_once()
-
-
-async def test_call_ignores_irrelevant_state(processor):
- callback = MagicMock()
- observation = AgentStateChangedObservation(
- agent_state=AgentState.RUNNING, content=''
- )
-
- with patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.conversation_manager'
- ) as mock_conv_manager:
- await processor(callback, observation)
- mock_conv_manager.send_event_to_conversation.assert_not_called()
-
-
-@patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.get_summary_instruction',
- return_value='Summarize this.',
-)
-@patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.get_last_user_msg_from_conversation_manager',
- new_callable=AsyncMock,
-)
-@patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.conversation_manager',
- new_callable=AsyncMock,
-)
-async def test_call_sends_summary_instruction(
- mock_conv_manager, mock_get_last_msg, mock_get_summary_instruction, processor
-):
- callback = MagicMock(conversation_id='conv1')
- observation = AgentStateChangedObservation(
- agent_state=AgentState.FINISHED, content=''
- )
- mock_get_last_msg.return_value = [
- MessageAction(content='Not a summary instruction')
- ]
-
- await processor(callback, observation)
-
- mock_conv_manager.send_event_to_conversation.assert_called_once()
- call_args = mock_conv_manager.send_event_to_conversation.call_args[0]
- assert call_args[0] == 'conv1'
- assert call_args[1]['action'] == 'message'
- assert call_args[1]['args']['content'] == 'Summarize this.'
-
-
-@patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.jira_dc_manager'
-)
-@patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.extract_summary_from_conversation_manager',
- new_callable=AsyncMock,
-)
-@patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.get_last_user_msg_from_conversation_manager',
- new_callable=AsyncMock,
-)
-@patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.get_summary_instruction',
- return_value='Summarize this.',
-)
-async def test_call_sends_summary_to_jira_dc(
- mock_get_summary_instruction,
- mock_get_last_msg,
- mock_extract_summary,
- mock_jira_dc_manager,
- processor,
-):
- callback = MagicMock(conversation_id='conv1')
- observation = AgentStateChangedObservation(
- agent_state=AgentState.AWAITING_USER_INPUT, content=''
- )
- mock_get_last_msg.return_value = [MessageAction(content='Summarize this.')]
- mock_extract_summary.return_value = 'Extracted summary.'
- mock_workspace = MagicMock(status='active', svc_acc_api_key='encrypted_key')
- mock_jira_dc_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=mock_workspace
- )
- mock_jira_dc_manager.send_message = AsyncMock()
-
- with patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.asyncio.create_task'
- ) as mock_create_task, patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.conversation_manager'
- ) as mock_conv_manager:
- await processor(callback, observation)
- mock_create_task.assert_called_once()
- # To ensure the coro is awaited in test
- await mock_create_task.call_args[0][0]
-
- mock_extract_summary.assert_called_once_with(mock_conv_manager, 'conv1')
- mock_jira_dc_manager.send_message.assert_called_once()
-
-
-@patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.jira_dc_manager'
-)
-async def test_send_comment_to_jira_dc_workspace_not_found(
- mock_jira_dc_manager, processor
-):
- """Test behavior when workspace is not found"""
- # Setup
- mock_jira_dc_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=None
- )
-
- # Action
- await processor._send_comment_to_jira_dc('This is a summary.')
-
- # Assert
- mock_jira_dc_manager.integration_store.get_workspace_by_name.assert_called_once_with(
- 'test-workspace'
- )
- # Should not attempt to send message when workspace not found
- mock_jira_dc_manager.send_message.assert_not_called()
-
-
-@patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.jira_dc_manager'
-)
-async def test_send_comment_to_jira_dc_inactive_workspace(
- mock_jira_dc_manager, processor
-):
- """Test behavior when workspace is inactive"""
- # Setup
- mock_workspace = MagicMock(status='inactive', svc_acc_api_key='encrypted_key')
- mock_jira_dc_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=mock_workspace
- )
-
- # Action
- await processor._send_comment_to_jira_dc('This is a summary.')
-
- # Assert
- # Should not attempt to send message when workspace is inactive
- mock_jira_dc_manager.send_message.assert_not_called()
-
-
-@patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.jira_dc_manager'
-)
-async def test_send_comment_to_jira_dc_api_error(mock_jira_dc_manager, processor):
- """Test behavior when API call fails"""
- # Setup
- mock_workspace = MagicMock(status='active', svc_acc_api_key='encrypted_key')
- mock_jira_dc_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=mock_workspace
- )
- mock_jira_dc_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
- mock_jira_dc_manager.send_message = AsyncMock(side_effect=Exception('API Error'))
-
- # Action - should not raise exception, but handle it gracefully
- await processor._send_comment_to_jira_dc('This is a summary.')
-
- # Assert
- mock_jira_dc_manager.send_message.assert_called_once()
-
-
-# Test with various agent states
- 'agent_state',
- [
- AgentState.LOADING,
- AgentState.RUNNING,
- AgentState.PAUSED,
- AgentState.STOPPED,
- AgentState.ERROR,
- ],
-)
-async def test_call_ignores_irrelevant_states(processor, agent_state):
- """Test that processor ignores irrelevant agent states"""
- callback = MagicMock()
- observation = AgentStateChangedObservation(agent_state=agent_state, content='')
-
- with patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.conversation_manager'
- ) as mock_conv_manager:
- await processor(callback, observation)
- mock_conv_manager.send_event_to_conversation.assert_not_called()
-
-
- 'agent_state',
- [
- AgentState.AWAITING_USER_INPUT,
- AgentState.FINISHED,
- ],
-)
-async def test_call_processes_relevant_states(processor, agent_state):
- """Test that processor handles relevant agent states"""
- callback = MagicMock(conversation_id='conv1')
- observation = AgentStateChangedObservation(agent_state=agent_state, content='')
-
- with patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.get_summary_instruction',
- return_value='Summarize this.',
- ), patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.get_last_user_msg_from_conversation_manager',
- new_callable=AsyncMock,
- return_value=[MessageAction(content='Not a summary instruction')],
- ), patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.conversation_manager',
- new_callable=AsyncMock,
- ) as mock_conv_manager:
- await processor(callback, observation)
- mock_conv_manager.send_event_to_conversation.assert_called_once()
-
-
-# Test empty last messages
-@patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.get_summary_instruction',
- return_value='Summarize this.',
-)
-@patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.get_last_user_msg_from_conversation_manager',
- new_callable=AsyncMock,
-)
-@patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.conversation_manager',
- new_callable=AsyncMock,
-)
-async def test_call_handles_empty_last_messages(
- mock_conv_manager, mock_get_last_msg, mock_get_summary_instruction, processor
-):
- """Test behavior when there are no last user messages"""
- callback = MagicMock(conversation_id='conv1')
- observation = AgentStateChangedObservation(
- agent_state=AgentState.FINISHED, content=''
- )
- mock_get_last_msg.return_value = [] # Empty list
-
- await processor(callback, observation)
-
- # Should send summary instruction when no previous messages
- mock_conv_manager.send_event_to_conversation.assert_called_once()
-
-
-# Test exception handling in main callback
-@patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.get_summary_instruction',
- side_effect=Exception('Unexpected error'),
-)
-async def test_call_handles_exceptions_gracefully(
- mock_get_summary_instruction, processor
-):
- """Test that exceptions in callback processing are handled gracefully"""
- callback = MagicMock(conversation_id='conv1')
- observation = AgentStateChangedObservation(
- agent_state=AgentState.FINISHED, content=''
- )
-
- # Should not raise exception
- await processor(callback, observation)
-
-
-# Test correct message construction
-@patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.jira_dc_manager'
-)
-async def test_send_comment_to_jira_dc_message_construction(
- mock_jira_dc_manager, processor
-):
- """Test that outgoing message is constructed correctly"""
- # Setup
- mock_workspace = MagicMock(
- status='active', svc_acc_api_key='encrypted_key', id='workspace_123'
- )
- mock_jira_dc_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=mock_workspace
- )
- mock_jira_dc_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
- mock_jira_dc_manager.send_message = AsyncMock()
-
- test_message = 'This is a test summary message.'
-
- # Action
- await processor._send_comment_to_jira_dc(test_message)
-
- # Assert - send_message now receives the string directly
- mock_jira_dc_manager.send_message.assert_called_once_with(
- test_message,
- issue_key='TEST-123',
- base_api_url='https://test-jira-dc.company.com',
- svc_acc_api_key='decrypted_key',
- )
-
-
-# Test asyncio.create_task usage
-@patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.jira_dc_manager'
-)
-@patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.extract_summary_from_conversation_manager',
- new_callable=AsyncMock,
-)
-@patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.get_last_user_msg_from_conversation_manager',
- new_callable=AsyncMock,
-)
-@patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.get_summary_instruction',
- return_value='Summarize this.',
-)
-async def test_call_creates_background_task_for_sending(
- mock_get_summary_instruction,
- mock_get_last_msg,
- mock_extract_summary,
- mock_jira_dc_manager,
- processor,
-):
- """Test that summary sending is done in background task"""
- callback = MagicMock(conversation_id='conv1')
- observation = AgentStateChangedObservation(
- agent_state=AgentState.AWAITING_USER_INPUT, content=''
- )
- mock_get_last_msg.return_value = [MessageAction(content='Summarize this.')]
- mock_extract_summary.return_value = 'Extracted summary.'
- mock_workspace = MagicMock(status='active', svc_acc_api_key='encrypted_key')
- mock_jira_dc_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=mock_workspace
- )
- mock_jira_dc_manager.send_message = AsyncMock()
-
- with patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.asyncio.create_task'
- ) as mock_create_task, patch(
- 'server.conversation_callback_processor.jira_dc_callback_processor.conversation_manager'
- ):
- await processor(callback, observation)
-
- # Verify that create_task was called
- mock_create_task.assert_called_once()
-
- # Verify the task is for sending comment
- task_coro = mock_create_task.call_args[0][0]
- assert task_coro.__class__.__name__ == 'coroutine'
diff --git a/enterprise/tests/unit/server/conversation_callback_processor/test_linear_callback_processor.py b/enterprise/tests/unit/server/conversation_callback_processor/test_linear_callback_processor.py
deleted file mode 100644
index 513b15aa07..0000000000
--- a/enterprise/tests/unit/server/conversation_callback_processor/test_linear_callback_processor.py
+++ /dev/null
@@ -1,391 +0,0 @@
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pytest
-from server.conversation_callback_processor.linear_callback_processor import (
- LinearCallbackProcessor,
-)
-
-from openhands.core.schema.agent import AgentState
-from openhands.events.action import MessageAction
-from openhands.events.observation.agent import AgentStateChangedObservation
-
-
-def processor():
- processor = LinearCallbackProcessor(
- issue_id='TEST-123',
- issue_key='TEST-123',
- workspace_name='test-workspace',
- )
- return processor
-
-
-@patch(
- 'server.conversation_callback_processor.linear_callback_processor.linear_manager'
-)
-async def test_send_comment_to_linear_success(mock_linear_manager, processor):
- # Setup
- mock_workspace = MagicMock(status='active', svc_acc_api_key='encrypted_key')
- mock_linear_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=mock_workspace
- )
- mock_linear_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
- mock_linear_manager.send_message = AsyncMock()
-
- # Action
- await processor._send_comment_to_linear('This is a summary.')
-
- # Assert
- mock_linear_manager.integration_store.get_workspace_by_name.assert_called_once_with(
- 'test-workspace'
- )
- mock_linear_manager.send_message.assert_called_once()
-
-
-async def test_call_ignores_irrelevant_state(processor):
- callback = MagicMock()
- observation = AgentStateChangedObservation(
- agent_state=AgentState.RUNNING, content=''
- )
-
- with patch(
- 'server.conversation_callback_processor.linear_callback_processor.conversation_manager'
- ) as mock_conv_manager:
- await processor(callback, observation)
- mock_conv_manager.send_event_to_conversation.assert_not_called()
-
-
-@patch(
- 'server.conversation_callback_processor.linear_callback_processor.get_summary_instruction',
- return_value='Summarize this.',
-)
-@patch(
- 'server.conversation_callback_processor.linear_callback_processor.get_last_user_msg_from_conversation_manager',
- new_callable=AsyncMock,
-)
-@patch(
- 'server.conversation_callback_processor.linear_callback_processor.conversation_manager',
- new_callable=AsyncMock,
-)
-async def test_call_sends_summary_instruction(
- mock_conv_manager, mock_get_last_msg, mock_get_summary_instruction, processor
-):
- callback = MagicMock(conversation_id='conv1')
- observation = AgentStateChangedObservation(
- agent_state=AgentState.FINISHED, content=''
- )
- mock_get_last_msg.return_value = [
- MessageAction(content='Not a summary instruction')
- ]
-
- await processor(callback, observation)
-
- mock_conv_manager.send_event_to_conversation.assert_called_once()
- call_args = mock_conv_manager.send_event_to_conversation.call_args[0]
- assert call_args[0] == 'conv1'
- assert call_args[1]['action'] == 'message'
- assert call_args[1]['args']['content'] == 'Summarize this.'
-
-
-@patch(
- 'server.conversation_callback_processor.linear_callback_processor.linear_manager'
-)
-@patch(
- 'server.conversation_callback_processor.linear_callback_processor.extract_summary_from_conversation_manager',
- new_callable=AsyncMock,
-)
-@patch(
- 'server.conversation_callback_processor.linear_callback_processor.get_last_user_msg_from_conversation_manager',
- new_callable=AsyncMock,
-)
-@patch(
- 'server.conversation_callback_processor.linear_callback_processor.get_summary_instruction',
- return_value='Summarize this.',
-)
-async def test_call_sends_summary_to_linear(
- mock_get_summary_instruction,
- mock_get_last_msg,
- mock_extract_summary,
- mock_linear_manager,
- processor,
-):
- callback = MagicMock(conversation_id='conv1')
- observation = AgentStateChangedObservation(
- agent_state=AgentState.AWAITING_USER_INPUT, content=''
- )
- mock_get_last_msg.return_value = [MessageAction(content='Summarize this.')]
- mock_extract_summary.return_value = 'Extracted summary.'
- mock_workspace = MagicMock(status='active', svc_acc_api_key='encrypted_key')
- mock_linear_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=mock_workspace
- )
- mock_linear_manager.send_message = AsyncMock()
-
- with patch(
- 'server.conversation_callback_processor.linear_callback_processor.asyncio.create_task'
- ) as mock_create_task, patch(
- 'server.conversation_callback_processor.linear_callback_processor.conversation_manager'
- ) as mock_conv_manager:
- await processor(callback, observation)
- mock_create_task.assert_called_once()
- # To ensure the coro is awaited in test
- await mock_create_task.call_args[0][0]
-
- mock_extract_summary.assert_called_once_with(mock_conv_manager, 'conv1')
- mock_linear_manager.send_message.assert_called_once()
-
-
-@patch(
- 'server.conversation_callback_processor.linear_callback_processor.linear_manager'
-)
-async def test_send_comment_to_linear_workspace_not_found(
- mock_linear_manager, processor
-):
- """Test behavior when workspace is not found"""
- # Setup
- mock_linear_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=None
- )
-
- # Action
- await processor._send_comment_to_linear('This is a summary.')
-
- # Assert
- mock_linear_manager.integration_store.get_workspace_by_name.assert_called_once_with(
- 'test-workspace'
- )
- # Should not attempt to send message when workspace not found
- mock_linear_manager.send_message.assert_not_called()
-
-
-@patch(
- 'server.conversation_callback_processor.linear_callback_processor.linear_manager'
-)
-async def test_send_comment_to_linear_inactive_workspace(
- mock_linear_manager, processor
-):
- """Test behavior when workspace is inactive"""
- # Setup
- mock_workspace = MagicMock(status='inactive', svc_acc_api_key='encrypted_key')
- mock_linear_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=mock_workspace
- )
-
- # Action
- await processor._send_comment_to_linear('This is a summary.')
-
- # Assert
- # Should not attempt to send message when workspace is inactive
- mock_linear_manager.send_message.assert_not_called()
-
-
-@patch(
- 'server.conversation_callback_processor.linear_callback_processor.linear_manager'
-)
-async def test_send_comment_to_linear_api_error(mock_linear_manager, processor):
- """Test behavior when API call fails"""
- # Setup
- mock_workspace = MagicMock(status='active', svc_acc_api_key='encrypted_key')
- mock_linear_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=mock_workspace
- )
- mock_linear_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
- mock_linear_manager.send_message = AsyncMock(side_effect=Exception('API Error'))
-
- # Action - should not raise exception, but handle it gracefully
- await processor._send_comment_to_linear('This is a summary.')
-
- # Assert
- mock_linear_manager.send_message.assert_called_once()
-
-
-# Test with various agent states
- 'agent_state',
- [
- AgentState.LOADING,
- AgentState.RUNNING,
- AgentState.PAUSED,
- AgentState.STOPPED,
- AgentState.ERROR,
- ],
-)
-async def test_call_ignores_irrelevant_states(processor, agent_state):
- """Test that processor ignores irrelevant agent states"""
- callback = MagicMock()
- observation = AgentStateChangedObservation(agent_state=agent_state, content='')
-
- with patch(
- 'server.conversation_callback_processor.linear_callback_processor.conversation_manager'
- ) as mock_conv_manager:
- await processor(callback, observation)
- mock_conv_manager.send_event_to_conversation.assert_not_called()
-
-
- 'agent_state',
- [
- AgentState.AWAITING_USER_INPUT,
- AgentState.FINISHED,
- ],
-)
-async def test_call_processes_relevant_states(processor, agent_state):
- """Test that processor handles relevant agent states"""
- callback = MagicMock(conversation_id='conv1')
- observation = AgentStateChangedObservation(agent_state=agent_state, content='')
-
- with patch(
- 'server.conversation_callback_processor.linear_callback_processor.get_summary_instruction',
- return_value='Summarize this.',
- ), patch(
- 'server.conversation_callback_processor.linear_callback_processor.get_last_user_msg_from_conversation_manager',
- new_callable=AsyncMock,
- return_value=[MessageAction(content='Not a summary instruction')],
- ), patch(
- 'server.conversation_callback_processor.linear_callback_processor.conversation_manager',
- new_callable=AsyncMock,
- ) as mock_conv_manager:
- await processor(callback, observation)
- mock_conv_manager.send_event_to_conversation.assert_called_once()
-
-
-# Test empty last messages
-@patch(
- 'server.conversation_callback_processor.linear_callback_processor.get_summary_instruction',
- return_value='Summarize this.',
-)
-@patch(
- 'server.conversation_callback_processor.linear_callback_processor.get_last_user_msg_from_conversation_manager',
- new_callable=AsyncMock,
-)
-@patch(
- 'server.conversation_callback_processor.linear_callback_processor.conversation_manager',
- new_callable=AsyncMock,
-)
-async def test_call_handles_empty_last_messages(
- mock_conv_manager, mock_get_last_msg, mock_get_summary_instruction, processor
-):
- """Test behavior when there are no last user messages"""
- callback = MagicMock(conversation_id='conv1')
- observation = AgentStateChangedObservation(
- agent_state=AgentState.FINISHED, content=''
- )
- mock_get_last_msg.return_value = [] # Empty list
-
- await processor(callback, observation)
-
- # Should send summary instruction when no previous messages
- mock_conv_manager.send_event_to_conversation.assert_called_once()
-
-
-# Test exception handling in main callback
-@patch(
- 'server.conversation_callback_processor.linear_callback_processor.get_summary_instruction',
- side_effect=Exception('Unexpected error'),
-)
-async def test_call_handles_exceptions_gracefully(
- mock_get_summary_instruction, processor
-):
- """Test that exceptions in callback processing are handled gracefully"""
- callback = MagicMock(conversation_id='conv1')
- observation = AgentStateChangedObservation(
- agent_state=AgentState.FINISHED, content=''
- )
-
- # Should not raise exception
- await processor(callback, observation)
-
-
-# Test correct message construction
-@patch(
- 'server.conversation_callback_processor.linear_callback_processor.linear_manager'
-)
-async def test_send_comment_to_linear_message_construction(
- mock_linear_manager, processor
-):
- """Test that outgoing message is constructed correctly"""
- # Setup
- mock_workspace = MagicMock(
- status='active', svc_acc_api_key='encrypted_key', id='workspace_123'
- )
- mock_linear_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=mock_workspace
- )
- mock_linear_manager.token_manager.decrypt_text.return_value = 'decrypted_key'
- mock_linear_manager.send_message = AsyncMock()
-
- test_message = 'This is a test summary message.'
-
- # Action
- await processor._send_comment_to_linear(test_message)
-
- # Assert - send_message now receives the string directly
- mock_linear_manager.send_message.assert_called_once_with(
- test_message,
- 'TEST-123', # issue_id
- 'decrypted_key', # api_key
- )
-
-
-# Test asyncio.create_task usage
-@patch(
- 'server.conversation_callback_processor.linear_callback_processor.linear_manager'
-)
-@patch(
- 'server.conversation_callback_processor.linear_callback_processor.extract_summary_from_conversation_manager',
- new_callable=AsyncMock,
-)
-@patch(
- 'server.conversation_callback_processor.linear_callback_processor.get_last_user_msg_from_conversation_manager',
- new_callable=AsyncMock,
-)
-@patch(
- 'server.conversation_callback_processor.linear_callback_processor.get_summary_instruction',
- return_value='Summarize this.',
-)
-async def test_call_creates_background_task_for_sending(
- mock_get_summary_instruction,
- mock_get_last_msg,
- mock_extract_summary,
- mock_linear_manager,
- processor,
-):
- """Test that summary sending is done in background task"""
- callback = MagicMock(conversation_id='conv1')
- observation = AgentStateChangedObservation(
- agent_state=AgentState.AWAITING_USER_INPUT, content=''
- )
- mock_get_last_msg.return_value = [MessageAction(content='Summarize this.')]
- mock_extract_summary.return_value = 'Extracted summary.'
- mock_workspace = MagicMock(status='active', svc_acc_api_key='encrypted_key')
- mock_linear_manager.integration_store.get_workspace_by_name = AsyncMock(
- return_value=mock_workspace
- )
- mock_linear_manager.send_message = AsyncMock()
-
- with patch(
- 'server.conversation_callback_processor.linear_callback_processor.asyncio.create_task'
- ) as mock_create_task, patch(
- 'server.conversation_callback_processor.linear_callback_processor.conversation_manager'
- ):
- await processor(callback, observation)
-
- # Verify that create_task was called
- mock_create_task.assert_called_once()
-
- # Verify the task is for sending comment
- task_coro = mock_create_task.call_args[0][0]
- assert task_coro.__class__.__name__ == 'coroutine'
diff --git a/enterprise/tests/unit/server/routes/test_linear_integration_routes.py b/enterprise/tests/unit/server/routes/test_linear_integration_routes.py
deleted file mode 100644
index bfe4a4c011..0000000000
--- a/enterprise/tests/unit/server/routes/test_linear_integration_routes.py
+++ /dev/null
@@ -1,840 +0,0 @@
-import json
-from datetime import datetime
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pytest
-from fastapi import HTTPException, Request, status
-from fastapi.responses import RedirectResponse
-from pydantic import ValidationError
-from server.auth.saas_user_auth import SaasUserAuth
-from server.routes.integration.linear import (
- LinearLinkCreate,
- LinearWorkspaceCreate,
- _handle_workspace_link_creation,
- _validate_workspace_update_permissions,
- create_linear_workspace,
- create_workspace_link,
- get_current_workspace_link,
- linear_callback,
- linear_events,
- unlink_workspace,
- validate_workspace_integration,
-)
-
-
-def mock_request():
- req = MagicMock(spec=Request)
- req.headers = {}
- req.cookies = {}
- req.app.state.redis = MagicMock()
- return req
-
-
-def mock_linear_manager():
- manager = MagicMock()
- manager.integration_store = AsyncMock()
- manager.validate_request = AsyncMock()
- return manager
-
-
-def mock_token_manager():
- return MagicMock()
-
-
-def mock_redis_client():
- client = MagicMock()
- client.exists.return_value = False
- client.setex.return_value = True
- return client
-
-
-def mock_user_auth():
- auth = AsyncMock(spec=SaasUserAuth)
- auth.get_user_id = AsyncMock(return_value='test_user_id')
- auth.get_user_email = AsyncMock(return_value='[email protected]')
- return auth
-
-
-# Test Pydantic Model Validations
-class TestLinearWorkspaceCreateValidation:
- def test_valid_workspace_create(self):
- data = LinearWorkspaceCreate(
- workspace_name='test-workspace',
- webhook_secret='secret123',
- svc_acc_email='[email protected]',
- svc_acc_api_key='api_key_123',
- is_active=True,
- )
- assert data.workspace_name == 'test-workspace'
- assert data.svc_acc_email == '[email protected]'
-
- def test_invalid_workspace_name(self):
- with pytest.raises(ValidationError) as exc_info:
- LinearWorkspaceCreate(
- workspace_name='test workspace!', # Contains space and special char
- webhook_secret='secret123',
- svc_acc_email='[email protected]',
- svc_acc_api_key='api_key_123',
- )
- assert 'workspace_name can only contain alphanumeric characters' in str(
- exc_info.value
- )
-
- def test_invalid_email(self):
- with pytest.raises(ValidationError) as exc_info:
- LinearWorkspaceCreate(
- workspace_name='test-workspace',
- webhook_secret='secret123',
- svc_acc_email='invalid-email',
- svc_acc_api_key='api_key_123',
- )
- assert 'svc_acc_email must be a valid email address' in str(exc_info.value)
-
- def test_webhook_secret_with_spaces(self):
- with pytest.raises(ValidationError) as exc_info:
- LinearWorkspaceCreate(
- workspace_name='test-workspace',
- webhook_secret='secret with spaces',
- svc_acc_email='[email protected]',
- svc_acc_api_key='api_key_123',
- )
- assert 'webhook_secret cannot contain spaces' in str(exc_info.value)
-
- def test_api_key_with_spaces(self):
- with pytest.raises(ValidationError) as exc_info:
- LinearWorkspaceCreate(
- workspace_name='test-workspace',
- webhook_secret='secret123',
- svc_acc_email='[email protected]',
- svc_acc_api_key='api key with spaces',
- )
- assert 'svc_acc_api_key cannot contain spaces' in str(exc_info.value)
-
-
-class TestLinearLinkCreateValidation:
- def test_valid_link_create(self):
- data = LinearLinkCreate(workspace_name='test-workspace')
- assert data.workspace_name == 'test-workspace'
-
- def test_invalid_workspace_name(self):
- with pytest.raises(ValidationError) as exc_info:
- LinearLinkCreate(workspace_name='invalid workspace!')
- assert 'workspace can only contain alphanumeric characters' in str(
- exc_info.value
- )
-
-
-# Test linear_events error scenarios
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-@patch('server.routes.integration.linear.redis_client', new_callable=MagicMock)
-async def test_linear_events_processing_success(mock_redis, mock_manager, mock_request):
- with patch('server.routes.integration.linear.LINEAR_WEBHOOKS_ENABLED', True):
- mock_manager.validate_request.return_value = (
- True,
- 'sig123',
- {'test': 'payload'},
- )
- mock_redis.exists.return_value = False
-
- background_tasks = MagicMock()
- response = await linear_events(mock_request, background_tasks)
-
- assert response.status_code == 200
- body = json.loads(response.body)
- assert body['success'] is True
- mock_redis.setex.assert_called_once_with('linear:sig123', 60, 1)
- background_tasks.add_task.assert_called_once()
-
-
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-@patch('server.routes.integration.linear.redis_client', new_callable=MagicMock)
-async def test_linear_events_general_exception(mock_redis, mock_manager, mock_request):
- with patch('server.routes.integration.linear.LINEAR_WEBHOOKS_ENABLED', True):
- mock_manager.validate_request.side_effect = Exception('Unexpected error')
-
- response = await linear_events(mock_request, MagicMock())
-
- assert response.status_code == 500
- body = json.loads(response.body)
- assert 'Internal server error processing webhook' in body['error']
-
-
-# Test create_linear_workspace error scenarios
-@patch('server.routes.integration.linear.get_user_auth')
-async def test_create_linear_workspace_auth_failure(mock_get_auth, mock_request):
- mock_get_auth.side_effect = HTTPException(status_code=401, detail='Unauthorized')
-
- workspace_data = LinearWorkspaceCreate(
- workspace_name='test-workspace',
- webhook_secret='secret',
- svc_acc_email='[email protected]',
- svc_acc_api_key='key',
- )
-
- with pytest.raises(HTTPException) as exc_info:
- await create_linear_workspace(mock_request, workspace_data)
- assert exc_info.value.status_code == 401
-
-
-@patch('server.routes.integration.linear.get_user_auth')
-@patch('server.routes.integration.linear.redis_client')
-async def test_create_linear_workspace_redis_failure(
- mock_redis, mock_get_auth, mock_request, mock_user_auth
-):
- mock_get_auth.return_value = mock_user_auth
- mock_redis.setex.return_value = False # Redis operation failed
-
- workspace_data = LinearWorkspaceCreate(
- workspace_name='test-workspace',
- webhook_secret='secret',
- svc_acc_email='[email protected]',
- svc_acc_api_key='key',
- )
-
- with pytest.raises(HTTPException) as exc_info:
- await create_linear_workspace(mock_request, workspace_data)
- assert exc_info.value.status_code == 500
- assert 'Failed to create integration session' in exc_info.value.detail
-
-
-@patch('server.routes.integration.linear.get_user_auth')
-async def test_create_linear_workspace_unexpected_error(mock_get_auth, mock_request):
- mock_get_auth.side_effect = Exception('Unexpected error')
-
- workspace_data = LinearWorkspaceCreate(
- workspace_name='test-workspace',
- webhook_secret='secret',
- svc_acc_email='[email protected]',
- svc_acc_api_key='key',
- )
-
- with pytest.raises(HTTPException) as exc_info:
- await create_linear_workspace(mock_request, workspace_data)
- assert exc_info.value.status_code == 500
- assert 'Failed to create workspace' in exc_info.value.detail
-
-
-# Test create_workspace_link error scenarios
-@patch('server.routes.integration.linear.get_user_auth')
-@patch('server.routes.integration.linear.redis_client')
-async def test_create_workspace_link_redis_failure(
- mock_redis, mock_get_auth, mock_request, mock_user_auth
-):
- mock_get_auth.return_value = mock_user_auth
- mock_redis.setex.return_value = False
-
- link_data = LinearLinkCreate(workspace_name='test-workspace')
-
- with pytest.raises(HTTPException) as exc_info:
- await create_workspace_link(mock_request, link_data)
- assert exc_info.value.status_code == 500
- assert 'Failed to create integration session' in exc_info.value.detail
-
-
-@patch('server.routes.integration.linear.get_user_auth')
-async def test_create_workspace_link_unexpected_error(mock_get_auth, mock_request):
- mock_get_auth.side_effect = Exception('Unexpected error')
-
- link_data = LinearLinkCreate(workspace_name='test-workspace')
-
- with pytest.raises(HTTPException) as exc_info:
- await create_workspace_link(mock_request, link_data)
- assert exc_info.value.status_code == 500
- assert 'Failed to register user' in exc_info.value.detail
-
-
-# Test linear_callback error scenarios
-@patch('server.routes.integration.linear.redis_client')
-async def test_linear_callback_no_session(mock_redis, mock_request):
- mock_redis.get.return_value = None
-
- with pytest.raises(HTTPException) as exc_info:
- await linear_callback(mock_request, 'code', 'state')
- assert exc_info.value.status_code == 400
- assert 'No active integration session found' in exc_info.value.detail
-
-
-@patch('server.routes.integration.linear.redis_client')
-async def test_linear_callback_state_mismatch(mock_redis, mock_request):
- session_data = {'state': 'different_state'}
- mock_redis.get.return_value = json.dumps(session_data)
-
- with pytest.raises(HTTPException) as exc_info:
- await linear_callback(mock_request, 'code', 'wrong_state')
- assert exc_info.value.status_code == 400
- assert 'State mismatch. Possible CSRF attack' in exc_info.value.detail
-
-
-@patch('server.routes.integration.linear.redis_client')
-@patch('requests.post')
-async def test_linear_callback_token_fetch_failure(mock_post, mock_redis, mock_request):
- session_data = {'state': 'test_state'}
- mock_redis.get.return_value = json.dumps(session_data)
- mock_post.return_value = MagicMock(status_code=400, text='Token error')
-
- with pytest.raises(HTTPException) as exc_info:
- await linear_callback(mock_request, 'code', 'test_state')
- assert exc_info.value.status_code == 400
- assert 'Error fetching token' in exc_info.value.detail
-
-
-@patch('server.routes.integration.linear.redis_client')
-@patch('requests.post')
-async def test_linear_callback_workspace_fetch_failure(
- mock_post, mock_redis, mock_request
-):
- session_data = {'state': 'test_state'}
- mock_redis.get.return_value = json.dumps(session_data)
- mock_post.side_effect = [
- MagicMock(status_code=200, json=lambda: {'access_token': 'token'}),
- MagicMock(status_code=400, text='Workspace error'),
- ]
-
- with pytest.raises(HTTPException) as exc_info:
- await linear_callback(mock_request, 'code', 'test_state')
- assert exc_info.value.status_code == 400
- assert 'Error fetching workspace' in exc_info.value.detail
-
-
-@patch('server.routes.integration.linear.redis_client')
-@patch('requests.post')
-async def test_linear_callback_unauthorized_workspace(
- mock_post, mock_redis, mock_request
-):
- session_data = {'state': 'test_state', 'target_workspace': 'target-workspace'}
- mock_redis.get.return_value = json.dumps(session_data)
- mock_post.side_effect = [
- MagicMock(status_code=200, json=lambda: {'access_token': 'token'}),
- MagicMock(
- status_code=200,
- json=lambda: {
- 'data': {'viewer': {'organization': {'urlKey': 'different-workspace'}}}
- },
- ),
- ]
-
- with pytest.raises(HTTPException) as exc_info:
- await linear_callback(mock_request, 'code', 'test_state')
- assert exc_info.value.status_code == 401
- assert 'User is not authorized to access workspace' in exc_info.value.detail
-
-
-@patch('server.routes.integration.linear.redis_client')
-@patch('requests.post')
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-@patch(
- 'server.routes.integration.linear._handle_workspace_link_creation',
- new_callable=AsyncMock,
-)
-async def test_linear_callback_workspace_integration_existing_workspace(
- mock_handle_link, mock_manager, mock_post, mock_redis, mock_request
-):
- state = 'test_state'
- session_data = {
- 'operation_type': 'workspace_integration',
- 'keycloak_user_id': 'user1',
- 'target_workspace': 'existing-space',
- 'webhook_secret': 'secret',
- 'svc_acc_email': '[email protected]',
- 'svc_acc_api_key': 'apikey',
- 'is_active': True,
- 'state': state,
- }
- mock_redis.get.return_value = json.dumps(session_data)
- mock_post.side_effect = [
- MagicMock(status_code=200, json=lambda: {'access_token': 'token'}),
- MagicMock(
- status_code=200,
- json=lambda: {
- 'data': {'viewer': {'organization': {'urlKey': 'existing-space'}}}
- },
- ),
- ]
-
- # Mock existing workspace
- mock_workspace = MagicMock(id=1)
- mock_manager.integration_store.get_workspace_by_name.return_value = mock_workspace
-
- with patch('server.routes.integration.linear.token_manager') as mock_token_manager:
- with patch(
- 'server.routes.integration.linear._validate_workspace_update_permissions'
- ) as mock_validate:
- mock_validate.return_value = mock_workspace
- mock_token_manager.encrypt_text.side_effect = lambda x: f'enc_{x}'
-
- response = await linear_callback(mock_request, 'code', state)
-
- assert isinstance(response, RedirectResponse)
- assert response.status_code == status.HTTP_302_FOUND
- mock_manager.integration_store.update_workspace.assert_called_once()
- mock_handle_link.assert_called_once_with('user1', None, 'existing-space')
-
-
-@patch('server.routes.integration.linear.redis_client')
-@patch('requests.post')
-async def test_linear_callback_invalid_operation_type(
- mock_post, mock_redis, mock_request
-):
- session_data = {
- 'operation_type': 'invalid_operation',
- 'target_workspace': 'test-workspace',
- 'keycloak_user_id': 'user1', # Add missing field
- 'state': 'test_state',
- }
- mock_redis.get.return_value = json.dumps(session_data)
- mock_post.side_effect = [
- MagicMock(status_code=200, json=lambda: {'access_token': 'token'}),
- MagicMock(
- status_code=200,
- json=lambda: {
- 'data': {'viewer': {'organization': {'urlKey': 'test-workspace'}}}
- },
- ),
- ]
-
- with pytest.raises(HTTPException) as exc_info:
- await linear_callback(mock_request, 'code', 'test_state')
- assert exc_info.value.status_code == 400
- assert 'Invalid operation type' in exc_info.value.detail
-
-
-# Test get_current_workspace_link error scenarios
-@patch('server.routes.integration.linear.get_user_auth')
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_get_current_workspace_link_user_not_found(
- mock_manager, mock_get_auth, mock_request, mock_user_auth
-):
- mock_get_auth.return_value = mock_user_auth
- mock_manager.integration_store.get_user_by_active_workspace.return_value = None
-
- with pytest.raises(HTTPException) as exc_info:
- await get_current_workspace_link(mock_request)
- assert exc_info.value.status_code == 404
- assert 'User is not registered for Linear integration' in exc_info.value.detail
-
-
-@patch('server.routes.integration.linear.get_user_auth')
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_get_current_workspace_link_workspace_not_found(
- mock_manager, mock_get_auth, mock_request, mock_user_auth
-):
- mock_get_auth.return_value = mock_user_auth
- mock_user = MagicMock(linear_workspace_id=10)
- mock_manager.integration_store.get_user_by_active_workspace.return_value = mock_user
- mock_manager.integration_store.get_workspace_by_id.return_value = None
-
- with pytest.raises(HTTPException) as exc_info:
- await get_current_workspace_link(mock_request)
- assert exc_info.value.status_code == 404
- assert 'Workspace not found for the user' in exc_info.value.detail
-
-
-@patch('server.routes.integration.linear.get_user_auth')
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_get_current_workspace_link_not_editable(
- mock_manager, mock_get_auth, mock_request, mock_user_auth
-):
- mock_get_auth.return_value = mock_user_auth
- user_id = 'test_user_id'
- different_admin = 'different_admin'
-
- mock_user = MagicMock(
- id=1,
- keycloak_user_id=user_id,
- linear_workspace_id=10,
- status='active',
- created_at=datetime.now(),
- updated_at=datetime.now(),
- )
-
- mock_workspace = MagicMock(
- id=10,
- status='active',
- admin_user_id=different_admin,
- created_at=datetime.now(),
- updated_at=datetime.now(),
- linear_org_id='test-org-id',
- svc_acc_email='[email protected]',
- svc_acc_api_key='encrypted-key',
- )
- # Fix the name attribute to be a string instead of MagicMock
- mock_workspace.name = 'test-space'
-
- mock_manager.integration_store.get_user_by_active_workspace.return_value = mock_user
- mock_manager.integration_store.get_workspace_by_id.return_value = mock_workspace
-
- response = await get_current_workspace_link(mock_request)
- assert response.workspace.editable is False
-
-
-@patch('server.routes.integration.linear.get_user_auth')
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_get_current_workspace_link_unexpected_error(
- mock_manager, mock_get_auth, mock_request, mock_user_auth
-):
- mock_get_auth.return_value = mock_user_auth
- mock_manager.integration_store.get_user_by_active_workspace.side_effect = Exception(
- 'DB error'
- )
-
- with pytest.raises(HTTPException) as exc_info:
- await get_current_workspace_link(mock_request)
- assert exc_info.value.status_code == 500
- assert 'Failed to retrieve user' in exc_info.value.detail
-
-
-# Test unlink_workspace error scenarios
-@patch('server.routes.integration.linear.get_user_auth')
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_unlink_workspace_user_not_found(
- mock_manager, mock_get_auth, mock_request, mock_user_auth
-):
- mock_get_auth.return_value = mock_user_auth
- mock_manager.integration_store.get_user_by_active_workspace.return_value = None
-
- with pytest.raises(HTTPException) as exc_info:
- await unlink_workspace(mock_request)
- assert exc_info.value.status_code == 404
- assert 'User is not registered for Linear integration' in exc_info.value.detail
-
-
-@patch('server.routes.integration.linear.get_user_auth')
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_unlink_workspace_workspace_not_found(
- mock_manager, mock_get_auth, mock_request, mock_user_auth
-):
- mock_get_auth.return_value = mock_user_auth
- mock_user = MagicMock(linear_workspace_id=10)
- mock_manager.integration_store.get_user_by_active_workspace.return_value = mock_user
- mock_manager.integration_store.get_workspace_by_id.return_value = None
-
- with pytest.raises(HTTPException) as exc_info:
- await unlink_workspace(mock_request)
- assert exc_info.value.status_code == 404
- assert 'Workspace not found for the user' in exc_info.value.detail
-
-
-@patch('server.routes.integration.linear.get_user_auth')
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_unlink_workspace_non_admin(
- mock_manager, mock_get_auth, mock_request, mock_user_auth
-):
- mock_get_auth.return_value = mock_user_auth
- user_id = 'test_user_id'
- mock_user = MagicMock(linear_workspace_id=10)
- mock_workspace = MagicMock(id=10, admin_user_id='different_admin')
- mock_manager.integration_store.get_user_by_active_workspace.return_value = mock_user
- mock_manager.integration_store.get_workspace_by_id.return_value = mock_workspace
-
- response = await unlink_workspace(mock_request)
- content = json.loads(response.body)
- assert content['success'] is True
- mock_manager.integration_store.update_user_integration_status.assert_called_once_with(
- user_id, 'inactive'
- )
-
-
-@patch('server.routes.integration.linear.get_user_auth')
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_unlink_workspace_unexpected_error(
- mock_manager, mock_get_auth, mock_request, mock_user_auth
-):
- mock_get_auth.return_value = mock_user_auth
- mock_manager.integration_store.get_user_by_active_workspace.side_effect = Exception(
- 'DB error'
- )
-
- with pytest.raises(HTTPException) as exc_info:
- await unlink_workspace(mock_request)
- assert exc_info.value.status_code == 500
- assert 'Failed to unlink user' in exc_info.value.detail
-
-
-# Test validate_workspace_integration error scenarios
-@patch('server.routes.integration.linear.get_user_auth')
-async def test_validate_workspace_integration_invalid_name(
- mock_get_auth, mock_request, mock_user_auth
-):
- mock_get_auth.return_value = mock_user_auth
-
- with pytest.raises(HTTPException) as exc_info:
- await validate_workspace_integration(mock_request, 'invalid workspace!')
- assert exc_info.value.status_code == 400
- assert (
- 'workspace_name can only contain alphanumeric characters'
- in exc_info.value.detail
- )
-
-
-@patch('server.routes.integration.linear.get_user_auth')
-async def test_validate_workspace_integration_no_email(
- mock_get_auth, mock_request, mock_user_auth
-):
- mock_user_auth.get_user_email.return_value = None
- mock_get_auth.return_value = mock_user_auth
-
- with pytest.raises(HTTPException) as exc_info:
- await validate_workspace_integration(mock_request, 'test-workspace')
- assert exc_info.value.status_code == 400
- assert 'Unable to retrieve user email' in exc_info.value.detail
-
-
-@patch('server.routes.integration.linear.get_user_auth')
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_validate_workspace_integration_workspace_not_found(
- mock_manager, mock_get_auth, mock_request, mock_user_auth
-):
- mock_get_auth.return_value = mock_user_auth
- mock_manager.integration_store.get_workspace_by_name.return_value = None
-
- with pytest.raises(HTTPException) as exc_info:
- await validate_workspace_integration(mock_request, 'nonexistent-workspace')
- assert exc_info.value.status_code == 404
- assert (
- "Workspace with name 'nonexistent-workspace' not found" in exc_info.value.detail
- )
-
-
-@patch('server.routes.integration.linear.get_user_auth')
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_validate_workspace_integration_inactive_workspace(
- mock_manager, mock_get_auth, mock_request, mock_user_auth
-):
- mock_get_auth.return_value = mock_user_auth
- mock_workspace = MagicMock(status='inactive')
- # Fix the name attribute to be a string instead of MagicMock
- mock_workspace.name = 'test-workspace'
- mock_manager.integration_store.get_workspace_by_name.return_value = mock_workspace
-
- with pytest.raises(HTTPException) as exc_info:
- await validate_workspace_integration(mock_request, 'test-workspace')
- assert exc_info.value.status_code == 404
- assert "Workspace 'test-workspace' is not active" in exc_info.value.detail
-
-
-@patch('server.routes.integration.linear.get_user_auth')
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_validate_workspace_integration_unexpected_error(
- mock_manager, mock_get_auth, mock_request, mock_user_auth
-):
- mock_get_auth.return_value = mock_user_auth
- mock_manager.integration_store.get_workspace_by_name.side_effect = Exception(
- 'DB error'
- )
-
- with pytest.raises(HTTPException) as exc_info:
- await validate_workspace_integration(mock_request, 'test-workspace')
- assert exc_info.value.status_code == 500
- assert 'Failed to validate workspace' in exc_info.value.detail
-
-
-# Test helper functions
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_handle_workspace_link_creation_workspace_not_found(mock_manager):
- mock_manager.integration_store.get_workspace_by_name.return_value = None
-
- with pytest.raises(HTTPException) as exc_info:
- await _handle_workspace_link_creation(
- 'user1', 'linear_user_123', 'nonexistent-workspace'
- )
- assert exc_info.value.status_code == 404
- assert 'Workspace "nonexistent-workspace" not found' in exc_info.value.detail
-
-
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_handle_workspace_link_creation_inactive_workspace(mock_manager):
- mock_workspace = MagicMock(status='inactive')
- mock_manager.integration_store.get_workspace_by_name.return_value = mock_workspace
-
- with pytest.raises(HTTPException) as exc_info:
- await _handle_workspace_link_creation(
- 'user1', 'linear_user_123', 'inactive-workspace'
- )
- assert exc_info.value.status_code == 400
- assert 'Workspace "inactive-workspace" is not active' in exc_info.value.detail
-
-
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_handle_workspace_link_creation_already_linked_same_workspace(
- mock_manager,
-):
- mock_workspace = MagicMock(id=1, status='active')
- mock_existing_user = MagicMock(linear_workspace_id=1)
-
- mock_manager.integration_store.get_workspace_by_name.return_value = mock_workspace
- mock_manager.integration_store.get_user_by_active_workspace.return_value = (
- mock_existing_user
- )
-
- # Should not raise exception and should not create new link
- await _handle_workspace_link_creation('user1', 'linear_user_123', 'test-workspace')
-
- mock_manager.integration_store.create_workspace_link.assert_not_called()
- mock_manager.integration_store.update_user_integration_status.assert_not_called()
-
-
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_handle_workspace_link_creation_already_linked_different_workspace(
- mock_manager,
-):
- mock_workspace = MagicMock(id=2, status='active')
- mock_existing_user = MagicMock(linear_workspace_id=1) # Different workspace
-
- mock_manager.integration_store.get_workspace_by_name.return_value = mock_workspace
- mock_manager.integration_store.get_user_by_active_workspace.return_value = (
- mock_existing_user
- )
-
- with pytest.raises(HTTPException) as exc_info:
- await _handle_workspace_link_creation(
- 'user1', 'linear_user_123', 'test-workspace'
- )
- assert exc_info.value.status_code == 400
- assert 'You already have an active workspace link' in exc_info.value.detail
-
-
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_handle_workspace_link_creation_reactivate_existing_link(mock_manager):
- mock_workspace = MagicMock(id=1, status='active')
- mock_existing_link = MagicMock()
-
- mock_manager.integration_store.get_workspace_by_name.return_value = mock_workspace
- mock_manager.integration_store.get_user_by_active_workspace.return_value = None
- mock_manager.integration_store.get_user_by_keycloak_id_and_workspace.return_value = mock_existing_link
-
- await _handle_workspace_link_creation('user1', 'linear_user_123', 'test-workspace')
-
- mock_manager.integration_store.update_user_integration_status.assert_called_once_with(
- 'user1', 'active'
- )
- mock_manager.integration_store.create_workspace_link.assert_not_called()
-
-
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_handle_workspace_link_creation_create_new_link(mock_manager):
- mock_workspace = MagicMock(id=1, status='active')
-
- mock_manager.integration_store.get_workspace_by_name.return_value = mock_workspace
- mock_manager.integration_store.get_user_by_active_workspace.return_value = None
- mock_manager.integration_store.get_user_by_keycloak_id_and_workspace.return_value = None
-
- await _handle_workspace_link_creation('user1', 'linear_user_123', 'test-workspace')
-
- mock_manager.integration_store.create_workspace_link.assert_called_once_with(
- keycloak_user_id='user1',
- linear_user_id='linear_user_123',
- linear_workspace_id=1,
- )
- mock_manager.integration_store.update_user_integration_status.assert_not_called()
-
-
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_validate_workspace_update_permissions_workspace_not_found(mock_manager):
- mock_manager.integration_store.get_workspace_by_name.return_value = None
-
- with pytest.raises(HTTPException) as exc_info:
- await _validate_workspace_update_permissions('user1', 'nonexistent-workspace')
- assert exc_info.value.status_code == 404
- assert 'Workspace "nonexistent-workspace" not found' in exc_info.value.detail
-
-
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_validate_workspace_update_permissions_not_admin(mock_manager):
- mock_workspace = MagicMock(admin_user_id='different_user')
- mock_manager.integration_store.get_workspace_by_name.return_value = mock_workspace
-
- with pytest.raises(HTTPException) as exc_info:
- await _validate_workspace_update_permissions('user1', 'test-workspace')
- assert exc_info.value.status_code == 403
- assert (
- 'You do not have permission to update this workspace' in exc_info.value.detail
- )
-
-
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_validate_workspace_update_permissions_wrong_linked_workspace(
- mock_manager,
-):
- mock_workspace = MagicMock(id=1, admin_user_id='user1')
- mock_user_link = MagicMock(linear_workspace_id=2) # Different workspace
-
- mock_manager.integration_store.get_workspace_by_name.return_value = mock_workspace
- mock_manager.integration_store.get_user_by_active_workspace.return_value = (
- mock_user_link
- )
-
- with pytest.raises(HTTPException) as exc_info:
- await _validate_workspace_update_permissions('user1', 'test-workspace')
- assert exc_info.value.status_code == 403
- assert (
- 'You can only update the workspace you are currently linked to'
- in exc_info.value.detail
- )
-
-
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_validate_workspace_update_permissions_success(mock_manager):
- mock_workspace = MagicMock(id=1, admin_user_id='user1')
- mock_user_link = MagicMock(linear_workspace_id=1)
-
- mock_manager.integration_store.get_workspace_by_name.return_value = mock_workspace
- mock_manager.integration_store.get_user_by_active_workspace.return_value = (
- mock_user_link
- )
-
- result = await _validate_workspace_update_permissions('user1', 'test-workspace')
- assert result == mock_workspace
-
-
-@patch('server.routes.integration.linear.linear_manager', new_callable=AsyncMock)
-async def test_validate_workspace_update_permissions_no_current_link(mock_manager):
- mock_workspace = MagicMock(id=1, admin_user_id='user1')
-
- mock_manager.integration_store.get_workspace_by_name.return_value = mock_workspace
- mock_manager.integration_store.get_user_by_active_workspace.return_value = None
-
- result = await _validate_workspace_update_permissions('user1', 'test-workspace')
- assert result == mock_workspace
diff --git a/enterprise/tests/unit/server/test_event_webhook.py b/enterprise/tests/unit/server/test_event_webhook.py
deleted file mode 100644
index eba2c44af0..0000000000
--- a/enterprise/tests/unit/server/test_event_webhook.py
+++ /dev/null
@@ -1,728 +0,0 @@
-"""Unit tests for event_webhook.py"""
-
-import json
-from datetime import datetime
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pytest
-from fastapi import BackgroundTasks, HTTPException, Request, status
-from server.routes.event_webhook import (
- BatchMethod,
- BatchOperation,
- _get_session_api_key,
- _get_user_id,
- _parse_conversation_id_and_subpath,
- _process_batch_operations_background,
- on_batch_write,
- on_delete,
- on_write,
-)
-from server.utils.conversation_callback_utils import (
- process_event,
- update_conversation_metadata,
-)
-from storage.stored_conversation_metadata import StoredConversationMetadata
-
-from openhands.events.observation.agent import AgentStateChangedObservation
-
-
-class TestParseConversationIdAndSubpath:
- """Test the _parse_conversation_id_and_subpath function."""
-
- def test_valid_path_with_metadata(self):
- """Test parsing a valid path with metadata.json."""
- path = 'sessions/conv-123/metadata.json'
- conversation_id, subpath = _parse_conversation_id_and_subpath(path)
- assert conversation_id == 'conv-123'
- assert subpath == 'metadata.json'
-
- def test_valid_path_with_events(self):
- """Test parsing a valid path with events."""
- path = 'sessions/conv-456/events/event-1.json'
- conversation_id, subpath = _parse_conversation_id_and_subpath(path)
- assert conversation_id == 'conv-456'
- assert subpath == 'events/event-1.json'
-
- def test_valid_path_with_nested_subpath(self):
- """Test parsing a valid path with nested subpath."""
- path = 'sessions/conv-789/events/subfolder/event.json'
- conversation_id, subpath = _parse_conversation_id_and_subpath(path)
- assert conversation_id == 'conv-789'
- assert subpath == 'events/subfolder/event.json'
-
- def test_invalid_path_missing_sessions(self):
- """Test parsing an invalid path that doesn't start with 'sessions'."""
- path = 'invalid/conv-123/metadata.json'
- with pytest.raises(HTTPException) as exc_info:
- _parse_conversation_id_and_subpath(path)
- assert exc_info.value.status_code == status.HTTP_400_BAD_REQUEST
-
- def test_invalid_path_too_short(self):
- """Test parsing an invalid path that's too short."""
- path = 'sessions'
- with pytest.raises(HTTPException) as exc_info:
- _parse_conversation_id_and_subpath(path)
- assert exc_info.value.status_code == status.HTTP_400_BAD_REQUEST
-
- def test_invalid_path_empty_conversation_id(self):
- """Test parsing a path with empty conversation ID."""
- path = 'sessions//metadata.json'
- conversation_id, subpath = _parse_conversation_id_and_subpath(path)
- assert conversation_id == ''
- assert subpath == 'metadata.json'
-
-
-class TestGetUserId:
- """Test the _get_user_id function."""
-
- def test_get_user_id_success(self, session_maker_with_minimal_fixtures):
- """Test successfully getting user ID."""
- with patch(
- 'server.routes.event_webhook.session_maker',
- session_maker_with_minimal_fixtures,
- ):
- user_id = _get_user_id('mock-conversation-id')
- assert user_id == '5594c7b6-f959-4b81-92e9-b09c206f5081'
-
- def test_get_user_id_conversation_not_found(self, session_maker):
- """Test getting user ID when conversation doesn't exist."""
- with patch('server.routes.event_webhook.session_maker', session_maker):
- with pytest.raises(AttributeError):
- _get_user_id('nonexistent-conversation-id')
-
-
-class TestGetSessionApiKey:
- """Test the _get_session_api_key function."""
-
- @pytest.mark.asyncio
- async def test_get_session_api_key_success(self):
- """Test successfully getting session API key."""
- mock_agent_loop_info = MagicMock()
- mock_agent_loop_info.session_api_key = 'test-api-key'
-
- with patch('server.routes.event_webhook.conversation_manager') as mock_manager:
- mock_manager.get_agent_loop_info = AsyncMock(
- return_value=[mock_agent_loop_info]
- )
-
- api_key = await _get_session_api_key(
- '5594c7b6-f959-4b81-92e9-b09c206f5081', 'conv-456'
- )
- assert api_key == 'test-api-key'
- mock_manager.get_agent_loop_info.assert_called_once_with(
- '5594c7b6-f959-4b81-92e9-b09c206f5081', filter_to_sids={'conv-456'}
- )
-
- @pytest.mark.asyncio
- async def test_get_session_api_key_no_results(self):
- """Test getting session API key when no agent loop info is found."""
- with patch('server.routes.event_webhook.conversation_manager') as mock_manager:
- mock_manager.get_agent_loop_info = AsyncMock(return_value=[])
-
- with pytest.raises(IndexError):
- await _get_session_api_key(
- '5594c7b6-f959-4b81-92e9-b09c206f5081', 'conv-456'
- )
-
-
-class TestProcessEvent:
- """Test the process_event function."""
-
- @pytest.mark.asyncio
- async def test_process_event_regular_event(
- self, session_maker_with_minimal_fixtures
- ):
- """Test processing a regular event."""
- content = {'type': 'action', 'action': 'run', 'args': {'command': 'ls'}}
-
- with patch(
- 'server.utils.conversation_callback_utils.file_store'
- ) as mock_file_store, patch(
- 'server.utils.conversation_callback_utils.event_from_dict'
- ) as mock_event_from_dict, patch(
- 'server.utils.conversation_callback_utils.session_maker',
- session_maker_with_minimal_fixtures,
- ):
- mock_event = MagicMock()
- mock_event_from_dict.return_value = mock_event
-
- await process_event(
- '5594c7b6-f959-4b81-92e9-b09c206f5081',
- 'conv-456',
- 'events/event-1.json',
- content,
- )
-
- mock_file_store.write.assert_called_once_with(
- 'users/5594c7b6-f959-4b81-92e9-b09c206f5081/conversations/conv-456/events/event-1.json',
- json.dumps(content),
- )
- mock_event_from_dict.assert_called_once_with(content)
-
- @pytest.mark.asyncio
- async def test_process_event_agent_state_changed(
- self, session_maker_with_minimal_fixtures
- ):
- """Test processing an AgentStateChangedObservation event."""
- content = {'type': 'observation', 'observation': 'agent_state_changed'}
-
- with patch(
- 'server.utils.conversation_callback_utils.file_store'
- ) as mock_file_store, patch(
- 'server.utils.conversation_callback_utils.event_from_dict'
- ) as mock_event_from_dict, patch(
- 'server.utils.conversation_callback_utils.session_maker',
- session_maker_with_minimal_fixtures,
- ), patch(
- 'server.utils.conversation_callback_utils.invoke_conversation_callbacks'
- ) as mock_invoke_callbacks, patch(
- 'server.utils.conversation_callback_utils.update_active_working_seconds'
- ) as mock_update_working_seconds, patch(
- 'server.utils.conversation_callback_utils.EventStore'
- ) as mock_event_store_class:
- mock_event = MagicMock(spec=AgentStateChangedObservation)
- mock_event.agent_state = (
- 'stopped' # Set a non-RUNNING state to trigger the update
- )
- mock_event_from_dict.return_value = mock_event
-
- await process_event(
- '5594c7b6-f959-4b81-92e9-b09c206f5081',
- 'conv-456',
- 'events/event-1.json',
- content,
- )
-
- mock_file_store.write.assert_called_once()
- mock_event_from_dict.assert_called_once_with(content)
- mock_invoke_callbacks.assert_called_once_with('conv-456', mock_event)
- mock_update_working_seconds.assert_called_once()
- mock_event_store_class.assert_called_once_with(
- 'conv-456', mock_file_store, '5594c7b6-f959-4b81-92e9-b09c206f5081'
- )
-
- @pytest.mark.asyncio
- async def test_process_event_agent_state_changed_running(
- self, session_maker_with_minimal_fixtures
- ):
- """Test processing an AgentStateChangedObservation event with RUNNING state."""
- content = {'type': 'observation', 'observation': 'agent_state_changed'}
-
- with patch(
- 'server.utils.conversation_callback_utils.file_store'
- ) as mock_file_store, patch(
- 'server.utils.conversation_callback_utils.event_from_dict'
- ) as mock_event_from_dict, patch(
- 'server.utils.conversation_callback_utils.session_maker',
- session_maker_with_minimal_fixtures,
- ), patch(
- 'server.utils.conversation_callback_utils.invoke_conversation_callbacks'
- ) as mock_invoke_callbacks, patch(
- 'server.utils.conversation_callback_utils.update_active_working_seconds'
- ) as mock_update_working_seconds, patch(
- 'server.utils.conversation_callback_utils.EventStore'
- ) as mock_event_store_class:
- mock_event = MagicMock(spec=AgentStateChangedObservation)
- mock_event.agent_state = 'running' # Set RUNNING state to skip the update
- mock_event_from_dict.return_value = mock_event
-
- await process_event(
- '5594c7b6-f959-4b81-92e9-b09c206f5081',
- 'conv-456',
- 'events/event-1.json',
- content,
- )
-
- mock_file_store.write.assert_called_once()
- mock_event_from_dict.assert_called_once_with(content)
- mock_invoke_callbacks.assert_called_once_with('conv-456', mock_event)
- # update_active_working_seconds should NOT be called when agent is RUNNING
- mock_update_working_seconds.assert_not_called()
- mock_event_store_class.assert_not_called()
-
-
-class TestUpdateConversationMetadata:
- """Test the _update_conversation_metadata function."""
-
- def test_update_conversation_metadata_all_fields(
- self, session_maker_with_minimal_fixtures
- ):
- """Test updating conversation metadata with all fields."""
- content = {
- 'accumulated_cost': 10.50,
- 'prompt_tokens': 1000,
- 'completion_tokens': 500,
- 'total_tokens': 1500,
- }
-
- with patch(
- 'server.utils.conversation_callback_utils.session_maker',
- session_maker_with_minimal_fixtures,
- ):
- update_conversation_metadata('mock-conversation-id', content)
-
- # Verify the conversation was updated
- with session_maker_with_minimal_fixtures() as session:
- conversation = (
- session.query(StoredConversationMetadata)
- .filter(
- StoredConversationMetadata.conversation_id
- == 'mock-conversation-id'
- )
- .first()
- )
- assert conversation.accumulated_cost == 10.50
- assert conversation.prompt_tokens == 1000
- assert conversation.completion_tokens == 500
- assert conversation.total_tokens == 1500
- assert isinstance(conversation.last_updated_at, datetime)
-
- def test_update_conversation_metadata_partial_fields(
- self, session_maker_with_minimal_fixtures
- ):
- """Test updating conversation metadata with only some fields."""
- content = {'accumulated_cost': 15.75, 'prompt_tokens': 2000}
-
- with patch(
- 'server.utils.conversation_callback_utils.session_maker',
- session_maker_with_minimal_fixtures,
- ):
- update_conversation_metadata('mock-conversation-id', content)
-
- # Verify only specified fields were updated, others remain unchanged
- with session_maker_with_minimal_fixtures() as session:
- conversation = (
- session.query(StoredConversationMetadata)
- .filter(
- StoredConversationMetadata.conversation_id
- == 'mock-conversation-id'
- )
- .first()
- )
- assert conversation.accumulated_cost == 15.75
- assert conversation.prompt_tokens == 2000
- # These should remain as original values from fixtures
- assert conversation.completion_tokens == 250
- assert conversation.total_tokens == 750
-
- def test_update_conversation_metadata_empty_content(
- self, session_maker_with_minimal_fixtures
- ):
- """Test updating conversation metadata with empty content."""
- content: dict[str, float] = {}
-
- with patch(
- 'server.utils.conversation_callback_utils.session_maker',
- session_maker_with_minimal_fixtures,
- ):
- update_conversation_metadata('mock-conversation-id', content)
-
- # Verify only last_updated_at was changed
- with session_maker_with_minimal_fixtures() as session:
- conversation = (
- session.query(StoredConversationMetadata)
- .filter(
- StoredConversationMetadata.conversation_id
- == 'mock-conversation-id'
- )
- .first()
- )
- # Original values should remain unchanged
- assert conversation.accumulated_cost == 5.25
- assert conversation.prompt_tokens == 500
- assert conversation.completion_tokens == 250
- assert conversation.total_tokens == 750
- assert isinstance(conversation.last_updated_at, datetime)
-
-
-class TestOnDelete:
- """Test the on_delete endpoint."""
-
- @pytest.mark.asyncio
- async def test_on_delete_returns_ok(self):
- """Test that on_delete always returns 200 OK."""
- result = await on_delete('any/path', 'any-api-key')
- assert result.status_code == status.HTTP_200_OK
-
-
-class TestOnWrite:
- """Test the on_write endpoint."""
-
- @pytest.fixture
- def mock_request(self):
- """Create a mock request object."""
- request = MagicMock(spec=Request)
- request.json = AsyncMock(return_value={'test': 'data'})
- return request
-
- @pytest.mark.asyncio
- async def test_on_write_metadata_success(
- self, mock_request, session_maker_with_minimal_fixtures
- ):
- """Test successful metadata update."""
- content = {'accumulated_cost': 20.0}
- mock_request.json.return_value = content
-
- with patch(
- 'server.routes.event_webhook.session_maker',
- session_maker_with_minimal_fixtures,
- ), patch(
- 'server.utils.conversation_callback_utils.session_maker',
- session_maker_with_minimal_fixtures,
- ), patch(
- 'server.routes.event_webhook._get_session_api_key'
- ) as mock_get_api_key:
- mock_get_api_key.return_value = 'correct-api-key'
-
- result = await on_write(
- 'sessions/mock-conversation-id/metadata.json',
- mock_request,
- 'correct-api-key',
- )
-
- assert result.status_code == status.HTTP_200_OK
-
- @pytest.mark.asyncio
- async def test_on_write_events_success(
- self, mock_request, session_maker_with_minimal_fixtures
- ):
- """Test successful event processing."""
- content = {'type': 'action', 'action': 'run'}
- mock_request.json.return_value = content
-
- with patch(
- 'server.routes.event_webhook.session_maker',
- session_maker_with_minimal_fixtures,
- ), patch(
- 'server.routes.event_webhook._get_session_api_key'
- ) as mock_get_api_key, patch(
- 'server.utils.conversation_callback_utils.file_store'
- ) as mock_file_store, patch(
- 'server.utils.conversation_callback_utils.event_from_dict'
- ) as mock_event_from_dict:
- mock_get_api_key.return_value = 'correct-api-key'
- mock_event_from_dict.return_value = MagicMock()
-
- result = await on_write(
- 'sessions/mock-conversation-id/events/event-1.json',
- mock_request,
- 'correct-api-key',
- )
-
- assert result.status_code == status.HTTP_200_OK
- mock_file_store.write.assert_called_once()
-
- @pytest.mark.asyncio
- async def test_on_write_invalid_api_key(
- self, mock_request, session_maker_with_minimal_fixtures
- ):
- """Test request with invalid API key."""
- with patch(
- 'server.routes.event_webhook.session_maker',
- session_maker_with_minimal_fixtures,
- ), patch(
- 'server.routes.event_webhook._get_session_api_key'
- ) as mock_get_api_key:
- mock_get_api_key.return_value = 'correct-api-key'
-
- result = await on_write(
- 'sessions/mock-conversation-id/metadata.json',
- mock_request,
- 'wrong-api-key',
- )
-
- assert result.status_code == status.HTTP_403_FORBIDDEN
-
- @pytest.mark.asyncio
- async def test_on_write_invalid_path(self, mock_request):
- """Test request with invalid path."""
- with pytest.raises(HTTPException) as excinfo:
- await on_write('invalid/path/format', mock_request, 'any-api-key')
- assert excinfo.value.status_code == status.HTTP_400_BAD_REQUEST
-
- @pytest.mark.asyncio
- async def test_on_write_unsupported_subpath(
- self, mock_request, session_maker_with_minimal_fixtures
- ):
- """Test request with unsupported subpath."""
- with patch(
- 'server.routes.event_webhook.session_maker',
- session_maker_with_minimal_fixtures,
- ), patch(
- 'server.routes.event_webhook._get_session_api_key'
- ) as mock_get_api_key:
- mock_get_api_key.return_value = 'correct-api-key'
-
- result = await on_write(
- 'sessions/mock-conversation-id/unsupported.json',
- mock_request,
- 'correct-api-key',
- )
-
- assert result.status_code == status.HTTP_400_BAD_REQUEST
-
- @pytest.mark.asyncio
- async def test_on_write_invalid_json(self, session_maker_with_minimal_fixtures):
- """Test request with invalid JSON."""
- mock_request = MagicMock(spec=Request)
- mock_request.json = AsyncMock(side_effect=ValueError('Invalid JSON'))
-
- with patch(
- 'server.routes.event_webhook.session_maker',
- session_maker_with_minimal_fixtures,
- ), patch(
- 'server.routes.event_webhook._get_session_api_key'
- ) as mock_get_api_key:
- mock_get_api_key.return_value = 'correct-api-key'
-
- result = await on_write(
- 'sessions/mock-conversation-id/metadata.json',
- mock_request,
- 'correct-api-key',
- )
-
- assert result.status_code == status.HTTP_400_BAD_REQUEST
-
-
-class TestBatchOperation:
- """Test the BatchOperation model."""
-
- def test_batch_operation_get_content_utf8(self):
- """Test getting content as UTF-8 bytes."""
- op = BatchOperation(
- method=BatchMethod.POST,
- path='sessions/test/metadata.json',
- content='{"test": "data"}',
- encoding=None,
- )
- content = op.get_content()
- assert content == b'{"test": "data"}'
-
- def test_batch_operation_get_content_base64(self):
- """Test getting content from base64 encoding."""
- import base64
-
- original_content = '{"test": "data"}'
- encoded_content = base64.b64encode(original_content.encode('utf-8')).decode(
- 'ascii'
- )
-
- op = BatchOperation(
- method=BatchMethod.POST,
- path='sessions/test/metadata.json',
- content=encoded_content,
- encoding='base64',
- )
- content = op.get_content()
- assert content == original_content.encode('utf-8')
-
- def test_batch_operation_get_content_json(self):
- """Test getting content as JSON."""
- op = BatchOperation(
- method=BatchMethod.POST,
- path='sessions/test/metadata.json',
- content='{"test": "data", "number": 42}',
- encoding=None,
- )
- json_content = op.get_content_json()
- assert json_content == {'test': 'data', 'number': 42}
-
- def test_batch_operation_get_content_empty_raises_error(self):
- """Test that empty content raises ValueError."""
- op = BatchOperation(
- method=BatchMethod.POST,
- path='sessions/test/metadata.json',
- content=None,
- encoding=None,
- )
- with pytest.raises(ValueError, match='empty_content_in_batch'):
- op.get_content()
-
-
-class TestOnBatchWrite:
- """Test the on_batch_write endpoint."""
-
- @pytest.mark.asyncio
- async def test_on_batch_write_returns_accepted(self):
- """Test that on_batch_write returns 202 ACCEPTED and queues background task."""
- batch_ops = [
- BatchOperation(
- method=BatchMethod.POST,
- path='sessions/test-conv/metadata.json',
- content='{"test": "data"}',
- )
- ]
-
- mock_background_tasks = MagicMock(spec=BackgroundTasks)
-
- result = await on_batch_write(
- batch_ops=batch_ops,
- background_tasks=mock_background_tasks,
- x_session_api_key='test-api-key',
- )
-
- # Should return 202 ACCEPTED immediately
- assert result.status_code == status.HTTP_202_ACCEPTED
-
- # Should have queued the background task
- mock_background_tasks.add_task.assert_called_once_with(
- _process_batch_operations_background,
- batch_ops,
- 'test-api-key',
- )
-
-
-class TestProcessBatchOperationsBackground:
- """Test the _process_batch_operations_background function."""
-
- @pytest.mark.asyncio
- async def test_process_batch_operations_metadata_success(
- self, session_maker_with_minimal_fixtures
- ):
- """Test successful processing of metadata batch operation."""
- batch_ops = [
- BatchOperation(
- method=BatchMethod.POST,
- path='sessions/mock-conversation-id/metadata.json',
- content='{"accumulated_cost": 15.0}',
- )
- ]
-
- with patch(
- 'server.routes.event_webhook.session_maker',
- session_maker_with_minimal_fixtures,
- ), patch(
- 'server.routes.event_webhook._get_session_api_key'
- ) as mock_get_api_key, patch(
- 'server.utils.conversation_callback_utils.session_maker',
- session_maker_with_minimal_fixtures,
- ):
- mock_get_api_key.return_value = 'correct-api-key'
-
- # Should not raise any exceptions
- await _process_batch_operations_background(batch_ops, 'correct-api-key')
-
- # Verify the conversation metadata was updated
- with session_maker_with_minimal_fixtures() as session:
- conversation = (
- session.query(StoredConversationMetadata)
- .filter(
- StoredConversationMetadata.conversation_id
- == 'mock-conversation-id'
- )
- .first()
- )
- assert conversation.accumulated_cost == 15.0
-
- @pytest.mark.asyncio
- async def test_process_batch_operations_events_success(
- self, session_maker_with_minimal_fixtures
- ):
- """Test successful processing of events batch operation."""
- batch_ops = [
- BatchOperation(
- method=BatchMethod.POST,
- path='sessions/mock-conversation-id/events/event-1.json',
- content='{"type": "action", "action": "run"}',
- )
- ]
-
- with patch(
- 'server.routes.event_webhook.session_maker',
- session_maker_with_minimal_fixtures,
- ), patch(
- 'server.routes.event_webhook._get_session_api_key'
- ) as mock_get_api_key, patch(
- 'server.utils.conversation_callback_utils.file_store'
- ) as mock_file_store, patch(
- 'server.utils.conversation_callback_utils.event_from_dict'
- ) as mock_event_from_dict:
- mock_get_api_key.return_value = 'correct-api-key'
- mock_event_from_dict.return_value = MagicMock()
-
- await _process_batch_operations_background(batch_ops, 'correct-api-key')
-
- # Verify file_store.write was called
- mock_file_store.write.assert_called_once()
-
- @pytest.mark.asyncio
- async def test_process_batch_operations_auth_failure_continues(
- self, session_maker_with_minimal_fixtures
- ):
- """Test that auth failure for one operation doesn't stop others."""
- batch_ops = [
- BatchOperation(
- method=BatchMethod.POST,
- path='sessions/conv-1/metadata.json',
- content='{"test": "data1"}',
- ),
- BatchOperation(
- method=BatchMethod.POST,
- path='sessions/conv-2/metadata.json',
- content='{"test": "data2"}',
- ),
- ]
-
- with patch(
- 'server.routes.event_webhook.session_maker',
- session_maker_with_minimal_fixtures,
- ), patch(
- 'server.routes.event_webhook._get_session_api_key'
- ) as mock_get_api_key, patch(
- 'server.utils.conversation_callback_utils.session_maker',
- session_maker_with_minimal_fixtures,
- ):
- # First call succeeds, second fails
- mock_get_api_key.side_effect = ['correct-api-key', 'wrong-api-key']
-
- # Should not raise exceptions, just log errors
- await _process_batch_operations_background(batch_ops, 'correct-api-key')
-
- @pytest.mark.asyncio
- async def test_process_batch_operations_invalid_method_skipped(
- self, session_maker_with_minimal_fixtures
- ):
- """Test that invalid methods are skipped with logging."""
- batch_ops = [
- BatchOperation(
- method=BatchMethod.DELETE, # Not supported
- path='sessions/mock-conversation-id/metadata.json',
- content='{"test": "data"}',
- )
- ]
-
- with patch('server.routes.event_webhook.logger') as mock_logger:
- await _process_batch_operations_background(batch_ops, 'test-api-key')
-
- # Should log the invalid operation
- mock_logger.info.assert_called_once_with(
- 'invalid_operation_in_batch_webhook',
- extra={
- 'method': 'BatchMethod.DELETE',
- 'path': 'sessions/mock-conversation-id/metadata.json',
- },
- )
-
- @pytest.mark.asyncio
- async def test_process_batch_operations_exception_handling(self):
- """Test that exceptions in individual operations are handled gracefully."""
- batch_ops = [
- BatchOperation(
- method=BatchMethod.POST,
- path='invalid-path', # This will cause an exception
- content='{"test": "data"}',
- )
- ]
-
- with patch('server.routes.event_webhook.logger') as mock_logger:
- # Should not raise exceptions
- await _process_batch_operations_background(batch_ops, 'test-api-key')
-
- # Should log the error with exception type and message in the log message
- mock_logger.error.assert_called_once()
- call_args = mock_logger.error.call_args
- log_message = call_args[0][0]
- assert log_message.startswith('error_processing_batch_operation:')
- assert call_args[1]['extra']['path'] == 'invalid-path'
- assert call_args[1]['extra']['method'] == 'BatchMethod.POST'
- assert call_args[1]['exc_info'] is True
diff --git a/enterprise/tests/unit/test_clustered_conversation_manager.py b/enterprise/tests/unit/test_clustered_conversation_manager.py
deleted file mode 100644
index 0503d360cf..0000000000
--- a/enterprise/tests/unit/test_clustered_conversation_manager.py
+++ /dev/null
@@ -1,740 +0,0 @@
-import asyncio
-import contextlib
-import json
-import time
-from dataclasses import dataclass
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pytest
-from server.clustered_conversation_manager import (
- ClusteredConversationManager,
-)
-
-from openhands.core.config.openhands_config import OpenHandsConfig
-from openhands.core.schema.agent import AgentState
-from openhands.server.monitoring import MonitoringListener
-from openhands.server.session.conversation_init_data import ConversationInitData
-from openhands.storage.memory import InMemoryFileStore
-
-
-@dataclass
-class GetMessageMock:
- message: dict | None
- sleep_time: float = 0.01
-
- async def get_message(self, **kwargs):
- await asyncio.sleep(self.sleep_time)
- return {'data': json.dumps(self.message)}
-
-
-class AsyncIteratorMock:
- def __init__(self, items):
- self.items = items
-
- def __aiter__(self):
- return self
-
- async def __anext__(self):
- if not self.items:
- raise StopAsyncIteration
- return self.items.pop(0)
-
-
-def get_mock_sio(get_message: GetMessageMock | None = None, scan_keys=None):
- sio = MagicMock()
- sio.enter_room = AsyncMock()
- sio.disconnect = AsyncMock() # Add mock for disconnect method
-
- # Create a Redis mock with all required methods
- redis_mock = MagicMock()
- redis_mock.publish = AsyncMock()
- redis_mock.get = AsyncMock(return_value=None)
- redis_mock.set = AsyncMock()
- redis_mock.delete = AsyncMock()
-
- # Create a pipeline mock
- pipeline_mock = MagicMock()
- pipeline_mock.set = AsyncMock()
- pipeline_mock.execute = AsyncMock()
- redis_mock.pipeline = MagicMock(return_value=pipeline_mock)
-
- # Mock scan_iter to return the specified keys
- if scan_keys is not None:
- # Convert keys to bytes as Redis returns bytes
- encoded_keys = [
- key.encode() if isinstance(key, str) else key for key in scan_keys
- ]
- # Create a proper async iterator mock
- async_iter = AsyncIteratorMock(encoded_keys)
- # Use the async iterator directly as the scan_iter method
- redis_mock.scan_iter = MagicMock(return_value=async_iter)
-
- # Create a pubsub mock
- pubsub = AsyncMock()
- pubsub.get_message = (get_message or GetMessageMock(None)).get_message
- redis_mock.pubsub.return_value = pubsub
-
- # Assign the Redis mock to the socketio manager
- sio.manager.redis = redis_mock
-
- return sio
-
-
-async def test_session_not_running_in_cluster():
- # Create a mock SIO with empty scan results (no running sessions)
- sio = get_mock_sio(scan_keys=[])
-
- async with ClusteredConversationManager(
- sio, OpenHandsConfig(), InMemoryFileStore(), MonitoringListener()
- ) as conversation_manager:
- result = await conversation_manager._get_running_agent_loops_remotely(
- filter_to_sids={'non-existant-session'}
- )
- assert result == set()
- # Verify scan_iter was called with the correct pattern
- sio.manager.redis.scan_iter.assert_called_once()
-
-
-async def test_get_running_agent_loops_remotely():
- # Create a mock SIO with scan results for 'existing-session'
- # The key format is 'ohcnv:{user_id}:{conversation_id}'
- sio = get_mock_sio(scan_keys=[b'ohcnv:1:existing-session'])
-
- async with ClusteredConversationManager(
- sio, OpenHandsConfig(), InMemoryFileStore(), MonitoringListener()
- ) as conversation_manager:
- result = await conversation_manager._get_running_agent_loops_remotely(
- 1, {'existing-session'}
- )
- assert result == {'existing-session'}
- # Verify scan_iter was called with the correct pattern
- sio.manager.redis.scan_iter.assert_called_once()
-
-
-async def test_init_new_local_session():
- session_instance = AsyncMock()
- session_instance.agent_session = MagicMock()
- session_instance.agent_session.event_stream.cur_id = 1
- session_instance.user_id = '1' # Add user_id for Redis key creation
- mock_session = MagicMock()
- mock_session.return_value = session_instance
- sio = get_mock_sio(scan_keys=[])
- get_running_agent_loops_mock = AsyncMock()
- get_running_agent_loops_mock.return_value = set()
- with (
- patch(
- 'openhands.server.conversation_manager.standalone_conversation_manager.Session',
- mock_session,
- ),
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._redis_subscribe',
- AsyncMock(),
- ),
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager.get_running_agent_loops',
- get_running_agent_loops_mock,
- ),
- ):
- async with ClusteredConversationManager(
- sio, OpenHandsConfig(), InMemoryFileStore(), MonitoringListener()
- ) as conversation_manager:
- await conversation_manager.maybe_start_agent_loop(
- 'new-session-id', ConversationInitData(), 1
- )
- await conversation_manager.join_conversation(
- 'new-session-id', 'new-session-id', ConversationInitData(), 1
- )
- assert session_instance.initialize_agent.call_count == 2
- assert sio.enter_room.await_count == 1
-
-
-async def test_join_local_session():
- session_instance = AsyncMock()
- session_instance.agent_session = MagicMock()
- session_instance.agent_session.event_stream.cur_id = 1
- session_instance.user_id = None # Add user_id for Redis key creation
- mock_session = MagicMock()
- mock_session.return_value = session_instance
- sio = get_mock_sio(scan_keys=[])
- get_running_agent_loops_mock = AsyncMock()
- get_running_agent_loops_mock.return_value = set()
- with (
- patch(
- 'openhands.server.conversation_manager.standalone_conversation_manager.Session',
- mock_session,
- ),
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._redis_subscribe',
- AsyncMock(),
- ),
- patch(
- 'openhands.server.conversation_manager.standalone_conversation_manager.StandaloneConversationManager.get_running_agent_loops',
- get_running_agent_loops_mock,
- ),
- ):
- async with ClusteredConversationManager(
- sio, OpenHandsConfig(), InMemoryFileStore(), MonitoringListener()
- ) as conversation_manager:
- await conversation_manager.maybe_start_agent_loop(
- 'new-session-id', ConversationInitData(), None
- )
- await conversation_manager.join_conversation(
- 'new-session-id', 'new-session-id', ConversationInitData(), None
- )
- await conversation_manager.join_conversation(
- 'new-session-id', 'new-session-id', ConversationInitData(), None
- )
- assert session_instance.initialize_agent.call_count == 3
- assert sio.enter_room.await_count == 2
-
-
-async def test_join_cluster_session():
- session_instance = AsyncMock()
- session_instance.agent_session = MagicMock()
- session_instance.user_id = '1' # Add user_id for Redis key creation
- mock_session = MagicMock()
- mock_session.return_value = session_instance
-
- # Create a mock SIO with scan results for 'new-session-id'
- sio = get_mock_sio(scan_keys=[b'ohcnv:1:new-session-id'])
-
- # Mock the Redis set method to return False (key already exists)
- # This simulates that the conversation is already running on another server
- sio.manager.redis.set.return_value = False
-
- # Mock the _get_event_store method to return a mock event store
- mock_event_store = MagicMock()
- get_event_store_mock = AsyncMock(return_value=mock_event_store)
-
- with (
- patch(
- 'openhands.server.conversation_manager.standalone_conversation_manager.Session',
- mock_session,
- ),
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._redis_subscribe',
- AsyncMock(),
- ),
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._get_event_store',
- get_event_store_mock,
- ),
- ):
- async with ClusteredConversationManager(
- sio, OpenHandsConfig(), InMemoryFileStore(), MonitoringListener()
- ) as conversation_manager:
- # Call join_conversation with the same parameters as in the original test
- # The user_id is passed directly to the join_conversation method
- await conversation_manager.join_conversation(
- 'new-session-id', 'new-session-id', ConversationInitData(), '1'
- )
-
- # Verify that the agent was not initialized (since it's running on another server)
- assert session_instance.initialize_agent.call_count == 0
-
- # Verify that the client was added to the room
- assert sio.enter_room.await_count == 1
-
-
-async def test_add_to_local_event_stream():
- session_instance = AsyncMock()
- session_instance.agent_session = MagicMock()
- session_instance.agent_session.event_stream.cur_id = 1
- session_instance.user_id = '1' # Add user_id for Redis key creation
- mock_session = MagicMock()
- mock_session.return_value = session_instance
- sio = get_mock_sio(scan_keys=[])
- get_running_agent_loops_mock = AsyncMock()
- get_running_agent_loops_mock.return_value = set()
- with (
- patch(
- 'openhands.server.conversation_manager.standalone_conversation_manager.Session',
- mock_session,
- ),
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._redis_subscribe',
- AsyncMock(),
- ),
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager.get_running_agent_loops',
- get_running_agent_loops_mock,
- ),
- ):
- async with ClusteredConversationManager(
- sio, OpenHandsConfig(), InMemoryFileStore(), MonitoringListener()
- ) as conversation_manager:
- await conversation_manager.maybe_start_agent_loop(
- 'new-session-id', ConversationInitData(), 1
- )
- await conversation_manager.join_conversation(
- 'new-session-id', 'connection-id', ConversationInitData(), 1
- )
- await conversation_manager.send_to_event_stream(
- 'connection-id', {'event_type': 'some_event'}
- )
- session_instance.dispatch.assert_called_once_with({'event_type': 'some_event'})
-
-
-async def test_add_to_cluster_event_stream():
- session_instance = AsyncMock()
- session_instance.agent_session = MagicMock()
- session_instance.user_id = '1' # Add user_id for Redis key creation
- mock_session = MagicMock()
- mock_session.return_value = session_instance
-
- # Create a mock SIO with scan results for 'new-session-id'
- sio = get_mock_sio(scan_keys=[b'ohcnv:1:new-session-id'])
-
- # Mock the Redis set method to return False (key already exists)
- # This simulates that the conversation is already running on another server
- sio.manager.redis.set.return_value = False
-
- with (
- patch(
- 'openhands.server.conversation_manager.standalone_conversation_manager.Session',
- mock_session,
- ),
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._redis_subscribe',
- AsyncMock(),
- ),
- ):
- async with ClusteredConversationManager(
- sio, OpenHandsConfig(), InMemoryFileStore(), MonitoringListener()
- ) as conversation_manager:
- # Set up the connection mapping
- conversation_manager._local_connection_id_to_session_id['connection-id'] = (
- 'new-session-id'
- )
-
- # Call send_to_event_stream
- await conversation_manager.send_to_event_stream(
- 'connection-id', {'event_type': 'some_event'}
- )
-
- # In the refactored implementation, we publish a message to Redis
- assert sio.manager.redis.publish.called
-
-
-async def test_cleanup_session_connections():
- sio = get_mock_sio(scan_keys=[])
- with (
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._redis_subscribe',
- AsyncMock(),
- ),
- ):
- async with ClusteredConversationManager(
- sio, OpenHandsConfig(), InMemoryFileStore(), MonitoringListener()
- ) as conversation_manager:
- conversation_manager._local_connection_id_to_session_id.update(
- {
- 'conn1': 'session1',
- 'conn2': 'session1',
- 'conn3': 'session2',
- 'conn4': 'session2',
- }
- )
-
- await conversation_manager._close_session('session1')
-
- # Verify disconnect was called for each connection to session1
- assert sio.disconnect.await_count == 2
- sio.disconnect.assert_any_await('conn1')
- sio.disconnect.assert_any_await('conn2')
-
- # Verify connections were removed from the mapping
- remaining_connections = (
- conversation_manager._local_connection_id_to_session_id
- )
- assert 'conn1' not in remaining_connections
- assert 'conn2' not in remaining_connections
- assert 'conn3' in remaining_connections
- assert 'conn4' in remaining_connections
- assert remaining_connections['conn3'] == 'session2'
- assert remaining_connections['conn4'] == 'session2'
-
-
-async def test_disconnect_from_stopped_no_remote_connections():
- """Test _disconnect_from_stopped when there are no remote connections."""
- sio = get_mock_sio(scan_keys=[])
- with (
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._redis_subscribe',
- AsyncMock(),
- ),
- ):
- async with ClusteredConversationManager(
- sio, OpenHandsConfig(), InMemoryFileStore(), MonitoringListener()
- ) as conversation_manager:
- # Setup: All connections are to local sessions
- conversation_manager._local_connection_id_to_session_id.update(
- {
- 'conn1': 'session1',
- 'conn2': 'session1',
- }
- )
- conversation_manager._local_agent_loops_by_sid['session1'] = MagicMock()
-
- # Execute
- await conversation_manager._disconnect_from_stopped()
-
- # Verify: No disconnections should happen
- assert sio.disconnect.call_count == 0
- assert len(conversation_manager._local_connection_id_to_session_id) == 2
-
-
-async def test_disconnect_from_stopped_with_running_remote():
- """Test _disconnect_from_stopped when remote sessions are still running."""
- # Create a mock SIO with scan results for remote sessions
- sio = get_mock_sio(
- scan_keys=[b'ohcnv:1:remote_session1', b'ohcnv:1:remote_session2']
- )
- get_running_agent_loops_remotely_mock = AsyncMock()
- get_running_agent_loops_remotely_mock.return_value = {
- 'remote_session1',
- 'remote_session2',
- }
-
- with (
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._redis_subscribe',
- AsyncMock(),
- ),
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._get_running_agent_loops_remotely',
- get_running_agent_loops_remotely_mock,
- ),
- ):
- async with ClusteredConversationManager(
- sio, OpenHandsConfig(), InMemoryFileStore(), MonitoringListener()
- ) as conversation_manager:
- # Setup: Some connections are to remote sessions
- conversation_manager._local_connection_id_to_session_id.update(
- {
- 'conn1': 'local_session1',
- 'conn2': 'remote_session1',
- 'conn3': 'remote_session2',
- }
- )
- conversation_manager._local_agent_loops_by_sid['local_session1'] = (
- MagicMock()
- )
-
- # Execute
- await conversation_manager._disconnect_from_stopped()
-
- # Verify: No disconnections should happen since remote sessions are running
- assert sio.disconnect.call_count == 0
- assert len(conversation_manager._local_connection_id_to_session_id) == 3
-
-
-async def test_disconnect_from_stopped_with_stopped_remote():
- """Test _disconnect_from_stopped when some remote sessions have stopped."""
- # Create a mock SIO with scan results for only remote_session1
- sio = get_mock_sio(scan_keys=[b'ohcnv:user1:remote_session1'])
-
- # Mock the async database session
- mock_user = MagicMock()
- mock_user.user_id = 'user1'
-
- mock_result = MagicMock()
- mock_result.scalars.return_value.first.return_value = mock_user
-
- mock_session = AsyncMock()
- mock_session.execute = AsyncMock(return_value=mock_result)
-
- @contextlib.asynccontextmanager
- async def mock_a_session_maker():
- yield mock_session
-
- with (
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._redis_subscribe',
- AsyncMock(),
- ),
- patch(
- 'server.clustered_conversation_manager.a_session_maker',
- mock_a_session_maker,
- ),
- patch('asyncio.create_task', MagicMock()),
- ):
- async with ClusteredConversationManager(
- sio, OpenHandsConfig(), InMemoryFileStore(), MonitoringListener()
- ) as conversation_manager:
- # Setup: Some connections are to remote sessions, one of which has stopped
- conversation_manager._local_connection_id_to_session_id.update(
- {
- 'conn1': 'local_session1',
- 'conn2': 'remote_session1', # Running
- 'conn3': 'remote_session2', # Stopped
- 'conn4': 'remote_session2', # Stopped (another connection to the same stopped session)
- }
- )
-
- # Mock the _get_running_agent_loops_remotely method
- conversation_manager._get_running_agent_loops_remotely = AsyncMock(
- return_value={'remote_session1'} # Only remote_session1 is running
- )
-
- # Add a local session
- conversation_manager._local_agent_loops_by_sid['local_session1'] = (
- MagicMock()
- )
-
- # Mock the _handle_remote_conversation_stopped method with the correct signature
- conversation_manager._handle_remote_conversation_stopped = AsyncMock()
-
- # Execute
- await conversation_manager._disconnect_from_stopped()
-
- # Verify: Connections to stopped remote sessions should be disconnected
- assert (
- conversation_manager._handle_remote_conversation_stopped.call_count == 2
- )
- # The method is called with user_id and connection_id in the refactored implementation
- conversation_manager._handle_remote_conversation_stopped.assert_any_call(
- 'user1', 'conn3'
- )
- conversation_manager._handle_remote_conversation_stopped.assert_any_call(
- 'user1', 'conn4'
- )
-
-
-async def test_close_disconnected_detached_conversations():
- """Test _close_disconnected for detached conversations."""
- sio = get_mock_sio(scan_keys=[])
-
- with (
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._redis_subscribe',
- AsyncMock(),
- ),
- ):
- async with ClusteredConversationManager(
- sio, OpenHandsConfig(), InMemoryFileStore(), MonitoringListener()
- ) as conversation_manager:
- # Setup: Add some detached conversations
- conversation1 = AsyncMock()
- conversation2 = AsyncMock()
- conversation_manager._detached_conversations.update(
- {
- 'session1': (conversation1, time.time()),
- 'session2': (conversation2, time.time()),
- }
- )
-
- # Execute
- await conversation_manager._close_disconnected()
-
- # Verify: All detached conversations should be disconnected
- assert conversation1.disconnect.await_count == 1
- assert conversation2.disconnect.await_count == 1
- assert len(conversation_manager._detached_conversations) == 0
-
-
-async def test_close_disconnected_inactive_sessions():
- """Test _close_disconnected for inactive sessions."""
- sio = get_mock_sio(scan_keys=[])
- get_connections_mock = AsyncMock()
- get_connections_mock.return_value = {} # No connections
- get_connections_remotely_mock = AsyncMock()
- get_connections_remotely_mock.return_value = {} # No remote connections
- close_session_mock = AsyncMock()
-
- # Create a mock config with a short close_delay
- config = OpenHandsConfig()
- config.sandbox.close_delay = 10 # 10 seconds
-
- with (
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._redis_subscribe',
- AsyncMock(),
- ),
- patch(
- 'openhands.server.conversation_manager.standalone_conversation_manager.StandaloneConversationManager.get_connections',
- get_connections_mock,
- ),
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._get_connections_remotely',
- get_connections_remotely_mock,
- ),
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._close_session',
- close_session_mock,
- ),
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._cleanup_stale',
- AsyncMock(),
- ),
- ):
- async with ClusteredConversationManager(
- sio, config, InMemoryFileStore(), MonitoringListener()
- ) as conversation_manager:
- # Setup: Add some agent loops with different states and activity times
-
- # Session 1: Inactive and not running (should be closed)
- session1 = MagicMock()
- session1.last_active_ts = time.time() - 20 # Inactive for 20 seconds
- session1.agent_session.get_state.return_value = AgentState.FINISHED
-
- # Session 2: Inactive but running (should not be closed)
- session2 = MagicMock()
- session2.last_active_ts = time.time() - 20 # Inactive for 20 seconds
- session2.agent_session.get_state.return_value = AgentState.RUNNING
-
- # Session 3: Active and not running (should not be closed)
- session3 = MagicMock()
- session3.last_active_ts = time.time() - 5 # Active recently
- session3.agent_session.get_state.return_value = AgentState.FINISHED
-
- conversation_manager._local_agent_loops_by_sid.update(
- {
- 'session1': session1,
- 'session2': session2,
- 'session3': session3,
- }
- )
-
- # Execute
- await conversation_manager._close_disconnected()
-
- # Verify: Only session1 should be closed
- assert close_session_mock.await_count == 1
- close_session_mock.assert_called_once_with('session1')
-
-
-async def test_close_disconnected_with_connections():
- """Test _close_disconnected when sessions have connections."""
- sio = get_mock_sio(scan_keys=[])
-
- # Mock local connections
- get_connections_mock = AsyncMock()
- get_connections_mock.return_value = {
- 'conn1': 'session1'
- } # session1 has a connection
-
- # Mock remote connections
- get_connections_remotely_mock = AsyncMock()
- get_connections_remotely_mock.return_value = {
- 'remote_conn': 'session2'
- } # session2 has a remote connection
-
- close_session_mock = AsyncMock()
-
- # Create a mock config with a short close_delay
- config = OpenHandsConfig()
- config.sandbox.close_delay = 10 # 10 seconds
-
- with (
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._redis_subscribe',
- AsyncMock(),
- ),
- patch(
- 'openhands.server.conversation_manager.standalone_conversation_manager.StandaloneConversationManager.get_connections',
- get_connections_mock,
- ),
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._get_connections_remotely',
- get_connections_remotely_mock,
- ),
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._close_session',
- close_session_mock,
- ),
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._cleanup_stale',
- AsyncMock(),
- ),
- ):
- async with ClusteredConversationManager(
- sio, config, InMemoryFileStore(), MonitoringListener()
- ) as conversation_manager:
- # Setup: Add some agent loops with different states and activity times
-
- # Session 1: Inactive and not running, but has a local connection (should not be closed)
- session1 = MagicMock()
- session1.last_active_ts = time.time() - 20 # Inactive for 20 seconds
- session1.agent_session.get_state.return_value = AgentState.FINISHED
-
- # Session 2: Inactive and not running, but has a remote connection (should not be closed)
- session2 = MagicMock()
- session2.last_active_ts = time.time() - 20 # Inactive for 20 seconds
- session2.agent_session.get_state.return_value = AgentState.FINISHED
-
- # Session 3: Inactive and not running, no connections (should be closed)
- session3 = MagicMock()
- session3.last_active_ts = time.time() - 20 # Inactive for 20 seconds
- session3.agent_session.get_state.return_value = AgentState.FINISHED
-
- conversation_manager._local_agent_loops_by_sid.update(
- {
- 'session1': session1,
- 'session2': session2,
- 'session3': session3,
- }
- )
-
- # Execute
- await conversation_manager._close_disconnected()
-
- # Verify: Only session3 should be closed
- assert close_session_mock.await_count == 1
- close_session_mock.assert_called_once_with('session3')
-
-
-async def test_cleanup_stale_integration():
- """Test the integration of _cleanup_stale with the new methods."""
- sio = get_mock_sio(scan_keys=[])
-
- disconnect_from_stopped_mock = AsyncMock()
- close_disconnected_mock = AsyncMock()
-
- with (
- patch(
- 'server.clustered_conversation_manager._CLEANUP_INTERVAL_SECONDS',
- 0.01, # Short interval for testing
- ),
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._redis_subscribe',
- AsyncMock(),
- ),
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._disconnect_from_stopped',
- disconnect_from_stopped_mock,
- ),
- patch(
- 'server.clustered_conversation_manager.ClusteredConversationManager._close_disconnected',
- close_disconnected_mock,
- ),
- patch(
- 'server.clustered_conversation_manager.should_continue',
- MagicMock(side_effect=[True, True, False]), # Run the loop 2 times
- ),
- ):
- async with ClusteredConversationManager(
- sio, OpenHandsConfig(), InMemoryFileStore(), MonitoringListener()
- ):
- # Let the cleanup task run for a short time
- await asyncio.sleep(0.05)
-
- # Verify: Both methods should be called at least once
- # The exact number of calls may vary due to timing, so we check for at least 1
- assert disconnect_from_stopped_mock.await_count >= 1
- assert close_disconnected_mock.await_count >= 1
diff --git a/enterprise/tests/unit/test_github_view.py b/enterprise/tests/unit/test_github_view.py
index 3dbb3d2124..040858de9f 100644
--- a/enterprise/tests/unit/test_github_view.py
+++ b/enterprise/tests/unit/test_github_view.py
@@ -1,5 +1,5 @@
from unittest import TestCase, mock
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import MagicMock, patch
from uuid import UUID
import pytest
@@ -158,43 +158,9 @@ class TestGithubV1ConversationRouting(TestCase):
self.assertTrue(github_issue.v1_enabled)
@pytest.mark.asyncio
- @patch.object(GithubIssue, '_create_v0_conversation')
@patch.object(GithubIssue, '_create_v1_conversation')
- async def test_create_new_conversation_routes_to_v0_when_disabled(
- self, mock_create_v1, mock_create_v0
- ):
- """Test that conversation creation routes to V0 when v1_enabled is False."""
- mock_create_v0.return_value = None
- mock_create_v1.return_value = None
-
- github_issue = self._create_github_issue()
- github_issue.v1_enabled = False
-
- # Mock parameters
- jinja_env = MagicMock()
- git_provider_tokens = MagicMock()
- conversation_metadata = MagicMock()
- saas_user_auth = MagicMock()
-
- # Call the method
- await github_issue.create_new_conversation(
- jinja_env, git_provider_tokens, conversation_metadata, saas_user_auth
- )
-
- # Verify V0 was called and V1 was not
- mock_create_v0.assert_called_once_with(
- jinja_env, git_provider_tokens, conversation_metadata
- )
- mock_create_v1.assert_not_called()
-
- @pytest.mark.asyncio
- @patch.object(GithubIssue, '_create_v0_conversation')
- @patch.object(GithubIssue, '_create_v1_conversation')
- async def test_create_new_conversation_routes_to_v1_when_enabled(
- self, mock_create_v1, mock_create_v0
- ):
- """Test that conversation creation routes to V1 when v1_enabled is True."""
- mock_create_v0.return_value = None
+ async def test_create_new_conversation_routes_to_v1(self, mock_create_v1):
+ """Test that conversation creation routes to V1."""
mock_create_v1.return_value = None
github_issue = self._create_github_issue()
@@ -211,11 +177,10 @@ class TestGithubV1ConversationRouting(TestCase):
jinja_env, git_provider_tokens, conversation_metadata, saas_user_auth
)
- # Verify V1 was called and V0 was not
+ # Verify V1 was called
mock_create_v1.assert_called_once_with(
jinja_env, saas_user_auth, conversation_metadata
)
- mock_create_v0.assert_not_called()
class TestGithubOrgRouting(TestCase):
@@ -251,41 +216,8 @@ class TestGithubOrgRouting(TestCase):
title='',
description='',
previous_comments=[],
- v1_enabled=False,
- )
-
- @pytest.mark.asyncio
- @patch(
- 'integrations.github.github_view.SaasConversationStore.get_resolver_instance'
- )
- @patch('integrations.github.github_view.resolve_org_for_repo')
- @patch('integrations.github.github_view.get_user_v1_enabled_setting')
- async def test_v0_passes_resolver_org_id_to_get_resolver_instance(
- self, mock_v1_setting, mock_resolve_org, mock_get_resolver
- ):
- """V0 path creates store via get_resolver_instance with resolver_org_id."""
- # Arrange
- mock_v1_setting.return_value = False
- mock_resolve_org.return_value = self.resolved_org_id
- mock_store = MagicMock()
- mock_store.save_metadata = AsyncMock()
- mock_get_resolver.return_value = mock_store
-
- github_issue = self._create_github_issue()
-
- # Act
- await github_issue.initialize_new_conversation()
-
- # Assert
- mock_resolve_org.assert_called_once_with(
- provider='github',
- full_repo_name='ClaimedOrg/repo',
- keycloak_user_id='test-keycloak-id',
+ v1_enabled=True,
)
- # get_resolver_instance(config, user_id, resolver_org_id)
- args, _ = mock_get_resolver.call_args
- assert args[1] == 'test-keycloak-id'
- assert args[2] == self.resolved_org_id
@pytest.mark.asyncio
@patch('integrations.github.github_view.get_app_conversation_service')
@@ -308,21 +240,16 @@ class TestGithubOrgRouting(TestCase):
assert github_issue.resolved_org_id == self.resolved_org_id
@pytest.mark.asyncio
- @patch(
- 'integrations.github.github_view.SaasConversationStore.get_resolver_instance'
- )
+ @patch('integrations.github.github_view.get_app_conversation_service')
@patch('integrations.github.github_view.resolve_org_for_repo')
@patch('integrations.github.github_view.get_user_v1_enabled_setting')
async def test_no_claim_passes_none_resolver_org_id(
- self, mock_v1_setting, mock_resolve_org, mock_get_resolver
+ self, mock_v1_setting, mock_resolve_org, mock_get_service
):
"""When no claim exists, resolver_org_id is None (falls back to personal workspace)."""
# Arrange
- mock_v1_setting.return_value = False
+ mock_v1_setting.return_value = True
mock_resolve_org.return_value = None
- mock_store = MagicMock()
- mock_store.save_metadata = AsyncMock()
- mock_get_resolver.return_value = mock_store
github_issue = self._create_github_issue()
@@ -330,5 +257,4 @@ class TestGithubOrgRouting(TestCase):
await github_issue.initialize_new_conversation()
# Assert
- args, _ = mock_get_resolver.call_args
- assert args[2] is None
+ assert github_issue.resolved_org_id is None
diff --git a/enterprise/tests/unit/test_gitlab_callback_processor.py b/enterprise/tests/unit/test_gitlab_callback_processor.py
deleted file mode 100644
index 629c8cd72c..0000000000
--- a/enterprise/tests/unit/test_gitlab_callback_processor.py
+++ /dev/null
@@ -1,227 +0,0 @@
-"""
-Tests for the GitlabCallbackProcessor.
-"""
-
-from unittest.mock import AsyncMock, patch
-
-import pytest
-from integrations.gitlab.gitlab_view import GitlabIssueComment
-from integrations.types import UserData
-from server.conversation_callback_processor.gitlab_callback_processor import (
- GitlabCallbackProcessor,
-)
-from storage.conversation_callback import CallbackStatus, ConversationCallback
-
-from openhands.core.schema.agent import AgentState
-from openhands.events.observation.agent import AgentStateChangedObservation
-
-
-def mock_gitlab_view():
- """Create a mock GitlabViewType for testing."""
- # Use a simple dict that matches GitlabIssue structure
- return GitlabIssueComment(
- installation_id='test_installation',
- issue_number=789,
- project_id=456,
- full_repo_name='test/repo',
- is_public_repo=True,
- user_info=UserData(
- user_id=123, username='test_user', keycloak_user_id='test_keycloak_id'
- ),
- raw_payload={'source': 'gitlab', 'message': {'test': 'data'}},
- conversation_id='test_conversation',
- should_extract=True,
- send_summary_instruction=True,
- title='',
- description='',
- previous_comments=[],
- is_mr=False,
- comment_body='sdfs',
- discussion_id='test_discussion',
- confidential=False,
- v1_enabled=False,
- )
-
-
-def gitlab_callback_processor(mock_gitlab_view):
- """Create a GitlabCallbackProcessor instance for testing."""
- return GitlabCallbackProcessor(
- gitlab_view=mock_gitlab_view,
- send_summary_instruction=True,
- )
-
-
-class TestGitlabCallbackProcessor:
- """Test the GitlabCallbackProcessor class."""
-
- def test_model_validation(self, mock_gitlab_view):
- """Test the model validation of GitlabCallbackProcessor."""
- # Test with all required fields
- processor = GitlabCallbackProcessor(
- gitlab_view=mock_gitlab_view,
- )
- # Check that gitlab_view was converted to a GitlabIssue object
- assert hasattr(processor.gitlab_view, 'issue_number')
- assert processor.gitlab_view.issue_number == 789
- assert processor.gitlab_view.full_repo_name == 'test/repo'
- assert processor.send_summary_instruction is True
-
- # Test with custom send_summary_instruction
- processor = GitlabCallbackProcessor(
- gitlab_view=mock_gitlab_view,
- send_summary_instruction=False,
- )
- assert hasattr(processor.gitlab_view, 'issue_number')
- assert processor.gitlab_view.issue_number == 789
- assert processor.send_summary_instruction is False
-
- def test_serialization(self, mock_gitlab_view):
- """Test serialization and deserialization of GitlabCallbackProcessor."""
- original_processor = GitlabCallbackProcessor(
- gitlab_view=mock_gitlab_view,
- send_summary_instruction=True,
- )
-
- # Serialize to JSON
- json_data = original_processor.model_dump_json()
- assert isinstance(json_data, str)
-
- # Deserialize from JSON
- deserialized_processor = GitlabCallbackProcessor.model_validate_json(json_data)
- assert (
- deserialized_processor.send_summary_instruction
- == original_processor.send_summary_instruction
- )
- assert (
- deserialized_processor.gitlab_view.issue_number
- == original_processor.gitlab_view.issue_number
- )
-
- assert isinstance(
- deserialized_processor.gitlab_view.issue_number,
- type(original_processor.gitlab_view.issue_number),
- )
- # Note: gitlab_view will be serialized as a dict, so we can't directly compare objects
-
- @pytest.mark.asyncio
- @patch(
- 'server.conversation_callback_processor.gitlab_callback_processor.get_summary_instruction'
- )
- @patch(
- 'server.conversation_callback_processor.gitlab_callback_processor.conversation_manager'
- )
- async def test_call_with_send_summary_instruction(
- self,
- mock_conversation_manager,
- mock_get_summary_instruction,
- async_session_maker,
- gitlab_callback_processor,
- ):
- """Test the __call__ method when send_summary_instruction is True."""
- # Setup mocks
- mock_conversation_manager.send_event_to_conversation = AsyncMock()
- mock_get_summary_instruction.return_value = (
- "I'm a man of few words. Any questions?"
- )
-
- # Create a callback and observation
- callback = ConversationCallback(
- conversation_id='conv123',
- status=CallbackStatus.ACTIVE,
- processor_type=f'{GitlabCallbackProcessor.__module__}.{GitlabCallbackProcessor.__name__}',
- processor_json=gitlab_callback_processor.model_dump_json(),
- )
- observation = AgentStateChangedObservation(
- content='', agent_state=AgentState.AWAITING_USER_INPUT
- )
-
- # Call the processor
- with patch(
- 'server.conversation_callback_processor.gitlab_callback_processor.a_session_maker',
- async_session_maker,
- ):
- await gitlab_callback_processor(callback, observation)
-
- # Verify that send_event_to_conversation was called
- mock_conversation_manager.send_event_to_conversation.assert_called_once()
-
- # Verify that the processor state was updated
- assert gitlab_callback_processor.send_summary_instruction is False
-
- @pytest.mark.asyncio
- @patch(
- 'server.conversation_callback_processor.gitlab_callback_processor.conversation_manager'
- )
- @patch(
- 'server.conversation_callback_processor.gitlab_callback_processor.extract_summary_from_conversation_manager'
- )
- @patch(
- 'server.conversation_callback_processor.gitlab_callback_processor.asyncio.create_task'
- )
- async def test_call_with_extract_summary(
- self,
- mock_create_task,
- mock_extract_summary,
- mock_conversation_manager,
- async_session_maker,
- gitlab_callback_processor,
- ):
- """Test the __call__ method when send_summary_instruction is False."""
- # Setup mocks
- mock_extract_summary.return_value = 'Test summary'
- # Ensure we don't leak an un-awaited coroutine when create_task is mocked
- mock_create_task.side_effect = lambda coro: (coro.close(), None)[1]
-
- # Set send_summary_instruction to False
- gitlab_callback_processor.send_summary_instruction = False
-
- # Create a callback and observation
- callback = ConversationCallback(
- conversation_id='conv123',
- status=CallbackStatus.ACTIVE,
- processor_type=f'{GitlabCallbackProcessor.__module__}.{GitlabCallbackProcessor.__name__}',
- processor_json=gitlab_callback_processor.model_dump_json(),
- )
- observation = AgentStateChangedObservation(
- content='', agent_state=AgentState.FINISHED
- )
-
- # Call the processor
- with patch(
- 'server.conversation_callback_processor.gitlab_callback_processor.a_session_maker',
- async_session_maker,
- ):
- await gitlab_callback_processor(callback, observation)
-
- # Verify that extract_summary_from_conversation_manager was called
- mock_extract_summary.assert_called_once_with(
- mock_conversation_manager, 'conv123'
- )
-
- # Verify that create_task was called at least once to send the message
- assert mock_create_task.call_count >= 1
-
- # Verify that the callback status was updated
- assert callback.status == CallbackStatus.COMPLETED
-
- @pytest.mark.asyncio
- async def test_call_with_non_terminal_state(self, gitlab_callback_processor):
- """Test the __call__ method with a non-terminal agent state."""
- # Create a callback and observation with a non-terminal state
- callback = ConversationCallback(
- conversation_id='conv123',
- status=CallbackStatus.ACTIVE,
- processor_type=f'{GitlabCallbackProcessor.__module__}.{GitlabCallbackProcessor.__name__}',
- processor_json=gitlab_callback_processor.model_dump_json(),
- )
- observation = AgentStateChangedObservation(
- content='', agent_state=AgentState.RUNNING
- )
-
- # Call the processor
- await gitlab_callback_processor(callback, observation)
-
- # Verify that nothing happened (early return)
- assert gitlab_callback_processor.send_summary_instruction is True
diff --git a/enterprise/tests/unit/test_gitlab_view.py b/enterprise/tests/unit/test_gitlab_view.py
index 0ed803dda0..644807bf6f 100644
--- a/enterprise/tests/unit/test_gitlab_view.py
+++ b/enterprise/tests/unit/test_gitlab_view.py
@@ -1,11 +1,11 @@
"""Tests for GitLab resolver org routing logic.
Tests that the GitLab resolver correctly resolves the target organization
-and passes resolver_org_id through V0 and V1 conversation paths.
+and passes resolver_org_id through V1 conversation paths.
"""
from unittest import TestCase
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import patch
from uuid import UUID
import pytest
@@ -48,40 +48,9 @@ class TestGitlabOrgRouting(TestCase):
description='',
previous_comments=[],
is_mr=False,
- v1_enabled=False,
+ v1_enabled=True,
)
- @pytest.mark.asyncio
- @patch(
- 'integrations.gitlab.gitlab_view.SaasConversationStore.get_resolver_instance'
- )
- @patch('integrations.gitlab.gitlab_view.resolve_org_for_repo')
- async def test_v0_passes_resolver_org_id_to_get_resolver_instance(
- self, mock_resolve_org, mock_get_resolver
- ):
- """V0 path creates store via get_resolver_instance with resolver_org_id."""
- # Arrange
- mock_resolve_org.return_value = self.resolved_org_id
- mock_store = MagicMock()
- mock_store.save_metadata = AsyncMock()
- mock_get_resolver.return_value = mock_store
-
- gitlab_issue = self._create_gitlab_issue()
-
- # Act
- await gitlab_issue.initialize_new_conversation()
-
- # Assert
- mock_resolve_org.assert_called_once_with(
- provider='gitlab',
- full_repo_name='ClaimedOrg/repo',
- keycloak_user_id='test-keycloak-id',
- )
- # get_resolver_instance(config, user_id, resolver_org_id)
- args, _ = mock_get_resolver.call_args
- assert args[1] == 'test-keycloak-id'
- assert args[2] == self.resolved_org_id
-
@pytest.mark.asyncio
@patch('integrations.gitlab.gitlab_view.get_app_conversation_service')
@patch('integrations.gitlab.gitlab_view.resolve_org_for_repo')
@@ -93,7 +62,6 @@ class TestGitlabOrgRouting(TestCase):
mock_resolve_org.return_value = self.resolved_org_id
gitlab_issue = self._create_gitlab_issue()
- gitlab_issue.v1_enabled = True
# Initialize to set resolved_org_id
await gitlab_issue.initialize_new_conversation()
@@ -102,19 +70,14 @@ class TestGitlabOrgRouting(TestCase):
assert gitlab_issue.resolved_org_id == self.resolved_org_id
@pytest.mark.asyncio
- @patch(
- 'integrations.gitlab.gitlab_view.SaasConversationStore.get_resolver_instance'
- )
+ @patch('integrations.gitlab.gitlab_view.get_app_conversation_service')
@patch('integrations.gitlab.gitlab_view.resolve_org_for_repo')
async def test_no_claim_passes_none_resolver_org_id(
- self, mock_resolve_org, mock_get_resolver
+ self, mock_resolve_org, mock_get_service
):
"""When no claim exists, resolver_org_id is None (falls back to personal workspace)."""
# Arrange
mock_resolve_org.return_value = None
- mock_store = MagicMock()
- mock_store.save_metadata = AsyncMock()
- mock_get_resolver.return_value = mock_store
gitlab_issue = self._create_gitlab_issue()
@@ -122,5 +85,4 @@ class TestGitlabOrgRouting(TestCase):
await gitlab_issue.initialize_new_conversation()
# Assert
- args, _ = mock_get_resolver.call_args
- assert args[2] is None
+ assert gitlab_issue.resolved_org_id is None
diff --git a/enterprise/tests/unit/test_linear_view.py b/enterprise/tests/unit/test_linear_view.py
deleted file mode 100644
index 3eb0dfbfa2..0000000000
--- a/enterprise/tests/unit/test_linear_view.py
+++ /dev/null
@@ -1,347 +0,0 @@
-"""Tests for Linear resolver org routing logic.
-
-Tests that the LinearNewConversationView correctly resolves the target
-organization and passes resolver_org_id through the V0 conversation path.
-"""
-
-from unittest.mock import AsyncMock, MagicMock, patch
-from uuid import UUID
-
-import pytest
-from integrations.linear.linear_view import LinearNewConversationView
-from integrations.models import JobContext
-from storage.linear_user import LinearUser
-from storage.linear_workspace import LinearWorkspace
-
-from openhands.integrations.service_types import ProviderType
-from openhands.server.user_auth.user_auth import UserAuth
-from openhands.storage.data_models.conversation_metadata import ConversationTrigger
-
-CLAIMING_ORG_ID = UUID('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa')
-KEYCLOAK_USER_ID = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'
-
-
-def mock_linear_user():
- user = LinearUser()
- user.id = 1
- user.keycloak_user_id = KEYCLOAK_USER_ID
- user.linear_user_id = 'linear-user-123'
- user.linear_workspace_id = 1
- user.status = 'active'
- return user
-
-
-def mock_linear_workspace():
- workspace = LinearWorkspace()
- workspace.id = 1
- workspace.name = 'test-workspace'
- workspace.linear_org_id = 'linear-org-123'
- workspace.admin_user_id = 'admin-123'
- workspace.webhook_secret = 'secret'
- workspace.svc_acc_email = '[email protected]'
- workspace.svc_acc_api_key = 'api-key'
- workspace.status = 'active'
- return workspace
-
-
-def mock_user_auth():
- auth = MagicMock(spec=UserAuth)
- auth.get_provider_tokens = AsyncMock(
- return_value={ProviderType.GITHUB: MagicMock()}
- )
- auth.get_secrets = AsyncMock(return_value=MagicMock(custom_secrets={}))
- return auth
-
-
-def job_context():
- return JobContext(
- issue_id='issue-123',
- issue_key='PROJ-42',
- issue_title='Test issue',
- issue_description='Test description',
- user_msg='@openhands fix this',
- user_email='[email protected]',
- platform_user_id='linear-user-123',
- workspace_name='test-workspace',
- display_name='Test User',
- )
-
-
-def linear_view(job_context, mock_user_auth, mock_linear_user, mock_linear_workspace):
- return LinearNewConversationView(
- job_context=job_context,
- saas_user_auth=mock_user_auth,
- linear_user=mock_linear_user,
- linear_workspace=mock_linear_workspace,
- selected_repo='OpenHands/foo',
- conversation_id='',
- )
-
-
-class TestLinearV0OrgRouting:
- """Test V0 conversation routing logic for Linear resolver."""
-
- @pytest.mark.asyncio
- @patch(
- 'integrations.linear.linear_view.resolve_org_for_repo', new_callable=AsyncMock
- )
- @patch('integrations.linear.linear_view.ProviderHandler')
- @patch(
- 'integrations.linear.linear_view.SaasConversationStore.get_resolver_instance',
- new_callable=AsyncMock,
- )
- @patch('integrations.linear.linear_view.start_conversation', new_callable=AsyncMock)
- @patch(
- 'integrations.linear.linear_view.integration_store',
- )
- async def test_v0_passes_resolver_org_id_to_get_resolver_instance(
- self,
- mock_integration_store,
- mock_start_convo,
- mock_get_resolver_instance,
- mock_provider_handler_cls,
- mock_resolve_org,
- linear_view,
- ):
- """V0 path should resolve org and pass resolver_org_id to get_resolver_instance."""
- # Arrange
- mock_repo = MagicMock()
- mock_repo.git_provider = ProviderType.GITHUB
- mock_handler = MagicMock()
- mock_handler.verify_repo_provider = AsyncMock(return_value=mock_repo)
- mock_provider_handler_cls.return_value = mock_handler
-
- mock_resolve_org.return_value = CLAIMING_ORG_ID
- mock_store = MagicMock()
- mock_store.save_metadata = AsyncMock()
- mock_get_resolver_instance.return_value = mock_store
- mock_integration_store.create_conversation = AsyncMock()
-
- mock_jinja = MagicMock()
-
- # Act
- with patch.object(
- linear_view,
- '_get_instructions',
- new_callable=AsyncMock,
- return_value=('instructions', 'user_msg'),
- ):
- await linear_view.create_or_update_conversation(mock_jinja)
-
- # Assert
- mock_resolve_org.assert_called_once_with(
- provider='github',
- full_repo_name='OpenHands/foo',
- keycloak_user_id=KEYCLOAK_USER_ID,
- )
- call_args = mock_get_resolver_instance.call_args
- assert call_args[0][1] == KEYCLOAK_USER_ID
- assert call_args[0][2] == CLAIMING_ORG_ID
- saved_metadata = mock_store.save_metadata.call_args[0][0]
- assert saved_metadata.trigger == ConversationTrigger.LINEAR
- assert saved_metadata.git_provider == ProviderType.GITHUB
-
- @pytest.mark.asyncio
- @patch(
- 'integrations.linear.linear_view.resolve_org_for_repo', new_callable=AsyncMock
- )
- @patch('integrations.linear.linear_view.ProviderHandler')
- @patch(
- 'integrations.linear.linear_view.SaasConversationStore.get_resolver_instance',
- new_callable=AsyncMock,
- )
- @patch('integrations.linear.linear_view.start_conversation', new_callable=AsyncMock)
- @patch(
- 'integrations.linear.linear_view.integration_store',
- )
- async def test_v0_passes_none_when_no_claim(
- self,
- mock_integration_store,
- mock_start_convo,
- mock_get_resolver_instance,
- mock_provider_handler_cls,
- mock_resolve_org,
- linear_view,
- ):
- """When no claim exists, resolver_org_id should be None (personal workspace)."""
- # Arrange
- mock_repo = MagicMock()
- mock_repo.git_provider = ProviderType.GITHUB
- mock_handler = MagicMock()
- mock_handler.verify_repo_provider = AsyncMock(return_value=mock_repo)
- mock_provider_handler_cls.return_value = mock_handler
-
- mock_resolve_org.return_value = None
- mock_store = MagicMock()
- mock_store.save_metadata = AsyncMock()
- mock_get_resolver_instance.return_value = mock_store
- mock_integration_store.create_conversation = AsyncMock()
-
- mock_jinja = MagicMock()
-
- # Act
- with patch.object(
- linear_view,
- '_get_instructions',
- new_callable=AsyncMock,
- return_value=('instructions', 'user_msg'),
- ):
- await linear_view.create_or_update_conversation(mock_jinja)
-
- # Assert
- call_args = mock_get_resolver_instance.call_args
- assert call_args[0][2] is None
-
- @pytest.mark.asyncio
- @patch(
- 'integrations.linear.linear_view.resolve_org_for_repo', new_callable=AsyncMock
- )
- @patch(
- 'integrations.linear.linear_view.SaasConversationStore.get_resolver_instance',
- new_callable=AsyncMock,
- )
- @patch('integrations.linear.linear_view.start_conversation', new_callable=AsyncMock)
- @patch(
- 'integrations.linear.linear_view.integration_store',
- )
- async def test_no_provider_tokens_skips_org_resolution(
- self,
- mock_integration_store,
- mock_start_convo,
- mock_get_resolver_instance,
- mock_resolve_org,
- linear_view,
- mock_user_auth,
- ):
- """When provider tokens are None, org resolution should be skipped."""
- # Arrange
- mock_user_auth.get_provider_tokens = AsyncMock(return_value=None)
- mock_store = MagicMock()
- mock_store.save_metadata = AsyncMock()
- mock_get_resolver_instance.return_value = mock_store
- mock_integration_store.create_conversation = AsyncMock()
-
- mock_jinja = MagicMock()
-
- # Act
- with patch.object(
- linear_view,
- '_get_instructions',
- new_callable=AsyncMock,
- return_value=('instructions', 'user_msg'),
- ):
- await linear_view.create_or_update_conversation(mock_jinja)
-
- # Assert
- mock_resolve_org.assert_not_called()
- call_args = mock_get_resolver_instance.call_args
- assert call_args[0][2] is None
- saved_metadata = mock_store.save_metadata.call_args[0][0]
- assert saved_metadata.git_provider is None
-
- @pytest.mark.asyncio
- @patch(
- 'integrations.linear.linear_view.resolve_org_for_repo', new_callable=AsyncMock
- )
- @patch('integrations.linear.linear_view.ProviderHandler')
- @patch(
- 'integrations.linear.linear_view.SaasConversationStore.get_resolver_instance',
- new_callable=AsyncMock,
- )
- @patch('integrations.linear.linear_view.start_conversation', new_callable=AsyncMock)
- @patch(
- 'integrations.linear.linear_view.integration_store',
- )
- async def test_verify_repo_provider_failure_falls_back_to_personal_workspace(
- self,
- mock_integration_store,
- mock_start_convo,
- mock_get_resolver_instance,
- mock_provider_handler_cls,
- mock_resolve_org,
- linear_view,
- ):
- """When verify_repo_provider fails, should fall back to personal workspace."""
- # Arrange
- mock_handler = MagicMock()
- mock_handler.verify_repo_provider = AsyncMock(
- side_effect=Exception('Repository not found')
- )
- mock_provider_handler_cls.return_value = mock_handler
-
- mock_store = MagicMock()
- mock_store.save_metadata = AsyncMock()
- mock_get_resolver_instance.return_value = mock_store
- mock_integration_store.create_conversation = AsyncMock()
-
- mock_jinja = MagicMock()
-
- # Act
- with patch.object(
- linear_view,
- '_get_instructions',
- new_callable=AsyncMock,
- return_value=('instructions', 'user_msg'),
- ):
- await linear_view.create_or_update_conversation(mock_jinja)
-
- # Assert - org resolution should be skipped, conversation created in personal workspace
- mock_resolve_org.assert_not_called()
- call_args = mock_get_resolver_instance.call_args
- assert call_args[0][2] is None
-
- @pytest.mark.asyncio
- @patch(
- 'integrations.linear.linear_view.resolve_org_for_repo', new_callable=AsyncMock
- )
- @patch('integrations.linear.linear_view.ProviderHandler')
- @patch(
- 'integrations.linear.linear_view.SaasConversationStore.get_resolver_instance',
- new_callable=AsyncMock,
- )
- @patch('integrations.linear.linear_view.start_conversation', new_callable=AsyncMock)
- @patch(
- 'integrations.linear.linear_view.integration_store',
- )
- async def test_resolve_org_failure_falls_back_to_personal_workspace(
- self,
- mock_integration_store,
- mock_start_convo,
- mock_get_resolver_instance,
- mock_provider_handler_cls,
- mock_resolve_org,
- linear_view,
- ):
- """When resolve_org_for_repo fails, should fall back to personal workspace."""
- # Arrange
- mock_repo = MagicMock()
- mock_repo.git_provider = ProviderType.GITHUB
- mock_handler = MagicMock()
- mock_handler.verify_repo_provider = AsyncMock(return_value=mock_repo)
- mock_provider_handler_cls.return_value = mock_handler
-
- mock_resolve_org.side_effect = Exception('Database connection failed')
- mock_store = MagicMock()
- mock_store.save_metadata = AsyncMock()
- mock_get_resolver_instance.return_value = mock_store
- mock_integration_store.create_conversation = AsyncMock()
-
- mock_jinja = MagicMock()
-
- # Act
- with patch.object(
- linear_view,
- '_get_instructions',
- new_callable=AsyncMock,
- return_value=('instructions', 'user_msg'),
- ):
- await linear_view.create_or_update_conversation(mock_jinja)
-
- # Assert - conversation should be created with resolver_org_id=None
- call_args = mock_get_resolver_instance.call_args
- assert call_args[0][2] is None
diff --git a/enterprise/tests/unit/test_saas_conversation_manager_secrets.py b/enterprise/tests/unit/test_saas_conversation_manager_secrets.py
deleted file mode 100644
index 391caa10cf..0000000000
--- a/enterprise/tests/unit/test_saas_conversation_manager_secrets.py
+++ /dev/null
@@ -1,176 +0,0 @@
-"""Tests for SaasNestedConversationManager custom secrets handling during resume."""
-
-from types import MappingProxyType
-from unittest.mock import AsyncMock, MagicMock
-
-import httpx
-import pytest
-from pydantic import SecretStr
-from server.saas_nested_conversation_manager import SaasNestedConversationManager
-
-from openhands.core.config.openhands_config import OpenHandsConfig
-from openhands.integrations.provider import CustomSecret
-from openhands.server.config.server_config import ServerConfig
-from openhands.storage.memory import InMemoryFileStore
-
-
-class MockHTTPXResponse:
- """Mock httpx.Response that behaves realistically."""
-
- def __init__(self, status_code: int, json_data: dict | None = None):
- self.status_code = status_code
- self._json_data = json_data or {}
- self.text = str(json_data) if json_data else ''
-
- def json(self):
- """Return JSON data."""
- if self._json_data:
- return self._json_data
- raise ValueError('No JSON data')
-
- def raise_for_status(self):
- """Raise an exception for 4xx/5xx status codes."""
- if self.status_code >= 400:
- # Create a proper mock response for the exception
- mock_response = MagicMock()
- mock_response.status_code = self.status_code
- mock_response.json = self.json
- mock_response.text = self.text
-
- error = httpx.HTTPStatusError(
- f"Client error '{self.status_code}' for url 'test'",
- request=MagicMock(),
- response=mock_response,
- )
- raise error
-
-
-def saas_manager():
- """Create a SaasNestedConversationManager instance for testing."""
- manager = SaasNestedConversationManager(
- sio=MagicMock(),
- config=MagicMock(spec=OpenHandsConfig),
- server_config=MagicMock(spec=ServerConfig),
- file_store=MagicMock(spec=InMemoryFileStore),
- event_retrieval=MagicMock(),
- )
- return manager
-
-
-async def test_duplicate_secrets_dont_crash_resume(saas_manager):
- """Test that duplicate secrets during resume are handled gracefully."""
- mock_client = AsyncMock(spec=httpx.AsyncClient)
-
- # Simulate resume scenario: secret already exists (400)
- mock_response = MockHTTPXResponse(
- 400, {'message': 'Secret MY_API_KEY already exists'}
- )
-
- async def mock_post(*args, **kwargs):
- return mock_response
-
- mock_client.post = AsyncMock(side_effect=mock_post)
-
- custom_secrets = MappingProxyType(
- {
- 'MY_API_KEY': CustomSecret(
- secret=SecretStr('api_key_value'),
- description='API Key that already exists on resume',
- ),
- }
- )
-
- # Should not raise despite 400 "already exists" error
- await saas_manager._setup_custom_secrets(
- client=mock_client,
- api_url='https://runtime.example.com',
- custom_secrets=custom_secrets,
- )
-
- assert mock_client.post.call_count == 1
-
-
-async def test_other_400_errors_still_fail(saas_manager):
- """Test that non-duplicate 400 errors are still raised."""
- mock_client = AsyncMock(spec=httpx.AsyncClient)
-
- # 400 error but NOT a duplicate
- mock_response = MockHTTPXResponse(400, {'message': 'Invalid secret name format'})
-
- async def mock_post(*args, **kwargs):
- return mock_response
-
- mock_client.post = AsyncMock(side_effect=mock_post)
-
- custom_secrets = MappingProxyType(
- {
- 'INVALID!NAME': CustomSecret(
- secret=SecretStr('value'), description='Secret with invalid name'
- ),
- }
- )
-
- with pytest.raises(httpx.HTTPStatusError) as exc_info:
- await saas_manager._setup_custom_secrets(
- client=mock_client,
- api_url='https://runtime.example.com',
- custom_secrets=custom_secrets,
- )
-
- assert exc_info.value.response.status_code == 400
-
-
-async def test_normal_secret_creation_still_works(saas_manager):
- """Test that normal secret creation works correctly."""
- mock_client = AsyncMock(spec=httpx.AsyncClient)
-
- # Successful creation
- mock_response = MockHTTPXResponse(200, {'message': 'Secret created'})
-
- async def mock_post(*args, **kwargs):
- return mock_response
-
- mock_client.post = AsyncMock(side_effect=mock_post)
-
- custom_secrets = MappingProxyType(
- {
- 'NEW_SECRET': CustomSecret(
- secret=SecretStr('new_value'), description='A new secret'
- ),
- }
- )
-
- await saas_manager._setup_custom_secrets(
- client=mock_client,
- api_url='https://runtime.example.com',
- custom_secrets=custom_secrets,
- )
-
- assert mock_client.post.call_count == 1
- call_args = mock_client.post.call_args_list[0]
- assert call_args[1]['json']['name'] == 'NEW_SECRET'
- assert call_args[1]['json']['value'] == 'new_value'
-
-
-async def test_handles_empty_secrets_gracefully(saas_manager):
- """Test that empty or missing secrets are handled correctly."""
- mock_client = AsyncMock(spec=httpx.AsyncClient)
-
- # Test with None
- await saas_manager._setup_custom_secrets(
- client=mock_client, api_url='https://runtime.example.com', custom_secrets=None
- )
- assert mock_client.post.call_count == 0
-
- # Test with empty dict
- await saas_manager._setup_custom_secrets(
- client=mock_client,
- api_url='https://runtime.example.com',
- custom_secrets=MappingProxyType({}),
- )
- assert mock_client.post.call_count == 0
diff --git a/enterprise/tests/unit/test_saas_nested_conversation_manager_token_refresh.py b/enterprise/tests/unit/test_saas_nested_conversation_manager_token_refresh.py
deleted file mode 100644
index 55780bd0a5..0000000000
--- a/enterprise/tests/unit/test_saas_nested_conversation_manager_token_refresh.py
+++ /dev/null
@@ -1,437 +0,0 @@
-"""
-TDD Tests for SaasNestedConversationManager token refresh functionality.
-
-This module tests the token refresh logic that prevents stale tokens from being
-sent to nested runtimes after Runtime.__init__() refreshes them.
-
-Test Coverage:
-- Token refresh with IDP user ID (GitLab webhook flow)
-- Token refresh with Keycloak user ID (Web UI flow)
-- Error handling and fallback behavior
-- Settings immutability handling
-"""
-
-from types import MappingProxyType
-from unittest.mock import AsyncMock, Mock, patch
-
-import pytest
-from pydantic import SecretStr
-
-from enterprise.server.saas_nested_conversation_manager import (
- SaasNestedConversationManager,
-)
-from openhands.integrations.provider import ProviderToken, ProviderType
-from openhands.server.session.conversation_init_data import ConversationInitData
-from openhands.storage.data_models.settings import Settings
-
-
-class TestRefreshProviderTokensAfterRuntimeInit:
- """Test suite for _refresh_provider_tokens_after_runtime_init method."""
-
- @pytest.fixture
- def conversation_manager(self):
- """Create a minimal SaasNestedConversationManager instance for testing."""
- # Arrange: Create mock dependencies
- mock_sio = Mock()
- mock_config = Mock()
- mock_config.max_concurrent_conversations = 5
- mock_server_config = Mock()
- mock_file_store = Mock()
-
- # Create manager instance
- manager = SaasNestedConversationManager(
- sio=mock_sio,
- config=mock_config,
- server_config=mock_server_config,
- file_store=mock_file_store,
- event_retrieval=Mock(),
- )
- return manager
-
- @pytest.fixture
- def gitlab_provider_token_with_user_id(self):
- """Create a GitLab ProviderToken with IDP user ID (webhook flow)."""
- return ProviderToken(
- token=SecretStr('old_token_abc123'),
- user_id='32546706', # GitLab user ID
- host=None,
- )
-
- @pytest.fixture
- def gitlab_provider_token_without_user_id(self):
- """Create a GitLab ProviderToken without IDP user ID (web UI flow)."""
- return ProviderToken(
- token=SecretStr('old_token_xyz789'),
- user_id=None,
- host=None,
- )
-
- @pytest.fixture
- def conversation_init_data_with_user_id(self, gitlab_provider_token_with_user_id):
- """Create ConversationInitData with provider token containing user_id."""
- return ConversationInitData(
- git_provider_tokens=MappingProxyType(
- {ProviderType.GITLAB: gitlab_provider_token_with_user_id}
- )
- )
-
- @pytest.fixture
- def conversation_init_data_without_user_id(
- self, gitlab_provider_token_without_user_id
- ):
- """Create ConversationInitData with provider token without user_id."""
- return ConversationInitData(
- git_provider_tokens=MappingProxyType(
- {ProviderType.GITLAB: gitlab_provider_token_without_user_id}
- )
- )
-
- @pytest.mark.asyncio
- async def test_returns_original_settings_when_not_conversation_init_data(
- self, conversation_manager
- ):
- """
- Test: Returns original settings when not ConversationInitData.
-
- Arrange: Create a Settings object (not ConversationInitData)
- Act: Call _refresh_provider_tokens_after_runtime_init
- Assert: Returns the same settings object unchanged
- """
- # Arrange
- settings = Settings()
- sid = 'test_session_123'
-
- # Act
- result = await conversation_manager._refresh_provider_tokens_after_runtime_init(
- settings, sid
- )
-
- # Assert
- assert result is settings
-
- @pytest.mark.asyncio
- async def test_returns_original_settings_when_no_provider_tokens(
- self, conversation_manager
- ):
- """
- Test: Returns original settings when no provider tokens present.
-
- Arrange: Create ConversationInitData without git_provider_tokens
- Act: Call _refresh_provider_tokens_after_runtime_init
- Assert: Returns the same settings object unchanged
- """
- # Arrange
- settings = ConversationInitData(git_provider_tokens=None)
- sid = 'test_session_456'
-
- # Act
- result = await conversation_manager._refresh_provider_tokens_after_runtime_init(
- settings, sid
- )
-
- # Assert
- assert result is settings
-
- @pytest.mark.asyncio
- async def test_refreshes_token_with_idp_user_id(
- self, conversation_manager, conversation_init_data_with_user_id
- ):
- """
- Test: Refreshes token using IDP user ID (GitLab webhook flow).
-
- Arrange: ConversationInitData with GitLab token containing user_id
- Act: Call _refresh_provider_tokens_after_runtime_init with mocked TokenManager
- Assert: Token is refreshed using get_idp_token_from_idp_user_id
- """
- # Arrange
- sid = 'test_session_789'
- fresh_token = 'fresh_token_def456'
-
- with patch(
- 'enterprise.server.saas_nested_conversation_manager.TokenManager'
- ) as mock_token_manager_class:
- mock_token_manager = AsyncMock()
- mock_token_manager.get_idp_token_from_idp_user_id = AsyncMock(
- return_value=fresh_token
- )
- mock_token_manager_class.return_value = mock_token_manager
-
- # Act
- result = (
- await conversation_manager._refresh_provider_tokens_after_runtime_init(
- conversation_init_data_with_user_id, sid
- )
- )
-
- # Assert
- mock_token_manager.get_idp_token_from_idp_user_id.assert_called_once_with(
- '32546706', ProviderType.GITLAB
- )
- assert (
- result.git_provider_tokens[ProviderType.GITLAB].token.get_secret_value()
- == fresh_token
- )
- assert result.git_provider_tokens[ProviderType.GITLAB].user_id == '32546706'
-
- @pytest.mark.asyncio
- async def test_refreshes_token_with_keycloak_user_id(
- self, conversation_manager, conversation_init_data_without_user_id
- ):
- """
- Test: Refreshes token using Keycloak user ID (Web UI flow).
-
- Arrange: ConversationInitData without IDP user_id, but with Keycloak user_id
- Act: Call _refresh_provider_tokens_after_runtime_init with mocked TokenManager
- Assert: Token is refreshed using load_offline_token + get_idp_token_from_offline_token
- """
- # Arrange
- sid = 'test_session_101'
- keycloak_user_id = 'keycloak_user_abc'
- offline_token = 'offline_token_xyz'
- fresh_token = 'fresh_token_ghi789'
-
- with patch(
- 'enterprise.server.saas_nested_conversation_manager.TokenManager'
- ) as mock_token_manager_class:
- mock_token_manager = AsyncMock()
- mock_token_manager.load_offline_token = AsyncMock(
- return_value=offline_token
- )
- mock_token_manager.get_idp_token_from_offline_token = AsyncMock(
- return_value=fresh_token
- )
- mock_token_manager_class.return_value = mock_token_manager
-
- # Act
- result = (
- await conversation_manager._refresh_provider_tokens_after_runtime_init(
- conversation_init_data_without_user_id, sid, keycloak_user_id
- )
- )
-
- # Assert
- mock_token_manager.load_offline_token.assert_called_once_with(
- keycloak_user_id
- )
- mock_token_manager.get_idp_token_from_offline_token.assert_called_once_with(
- offline_token, ProviderType.GITLAB
- )
- assert (
- result.git_provider_tokens[ProviderType.GITLAB].token.get_secret_value()
- == fresh_token
- )
- assert result.git_provider_tokens[ProviderType.GITLAB].user_id is None
-
- @pytest.mark.asyncio
- async def test_keeps_original_token_when_refresh_fails(
- self, conversation_manager, conversation_init_data_with_user_id
- ):
- """
- Test: Keeps original token when refresh fails (error handling).
-
- Arrange: ConversationInitData with token, TokenManager raises exception
- Act: Call _refresh_provider_tokens_after_runtime_init
- Assert: Original token is preserved, no exception raised
- """
- # Arrange
- sid = 'test_session_error'
- original_token = conversation_init_data_with_user_id.git_provider_tokens[
- ProviderType.GITLAB
- ].token.get_secret_value()
-
- with patch(
- 'enterprise.server.saas_nested_conversation_manager.TokenManager'
- ) as mock_token_manager_class:
- mock_token_manager = AsyncMock()
- mock_token_manager.get_idp_token_from_idp_user_id = AsyncMock(
- side_effect=Exception('Token refresh failed')
- )
- mock_token_manager_class.return_value = mock_token_manager
-
- # Act
- result = (
- await conversation_manager._refresh_provider_tokens_after_runtime_init(
- conversation_init_data_with_user_id, sid
- )
- )
-
- # Assert
- assert (
- result.git_provider_tokens[ProviderType.GITLAB].token.get_secret_value()
- == original_token
- )
-
- @pytest.mark.asyncio
- async def test_keeps_original_token_when_no_fresh_token_available(
- self, conversation_manager, conversation_init_data_with_user_id
- ):
- """
- Test: Keeps original token when no fresh token is available.
-
- Arrange: ConversationInitData with token, TokenManager returns None
- Act: Call _refresh_provider_tokens_after_runtime_init
- Assert: Original token is preserved
- """
- # Arrange
- sid = 'test_session_no_fresh'
- original_token = conversation_init_data_with_user_id.git_provider_tokens[
- ProviderType.GITLAB
- ].token.get_secret_value()
-
- with patch(
- 'enterprise.server.saas_nested_conversation_manager.TokenManager'
- ) as mock_token_manager_class:
- mock_token_manager = AsyncMock()
- mock_token_manager.get_idp_token_from_idp_user_id = AsyncMock(
- return_value=None
- )
- mock_token_manager_class.return_value = mock_token_manager
-
- # Act
- result = (
- await conversation_manager._refresh_provider_tokens_after_runtime_init(
- conversation_init_data_with_user_id, sid
- )
- )
-
- # Assert
- assert (
- result.git_provider_tokens[ProviderType.GITLAB].token.get_secret_value()
- == original_token
- )
-
- @pytest.mark.asyncio
- async def test_creates_new_settings_object_preserving_immutability(
- self, conversation_manager, conversation_init_data_with_user_id
- ):
- """
- Test: Creates new settings object (respects Pydantic frozen fields).
-
- Arrange: ConversationInitData with frozen git_provider_tokens field
- Act: Call _refresh_provider_tokens_after_runtime_init
- Assert: Returns a new ConversationInitData object, not the same instance
- """
- # Arrange
- sid = 'test_session_immutable'
- fresh_token = 'fresh_token_new'
-
- with patch(
- 'enterprise.server.saas_nested_conversation_manager.TokenManager'
- ) as mock_token_manager_class:
- mock_token_manager = AsyncMock()
- mock_token_manager.get_idp_token_from_idp_user_id = AsyncMock(
- return_value=fresh_token
- )
- mock_token_manager_class.return_value = mock_token_manager
-
- # Act
- result = (
- await conversation_manager._refresh_provider_tokens_after_runtime_init(
- conversation_init_data_with_user_id, sid
- )
- )
-
- # Assert
- assert result is not conversation_init_data_with_user_id
- assert isinstance(result, ConversationInitData)
-
- @pytest.mark.asyncio
- async def test_handles_multiple_providers(self, conversation_manager):
- """
- Test: Handles multiple provider tokens correctly.
-
- Arrange: ConversationInitData with both GitLab and GitHub tokens
- Act: Call _refresh_provider_tokens_after_runtime_init
- Assert: Both tokens are refreshed independently
- """
- # Arrange
- sid = 'test_session_multi'
- gitlab_token = ProviderToken(
- token=SecretStr('old_gitlab_token'), user_id='gitlab_user_123', host=None
- )
- github_token = ProviderToken(
- token=SecretStr('old_github_token'), user_id='github_user_456', host=None
- )
- settings = ConversationInitData(
- git_provider_tokens=MappingProxyType(
- {ProviderType.GITLAB: gitlab_token, ProviderType.GITHUB: github_token}
- )
- )
-
- fresh_gitlab_token = 'fresh_gitlab_token'
- fresh_github_token = 'fresh_github_token'
-
- with patch(
- 'enterprise.server.saas_nested_conversation_manager.TokenManager'
- ) as mock_token_manager_class:
- mock_token_manager = AsyncMock()
-
- async def mock_get_token(user_id, provider_type):
- if provider_type == ProviderType.GITLAB:
- return fresh_gitlab_token
- elif provider_type == ProviderType.GITHUB:
- return fresh_github_token
- return None
-
- mock_token_manager.get_idp_token_from_idp_user_id = AsyncMock(
- side_effect=mock_get_token
- )
- mock_token_manager_class.return_value = mock_token_manager
-
- # Act
- result = (
- await conversation_manager._refresh_provider_tokens_after_runtime_init(
- settings, sid
- )
- )
-
- # Assert
- assert (
- result.git_provider_tokens[ProviderType.GITLAB].token.get_secret_value()
- == fresh_gitlab_token
- )
- assert (
- result.git_provider_tokens[ProviderType.GITHUB].token.get_secret_value()
- == fresh_github_token
- )
- assert mock_token_manager.get_idp_token_from_idp_user_id.call_count == 2
-
- @pytest.mark.asyncio
- async def test_preserves_token_host_field(self, conversation_manager):
- """
- Test: Preserves the host field from original token.
-
- Arrange: ProviderToken with custom host value
- Act: Call _refresh_provider_tokens_after_runtime_init
- Assert: Host field is preserved in the refreshed token
- """
- # Arrange
- sid = 'test_session_host'
- custom_host = 'gitlab.example.com'
- token_with_host = ProviderToken(
- token=SecretStr('old_token'), user_id='user_789', host=custom_host
- )
- settings = ConversationInitData(
- git_provider_tokens=MappingProxyType({ProviderType.GITLAB: token_with_host})
- )
-
- fresh_token = 'fresh_token_with_host'
-
- with patch(
- 'enterprise.server.saas_nested_conversation_manager.TokenManager'
- ) as mock_token_manager_class:
- mock_token_manager = AsyncMock()
- mock_token_manager.get_idp_token_from_idp_user_id = AsyncMock(
- return_value=fresh_token
- )
- mock_token_manager_class.return_value = mock_token_manager
-
- # Act
- result = (
- await conversation_manager._refresh_provider_tokens_after_runtime_init(
- settings, sid
- )
- )
-
- # Assert
- assert result.git_provider_tokens[ProviderType.GITLAB].host == custom_host
diff --git a/enterprise/tests/unit/test_slack_callback_processor.py b/enterprise/tests/unit/test_slack_callback_processor.py
deleted file mode 100644
index 5cfb81e0b9..0000000000
--- a/enterprise/tests/unit/test_slack_callback_processor.py
+++ /dev/null
@@ -1,454 +0,0 @@
-"""
-Tests for the SlackCallbackProcessor.
-"""
-
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pytest
-from integrations.models import Message
-from server.conversation_callback_processor.slack_callback_processor import (
- SlackCallbackProcessor,
-)
-from storage.conversation_callback import ConversationCallback
-
-from openhands.core.schema.agent import AgentState
-from openhands.events.action import MessageAction
-from openhands.events.observation.agent import AgentStateChangedObservation
-from openhands.server.shared import conversation_manager
-
-
-def slack_callback_processor():
- """Create a SlackCallbackProcessor instance for testing."""
- return SlackCallbackProcessor(
- slack_user_id='test_slack_user_id',
- channel_id='test_channel_id',
- message_ts='test_message_ts',
- thread_ts='test_thread_ts',
- team_id='test_team_id',
- )
-
-
-def agent_state_changed_observation():
- """Create an AgentStateChangedObservation for testing."""
- return AgentStateChangedObservation('', AgentState.AWAITING_USER_INPUT)
-
-
-def conversation_callback():
- """Create a ConversationCallback for testing."""
- callback = MagicMock(spec=ConversationCallback)
- return callback
-
-
-class TestSlackCallbackProcessor:
- """Test the SlackCallbackProcessor class."""
-
- @patch(
- 'server.conversation_callback_processor.slack_callback_processor.get_summary_instruction'
- )
- @patch(
- 'server.conversation_callback_processor.slack_callback_processor.conversation_manager'
- )
- @patch(
- 'server.conversation_callback_processor.slack_callback_processor.get_last_user_msg_from_conversation_manager'
- )
- @patch(
- 'server.conversation_callback_processor.slack_callback_processor.event_to_dict'
- )
- async def test_call_with_send_summary_instruction(
- self,
- mock_event_to_dict,
- mock_get_last_user_msg,
- mock_conversation_manager,
- mock_get_summary_instruction,
- slack_callback_processor,
- agent_state_changed_observation,
- conversation_callback,
- ):
- """Test the __call__ method when send_summary_instruction is True."""
- # Setup mocks
- mock_get_summary_instruction.return_value = (
- 'Please summarize this conversation.'
- )
- mock_msg = MagicMock()
- mock_msg.id = 126
- mock_msg.content = 'Hello'
- mock_get_last_user_msg.return_value = [mock_msg] # Mock message with ID
- mock_conversation_manager.send_event_to_conversation = AsyncMock()
- mock_event_to_dict.return_value = {
- 'type': 'message_action',
- 'content': 'Please summarize this conversation.',
- }
-
- # Call the method
- await slack_callback_processor(
- callback=conversation_callback,
- observation=agent_state_changed_observation,
- )
-
- # Verify the behavior
- mock_get_summary_instruction.assert_called_once()
- mock_event_to_dict.assert_called_once()
- assert isinstance(mock_event_to_dict.call_args[0][0], MessageAction)
- mock_conversation_manager.send_event_to_conversation.assert_called_once_with(
- conversation_callback.conversation_id, mock_event_to_dict.return_value
- )
-
- # Verify the last_user_msg_id was updated
- assert slack_callback_processor.last_user_msg_id == 126
-
- # Verify the callback was updated and saved
- conversation_callback.set_processor.assert_called_once_with(
- slack_callback_processor
- )
-
- @patch(
- 'server.conversation_callback_processor.slack_callback_processor.extract_summary_from_conversation_manager'
- )
- @patch(
- 'server.conversation_callback_processor.slack_callback_processor.get_last_user_msg_from_conversation_manager'
- )
- @patch('server.conversation_callback_processor.slack_callback_processor.asyncio')
- async def test_call_with_extract_summary(
- self,
- mock_asyncio,
- mock_get_last_user_msg,
- mock_extract_summary,
- slack_callback_processor,
- agent_state_changed_observation,
- conversation_callback,
- ):
- """Test the __call__ method when last message is summary instruction."""
- # Setup - simulate that last message was the summary instruction
- mock_last_msg = MagicMock()
- mock_last_msg.id = 127
- mock_last_msg.content = 'Please summarize this conversation.'
- mock_get_last_user_msg.return_value = [mock_last_msg]
- mock_extract_summary.return_value = 'This is a summary of the conversation.'
-
- # Mock get_summary_instruction to return the same content
- with patch(
- 'server.conversation_callback_processor.slack_callback_processor.get_summary_instruction',
- return_value='Please summarize this conversation.',
- ):
- # Call the method
- await slack_callback_processor(
- callback=conversation_callback,
- observation=agent_state_changed_observation,
- )
-
- # Verify the behavior
- mock_extract_summary.assert_called_once_with(
- conversation_manager, conversation_callback.conversation_id
- )
- mock_asyncio.create_task.assert_called_once()
-
- # Verify the last_user_msg_id was updated
- assert slack_callback_processor.last_user_msg_id == 127
-
- # Verify the callback was updated and saved
- conversation_callback.set_processor.assert_called_once_with(
- slack_callback_processor
- )
-
- async def test_call_with_error_agent_state(
- self, slack_callback_processor, conversation_callback
- ):
- """Test the __call__ method when agent state is ERROR."""
- # Create an observation with ERROR state
- observation = AgentStateChangedObservation(
- content='', agent_state=AgentState.ERROR, reason=''
- )
-
- # Call the method
- await slack_callback_processor(
- callback=conversation_callback, observation=observation
- )
-
- # Verify that nothing happens when agent state is ERROR (method returns early)
-
- @patch(
- 'server.conversation_callback_processor.slack_callback_processor.extract_summary_from_conversation_manager'
- )
- @patch(
- 'server.conversation_callback_processor.slack_callback_processor.get_last_user_msg_from_conversation_manager'
- )
- @patch('server.conversation_callback_processor.slack_callback_processor.asyncio')
- async def test_call_with_completed_agent_state(
- self,
- mock_asyncio,
- mock_get_last_user_msg,
- mock_extract_summary,
- slack_callback_processor,
- conversation_callback,
- ):
- """Test the __call__ method when agent state is COMPLETED."""
- # Setup - simulate that last message was the summary instruction
- mock_last_msg = MagicMock()
- mock_last_msg.id = 124
- mock_last_msg.content = 'Please summarize this conversation.'
- mock_get_last_user_msg.return_value = [mock_last_msg]
- mock_extract_summary.return_value = (
- 'This is a summary of the completed conversation.'
- )
-
- # Create an observation with FINISHED state (COMPLETED doesn't exist)
- observation = AgentStateChangedObservation(
- content='', agent_state=AgentState.FINISHED, reason=''
- )
-
- # Mock get_summary_instruction to return the same content
- with patch(
- 'server.conversation_callback_processor.slack_callback_processor.get_summary_instruction',
- return_value='Please summarize this conversation.',
- ):
- # Call the method
- await slack_callback_processor(
- callback=conversation_callback, observation=observation
- )
-
- # Verify the behavior
- mock_extract_summary.assert_called_once_with(
- conversation_manager, conversation_callback.conversation_id
- )
- mock_asyncio.create_task.assert_called_once()
-
- # Verify the last_user_msg_id was updated
- assert slack_callback_processor.last_user_msg_id == 124
-
- # Verify the callback was updated and saved
- conversation_callback.set_processor.assert_called_once_with(
- slack_callback_processor
- )
-
- @patch(
- 'server.conversation_callback_processor.slack_callback_processor.slack_manager'
- )
- async def test_send_message_to_slack(
- self, mock_slack_manager, slack_callback_processor
- ):
- """Test the _send_message_to_slack method."""
- # Setup mocks
- mock_slack_user = MagicMock()
- mock_saas_user_auth = MagicMock()
- mock_slack_view = MagicMock()
-
- # Mock the authenticate_user method on slack_manager
- mock_slack_manager.authenticate_user = AsyncMock(
- return_value=(mock_slack_user, mock_saas_user_auth)
- )
-
- # Mock the SlackFactory (async method)
- with patch(
- 'server.conversation_callback_processor.slack_callback_processor.SlackFactory'
- ) as mock_slack_factory:
- mock_slack_factory.create_slack_view_from_payload = AsyncMock(
- return_value=mock_slack_view
- )
- mock_slack_manager.send_message = AsyncMock()
-
- # Call the method
- await slack_callback_processor._send_message_to_slack('Test message')
-
- # Verify the behavior
- mock_slack_manager.authenticate_user.assert_called_once_with(
- slack_callback_processor.slack_user_id
- )
-
- # Check that the Message object was created correctly
- message_call = mock_slack_factory.create_slack_view_from_payload.call_args[
- 0
- ][0]
- assert isinstance(message_call, Message)
- assert (
- message_call.message['slack_user_id']
- == slack_callback_processor.slack_user_id
- )
- assert (
- message_call.message['channel_id']
- == slack_callback_processor.channel_id
- )
- assert (
- message_call.message['message_ts']
- == slack_callback_processor.message_ts
- )
- assert (
- message_call.message['thread_ts'] == slack_callback_processor.thread_ts
- )
- assert message_call.message['team_id'] == slack_callback_processor.team_id
-
- # Verify send_message was called with the string directly
- mock_slack_manager.send_message.assert_called_once_with(
- 'Test message', mock_slack_view
- )
-
- @patch('server.conversation_callback_processor.slack_callback_processor.logger')
- async def test_send_message_to_slack_exception(
- self, mock_logger, slack_callback_processor
- ):
- """Test the _send_message_to_slack method when an exception occurs."""
- # Setup mock to raise an exception
- with patch(
- 'server.conversation_callback_processor.slack_callback_processor.slack_manager'
- ) as mock_slack_manager:
- mock_slack_manager.authenticate_user = AsyncMock(
- side_effect=Exception('Test exception')
- )
-
- # Call the method
- await slack_callback_processor._send_message_to_slack('Test message')
-
- # Verify that the exception was caught and logged
- mock_logger.error.assert_called_once()
- assert (
- 'Failed to send summary message: Test exception'
- in mock_logger.error.call_args[0][0]
- )
-
- @patch(
- 'server.conversation_callback_processor.slack_callback_processor.get_summary_instruction'
- )
- @patch(
- 'server.conversation_callback_processor.slack_callback_processor.conversation_manager'
- )
- @patch('server.conversation_callback_processor.slack_callback_processor.logger')
- async def test_call_with_exception(
- self,
- mock_logger,
- mock_conversation_manager,
- mock_get_summary_instruction,
- slack_callback_processor,
- agent_state_changed_observation,
- conversation_callback,
- ):
- """Test the __call__ method when an exception occurs."""
- # Setup mock to raise an exception
- mock_get_summary_instruction.side_effect = Exception('Test exception')
-
- # Call the method
- await slack_callback_processor(
- callback=conversation_callback,
- observation=agent_state_changed_observation,
- )
-
- # Verify that the exception was caught and logged
- mock_logger.error.assert_called_once()
-
- def test_model_validation(self):
- """Test the model validation of SlackCallbackProcessor."""
- # Test with all required fields
- processor = SlackCallbackProcessor(
- slack_user_id='test_user',
- channel_id='test_channel',
- message_ts='test_message_ts',
- thread_ts='test_thread_ts',
- team_id='test_team_id',
- )
- assert processor.slack_user_id == 'test_user'
- assert processor.channel_id == 'test_channel'
- assert processor.message_ts == 'test_message_ts'
- assert processor.thread_ts == 'test_thread_ts'
- assert processor.team_id == 'test_team_id'
- assert processor.last_user_msg_id is None
-
- # Test with last_user_msg_id provided
- processor_with_msg_id = SlackCallbackProcessor(
- slack_user_id='test_user',
- channel_id='test_channel',
- message_ts='test_message_ts',
- thread_ts='test_thread_ts',
- team_id='test_team_id',
- last_user_msg_id=456,
- )
- assert processor_with_msg_id.last_user_msg_id == 456
-
- def test_serialization_deserialization(self):
- """Test serialization and deserialization of SlackCallbackProcessor."""
- # Create a processor
- original_processor = SlackCallbackProcessor(
- slack_user_id='test_user',
- channel_id='test_channel',
- message_ts='test_message_ts',
- thread_ts='test_thread_ts',
- team_id='test_team_id',
- last_user_msg_id=125,
- )
-
- # Serialize to JSON
- json_data = original_processor.model_dump_json()
-
- # Deserialize from JSON
- deserialized_processor = SlackCallbackProcessor.model_validate_json(json_data)
-
- # Verify fields match
- assert deserialized_processor.slack_user_id == original_processor.slack_user_id
- assert deserialized_processor.channel_id == original_processor.channel_id
- assert deserialized_processor.message_ts == original_processor.message_ts
- assert deserialized_processor.thread_ts == original_processor.thread_ts
- assert deserialized_processor.team_id == original_processor.team_id
- assert (
- deserialized_processor.last_user_msg_id
- == original_processor.last_user_msg_id
- )
-
- @patch(
- 'server.conversation_callback_processor.slack_callback_processor.get_last_user_msg_from_conversation_manager'
- )
- @patch('server.conversation_callback_processor.slack_callback_processor.logger')
- async def test_call_with_unchanged_message_id(
- self,
- mock_logger,
- mock_get_last_user_msg,
- slack_callback_processor,
- agent_state_changed_observation,
- conversation_callback,
- ):
- """Test the __call__ method when the message ID hasn't changed."""
- # Setup - simulate that the message ID hasn't changed
- mock_last_msg = MagicMock()
- mock_last_msg.id = 123
- mock_last_msg.content = 'Hello'
- mock_get_last_user_msg.return_value = [mock_last_msg]
-
- # Set the last_user_msg_id to the same value
- slack_callback_processor.last_user_msg_id = 123
-
- # Call the method
- await slack_callback_processor(
- callback=conversation_callback,
- observation=agent_state_changed_observation,
- )
-
- # Verify that the method returned early and no further processing was done
- # Make sure we didn't update the processor or save to the database
- conversation_callback.set_processor.assert_not_called()
-
- def test_integration_with_conversation_callback(self):
- """Test integration with ConversationCallback."""
- # Create a processor
- processor = SlackCallbackProcessor(
- slack_user_id='test_user',
- channel_id='test_channel',
- message_ts='test_message_ts',
- thread_ts='test_thread_ts',
- team_id='test_team_id',
- )
-
- # Set the processor on the callback
- callback = ConversationCallback()
- callback.set_processor(processor)
-
- # Verify set_processor was called with the correct processor type
- expected_processor_type = (
- f'{SlackCallbackProcessor.__module__}.{SlackCallbackProcessor.__name__}'
- )
- assert callback.processor_type == expected_processor_type
-
- # Verify processor_json contains the serialized processor
- assert 'slack_user_id' in callback.processor_json
- assert 'channel_id' in callback.processor_json
- assert 'message_ts' in callback.processor_json
- assert 'thread_ts' in callback.processor_json
- assert 'team_id' in callback.processor_json
diff --git a/enterprise/tests/unit/test_slack_view.py b/enterprise/tests/unit/test_slack_view.py
deleted file mode 100644
index 445ebfafc1..0000000000
--- a/enterprise/tests/unit/test_slack_view.py
+++ /dev/null
@@ -1,331 +0,0 @@
-"""Tests for Slack view org routing logic.
-
-Tests that the SlackNewConversationView correctly resolves the target org
-based on claimed git organizations and passes it through V0/V1 paths.
-"""
-
-from unittest.mock import AsyncMock, MagicMock, patch
-from uuid import UUID
-
-import pytest
-from integrations.slack.slack_view import SlackNewConversationView
-from storage.slack_user import SlackUser
-
-from openhands.integrations.service_types import ProviderType
-from openhands.server.user_auth.user_auth import UserAuth
-
-CLAIMING_ORG_ID = UUID('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa')
-KEYCLOAK_USER_ID = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'
-
-
-def mock_slack_user():
- """Create a mock SlackUser."""
- user = SlackUser()
- user.slack_user_id = 'U1234567890'
- user.keycloak_user_id = KEYCLOAK_USER_ID
- user.slack_display_name = 'Test User'
- user.org_id = UUID('cccccccc-cccc-cccc-cccc-cccccccccccc')
- return user
-
-
-def mock_user_auth():
- """Create a mock UserAuth."""
- auth = MagicMock(spec=UserAuth)
- auth.get_provider_tokens = AsyncMock(
- return_value={ProviderType.GITHUB: MagicMock()}
- )
- auth.get_secrets = AsyncMock(return_value=MagicMock(custom_secrets={}))
- auth.get_access_token = AsyncMock(return_value='access-token')
- auth.get_user_id = AsyncMock(return_value=KEYCLOAK_USER_ID)
- return auth
-
-
-def slack_view(mock_slack_user, mock_user_auth):
- """Create a SlackNewConversationView instance for testing."""
- return SlackNewConversationView(
- bot_access_token='xoxb-test-token',
- user_msg='Hello OpenHands!',
- slack_user_id='U1234567890',
- slack_to_openhands_user=mock_slack_user,
- saas_user_auth=mock_user_auth,
- channel_id='C1234567890',
- message_ts='1234567890.123456',
- thread_ts=None,
- selected_repo='OpenHands/foo',
- should_extract=True,
- send_summary_instruction=True,
- conversation_id='',
- team_id='T1234567890',
- v1_enabled=False,
- )
-
-
-def slack_view_no_repo(mock_slack_user, mock_user_auth):
- """Create a SlackNewConversationView with no selected repo."""
- return SlackNewConversationView(
- bot_access_token='xoxb-test-token',
- user_msg='Hello OpenHands!',
- slack_user_id='U1234567890',
- slack_to_openhands_user=mock_slack_user,
- saas_user_auth=mock_user_auth,
- channel_id='C1234567890',
- message_ts='1234567890.123456',
- thread_ts=None,
- selected_repo=None,
- should_extract=True,
- send_summary_instruction=True,
- conversation_id='',
- team_id='T1234567890',
- v1_enabled=False,
- )
-
-
-class TestSlackV0ConversationRouting:
- """Test V0 conversation routing logic in Slack integration."""
-
- @pytest.mark.asyncio
- @patch(
- 'integrations.slack.slack_view.is_v1_enabled_for_slack_resolver',
- new_callable=AsyncMock,
- return_value=False,
- )
- @patch('integrations.slack.slack_view.resolve_org_for_repo', new_callable=AsyncMock)
- @patch('integrations.slack.slack_view.ProviderHandler')
- @patch(
- 'integrations.slack.slack_view.SaasConversationStore.get_resolver_instance',
- new_callable=AsyncMock,
- )
- @patch('integrations.slack.slack_view.start_conversation', new_callable=AsyncMock)
- async def test_v0_passes_resolver_org_id(
- self,
- mock_start_convo,
- mock_get_resolver_instance,
- mock_provider_handler_cls,
- mock_resolve_org,
- mock_v1_enabled,
- slack_view,
- ):
- """V0 path should pass resolver_org_id to SaasConversationStore.get_resolver_instance."""
- # Arrange
- mock_repo = MagicMock()
- mock_repo.git_provider = ProviderType.GITHUB
- mock_handler = MagicMock()
- mock_handler.verify_repo_provider = AsyncMock(return_value=mock_repo)
- mock_provider_handler_cls.return_value = mock_handler
-
- mock_resolve_org.return_value = CLAIMING_ORG_ID
- mock_store = MagicMock()
- mock_store.save_metadata = AsyncMock()
- mock_get_resolver_instance.return_value = mock_store
- mock_start_convo.return_value = MagicMock(conversation_id='test-conv-id')
-
- mock_jinja = MagicMock()
-
- # Act
- with (
- patch.object(
- slack_view,
- '_get_instructions',
- new_callable=AsyncMock,
- return_value=('msg', 'instructions'),
- ),
- patch.object(slack_view, 'save_slack_convo', new_callable=AsyncMock),
- ):
- await slack_view.create_or_update_conversation(mock_jinja)
-
- # Assert
- mock_resolve_org.assert_called_once_with(
- provider='github',
- full_repo_name='OpenHands/foo',
- keycloak_user_id=KEYCLOAK_USER_ID,
- )
- mock_get_resolver_instance.assert_called_once()
- call_args = mock_get_resolver_instance.call_args
- assert call_args[0][1] == KEYCLOAK_USER_ID # user_id
- assert call_args[0][2] == CLAIMING_ORG_ID # resolver_org_id
- mock_store.save_metadata.assert_called_once()
- saved_metadata = mock_store.save_metadata.call_args[0][0]
- assert saved_metadata.git_provider == ProviderType.GITHUB
-
- @pytest.mark.asyncio
- @patch(
- 'integrations.slack.slack_view.is_v1_enabled_for_slack_resolver',
- new_callable=AsyncMock,
- return_value=False,
- )
- @patch('integrations.slack.slack_view.resolve_org_for_repo', new_callable=AsyncMock)
- @patch('integrations.slack.slack_view.ProviderHandler')
- @patch(
- 'integrations.slack.slack_view.SaasConversationStore.get_resolver_instance',
- new_callable=AsyncMock,
- )
- @patch('integrations.slack.slack_view.start_conversation', new_callable=AsyncMock)
- async def test_v0_passes_none_when_no_claim(
- self,
- mock_start_convo,
- mock_get_resolver_instance,
- mock_provider_handler_cls,
- mock_resolve_org,
- mock_v1_enabled,
- slack_view,
- ):
- """V0 path should pass resolver_org_id=None when no claim exists."""
- # Arrange
- mock_repo = MagicMock()
- mock_repo.git_provider = ProviderType.GITHUB
- mock_handler = MagicMock()
- mock_handler.verify_repo_provider = AsyncMock(return_value=mock_repo)
- mock_provider_handler_cls.return_value = mock_handler
-
- mock_resolve_org.return_value = None
- mock_store = MagicMock()
- mock_store.save_metadata = AsyncMock()
- mock_get_resolver_instance.return_value = mock_store
- mock_start_convo.return_value = MagicMock(conversation_id='test-conv-id')
-
- mock_jinja = MagicMock()
-
- # Act
- with (
- patch.object(
- slack_view,
- '_get_instructions',
- new_callable=AsyncMock,
- return_value=('msg', 'instructions'),
- ),
- patch.object(slack_view, 'save_slack_convo', new_callable=AsyncMock),
- ):
- await slack_view.create_or_update_conversation(mock_jinja)
-
- # Assert
- call_args = mock_get_resolver_instance.call_args
- assert call_args[0][2] is None # resolver_org_id is None
-
-
-class TestSlackV1ConversationRouting:
- """Test V1 conversation routing logic in Slack integration."""
-
- @pytest.mark.asyncio
- @patch(
- 'integrations.slack.slack_view.is_v1_enabled_for_slack_resolver',
- new_callable=AsyncMock,
- return_value=True,
- )
- @patch('integrations.slack.slack_view.resolve_org_for_repo', new_callable=AsyncMock)
- @patch('integrations.slack.slack_view.ProviderHandler')
- @patch('integrations.slack.slack_view.get_app_conversation_service')
- @patch('integrations.slack.slack_view.ResolverUserContext')
- async def test_v1_passes_resolver_org_id_to_context(
- self,
- mock_resolver_ctx_cls,
- mock_get_service,
- mock_provider_handler_cls,
- mock_resolve_org,
- mock_v1_enabled,
- slack_view,
- ):
- """V1 path should pass resolver_org_id to ResolverUserContext."""
- # Arrange
- mock_repo = MagicMock()
- mock_repo.git_provider = ProviderType.GITHUB
- mock_handler = MagicMock()
- mock_handler.verify_repo_provider = AsyncMock(return_value=mock_repo)
- mock_provider_handler_cls.return_value = mock_handler
-
- mock_resolve_org.return_value = CLAIMING_ORG_ID
- mock_resolver_ctx_cls.return_value = MagicMock()
-
- # Mock the async context manager for app_conversation_service
- mock_service = MagicMock()
- mock_service.start_app_conversation = MagicMock(return_value=aiter_empty())
- mock_ctx = MagicMock()
- mock_ctx.__aenter__ = AsyncMock(return_value=mock_service)
- mock_ctx.__aexit__ = AsyncMock(return_value=None)
- mock_get_service.return_value = mock_ctx
-
- mock_jinja = MagicMock()
-
- # Act
- with patch.object(
- slack_view,
- '_get_instructions',
- new_callable=AsyncMock,
- return_value=('msg', 'instructions'),
- ):
- with patch.object(slack_view, 'save_slack_convo', new_callable=AsyncMock):
- await slack_view.create_or_update_conversation(mock_jinja)
-
- # Assert
- mock_resolve_org.assert_called_once_with(
- provider='github',
- full_repo_name='OpenHands/foo',
- keycloak_user_id=KEYCLOAK_USER_ID,
- )
- mock_resolver_ctx_cls.assert_called_once_with(
- saas_user_auth=slack_view.saas_user_auth,
- resolver_org_id=CLAIMING_ORG_ID,
- )
-
-
-class TestSlackNoRepoRouting:
- """Test routing when no repository is selected."""
-
- @pytest.mark.asyncio
- @patch(
- 'integrations.slack.slack_view.is_v1_enabled_for_slack_resolver',
- new_callable=AsyncMock,
- return_value=False,
- )
- @patch('integrations.slack.slack_view.resolve_org_for_repo', new_callable=AsyncMock)
- @patch(
- 'integrations.slack.slack_view.SaasConversationStore.get_resolver_instance',
- new_callable=AsyncMock,
- )
- @patch('integrations.slack.slack_view.start_conversation', new_callable=AsyncMock)
- async def test_no_repo_skips_org_resolution(
- self,
- mock_start_convo,
- mock_get_resolver_instance,
- mock_resolve_org,
- mock_v1_enabled,
- slack_view_no_repo,
- ):
- """When selected_repo is None, org resolution should be skipped."""
- # Arrange
- mock_store = MagicMock()
- mock_store.save_metadata = AsyncMock()
- mock_get_resolver_instance.return_value = mock_store
- mock_start_convo.return_value = MagicMock(conversation_id='test-conv-id')
- mock_jinja = MagicMock()
-
- # Act
- with (
- patch.object(
- slack_view_no_repo,
- '_get_instructions',
- new_callable=AsyncMock,
- return_value=('msg', 'instructions'),
- ),
- patch.object(
- slack_view_no_repo, 'save_slack_convo', new_callable=AsyncMock
- ),
- patch.object(slack_view_no_repo, '_verify_necessary_values_are_set'),
- ):
- await slack_view_no_repo.create_or_update_conversation(mock_jinja)
-
- # Assert
- mock_resolve_org.assert_not_called()
- call_args = mock_get_resolver_instance.call_args
- assert call_args[0][2] is None # resolver_org_id is None
- saved_metadata = mock_store.save_metadata.call_args[0][0]
- assert saved_metadata.git_provider is None
-
-
-async def aiter_empty():
- """Helper: empty async iterator."""
- return
- yield # noqa: unreachable - makes this an async generator
diff --git a/openhands/server/app.py b/openhands/server/app.py
index 4ecc90f23a..ccacf82f28 100644
--- a/openhands/server/app.py
+++ b/openhands/server/app.py
@@ -8,8 +8,6 @@
# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
import contextlib
import warnings
-from contextlib import asynccontextmanager
-from typing import AsyncIterator
from fastapi.routing import Mount
@@ -27,7 +25,6 @@ from openhands.app_server.config import get_app_lifespan_service
from openhands.app_server.status.status_router import router as health_router
from openhands.integrations.service_types import AuthenticationError
from openhands.server.routes.mcp import mcp_server
-from openhands.server.shared import conversation_manager
from openhands.version import get_version
mcp_app = mcp_server.http_app(path='/mcp', stateless_http=True)
@@ -45,13 +42,7 @@ def combine_lifespans(*lifespans):
return combined_lifespan
-@asynccontextmanager
-async def _lifespan(app: FastAPI) -> AsyncIterator[None]:
- async with conversation_manager:
- yield
-
-
-lifespans = [_lifespan, mcp_app.lifespan]
+lifespans = [mcp_app.lifespan]
app_lifespan_ = get_app_lifespan_service()
if app_lifespan_:
lifespans.append(app_lifespan_.lifespan)
diff --git a/openhands/server/config/server_config.py b/openhands/server/config/server_config.py
index e7305ce214..b4dd2d66ea 100644
--- a/openhands/server/config/server_config.py
+++ b/openhands/server/config/server_config.py
@@ -30,10 +30,6 @@ class ServerConfig(ServerConfigInterface):
conversation_store_class: str = (
'openhands.storage.conversation.file_conversation_store.FileConversationStore'
)
- conversation_manager_class: str = os.environ.get(
- 'CONVERSATION_MANAGER_CLASS',
- 'openhands.server.conversation_manager.standalone_conversation_manager.StandaloneConversationManager',
- )
monitoring_listener_class: str = 'openhands.server.monitoring.MonitoringListener'
user_auth_class: str = (
'openhands.server.user_auth.default_user_auth.DefaultUserAuth'
diff --git a/openhands/server/conversation_manager/conversation_manager.py b/openhands/server/conversation_manager/conversation_manager.py
deleted file mode 100644
index 7a63233100..0000000000
--- a/openhands/server/conversation_manager/conversation_manager.py
+++ /dev/null
@@ -1,373 +0,0 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
-from __future__ import annotations
-
-from abc import ABC, abstractmethod
-
-import httpx
-import socketio
-
-from openhands.core.config import OpenHandsConfig
-from openhands.core.config.llm_config import LLMConfig
-from openhands.core.logger import openhands_logger as logger
-from openhands.events.action import MessageAction
-from openhands.server.config.server_config import ServerConfig
-from openhands.server.data_models.agent_loop_info import AgentLoopInfo
-from openhands.server.monitoring import MonitoringListener
-from openhands.server.session.agent_session import AgentSession
-from openhands.server.session.conversation import ServerConversation
-from openhands.storage.conversation.conversation_store import ConversationStore
-from openhands.storage.data_models.settings import Settings
-from openhands.storage.files import FileStore
-from openhands.utils.http_session import httpx_verify_option
-
-
-class ConversationManager(ABC):
- """Abstract base class for managing conversations in OpenHands.
-
- This class defines the interface for managing conversations, whether in standalone
- or clustered mode. It handles the lifecycle of conversations, including creation,
- attachment, detachment, and cleanup.
-
- This is an extension point in OpenHands, that applications built on it can use to modify behavior via server configuration, without modifying its code.
- Applications can provide their own
- implementation by:
- 1. Creating a class that inherits from ConversationManager
- 2. Implementing all required abstract methods
- 3. Setting server_config.conversation_manager_class to the fully qualified name
- of the implementation class
-
- The default implementation is StandaloneConversationManager, which handles
- conversations in a single-server deployment. Applications might want to provide
- their own implementation for scenarios like:
- - Clustered deployments with distributed conversation state
- - Custom persistence or caching strategies
- - Integration with external conversation management systems
- - Enhanced monitoring or logging capabilities
-
- The implementation class is instantiated via get_impl() in openhands.server.shared.py.
- """
-
- sio: socketio.AsyncServer
- config: OpenHandsConfig
- file_store: FileStore
- conversation_store: ConversationStore
-
- @abstractmethod
- async def __aenter__(self):
- """Initialize the conversation manager."""
-
- @abstractmethod
- async def __aexit__(self, exc_type, exc_value, traceback):
- """Clean up the conversation manager."""
-
- @abstractmethod
- async def attach_to_conversation(
- self, sid: str, user_id: str | None = None
- ) -> ServerConversation | None:
- """Attach to an existing conversation or create a new one."""
-
- @abstractmethod
- async def detach_from_conversation(self, conversation: ServerConversation):
- """Detach from a conversation."""
-
- @abstractmethod
- async def join_conversation(
- self,
- sid: str,
- connection_id: str,
- settings: Settings,
- user_id: str | None,
- ) -> AgentLoopInfo | None:
- """Join a conversation and return its event stream."""
-
- async def is_agent_loop_running(self, sid: str) -> bool:
- """Check if an agent loop is running for the given session ID."""
- sids = await self.get_running_agent_loops(filter_to_sids={sid})
- return bool(sids)
-
- @abstractmethod
- async def get_running_agent_loops(
- self, user_id: str | None = None, filter_to_sids: set[str] | None = None
- ) -> set[str]:
- """Get all running agent loops, optionally filtered by user ID and session IDs."""
-
- @abstractmethod
- async def get_connections(
- self, user_id: str | None = None, filter_to_sids: set[str] | None = None
- ) -> dict[str, str]:
- """Get all connections, optionally filtered by user ID and session IDs."""
-
- @abstractmethod
- async def maybe_start_agent_loop(
- self,
- sid: str,
- settings: Settings,
- user_id: str | None,
- initial_user_msg: MessageAction | None = None,
- replay_json: str | None = None,
- ) -> AgentLoopInfo:
- """Start an event loop if one is not already running"""
-
- @abstractmethod
- async def send_to_event_stream(self, connection_id: str, data: dict):
- """Send data to an event stream."""
-
- @abstractmethod
- async def send_event_to_conversation(self, sid: str, data: dict):
- """Send an event to a conversation."""
-
- @abstractmethod
- async def disconnect_from_session(self, connection_id: str):
- """Disconnect from a session."""
-
- @abstractmethod
- async def close_session(self, sid: str):
- """Close a session."""
-
- @abstractmethod
- def get_agent_session(self, sid: str) -> AgentSession | None:
- """Get the agent session for a given session ID.
-
- Args:
- sid: The session ID.
-
- Returns:
- The agent session, or None if not found.
- """
-
- @abstractmethod
- async def get_agent_loop_info(
- self, user_id: str | None = None, filter_to_sids: set[str] | None = None
- ) -> list[AgentLoopInfo]:
- """Get the AgentLoopInfo for conversations."""
-
- @abstractmethod
- async def request_llm_completion(
- self,
- sid: str,
- service_id: str,
- llm_config: LLMConfig,
- messages: list[dict[str, str]],
- ) -> str:
- """Request extraneous llm completions for a conversation"""
-
- @abstractmethod
- async def list_files(self, sid: str, path: str | None = None) -> list[str]:
- """List files in the workspace for a conversation.
-
- Args:
- sid: The session/conversation ID.
- path: Optional path to list files from. If None, lists from workspace root.
-
- Returns:
- A list of file paths.
-
- Raises:
- ValueError: If the conversation is not running (for nested managers).
- """
-
- @abstractmethod
- async def select_file(self, sid: str, file: str) -> tuple[str | None, str | None]:
- """Read a file from the workspace.
-
- Args:
- sid: The session/conversation ID.
- file: The file path relative to the workspace root.
-
- Returns:
- A tuple of (content, error). If successful, content is the file content
- and error is None. If failed, content is None and error is the error message.
-
- Raises:
- ValueError: If the conversation is not running (for nested managers).
- """
-
- @abstractmethod
- async def upload_files(
- self, sid: str, files: list[tuple[str, bytes]]
- ) -> tuple[list[str], list[dict[str, str]]]:
- """Upload files to the workspace.
-
- Args:
- sid: The session/conversation ID.
- files: List of (filename, content) tuples to upload.
-
- Returns:
- A tuple of (uploaded_files, skipped_files) where uploaded_files is a list
- of successfully uploaded file paths and skipped_files is a list of dicts
- with 'name' and 'reason' keys for files that failed to upload.
-
- Raises:
- ValueError: If the conversation is not running (for nested managers).
- """
-
- async def _fetch_list_files_from_nested(
- self,
- sid: str,
- nested_url: str,
- session_api_key: str | None,
- path: str | None = None,
- ) -> list[str]:
- """Fetch file list from a nested runtime container.
-
- This is a helper method used by nested conversation managers to make HTTP
- requests to the nested runtime's list-files endpoint.
-
- Args:
- sid: The session/conversation ID (for logging).
- nested_url: The base URL of the nested runtime.
- session_api_key: The session API key for authentication.
- path: Optional path to list files from.
-
- Returns:
- A list of file paths.
-
- Raises:
- httpx.TimeoutException: If the request times out.
- httpx.ConnectError: If unable to connect to the nested runtime.
- httpx.HTTPStatusError: If the nested runtime returns an error status.
- """
- async with httpx.AsyncClient(
- verify=httpx_verify_option(),
- headers={'X-Session-API-Key': session_api_key} if session_api_key else {},
- ) as client:
- params = {'path': path} if path else {}
- try:
- response = await client.get(f'{nested_url}/list-files', params=params)
- response.raise_for_status()
- return response.json()
- except httpx.TimeoutException:
- logger.error(
- 'Timeout fetching files from nested runtime',
- extra={'session_id': sid},
- )
- raise
- except httpx.ConnectError as e:
- logger.error(
- f'Failed to connect to nested runtime: {e}',
- extra={'session_id': sid},
- )
- raise
- except httpx.HTTPStatusError as e:
- logger.error(
- f'Nested runtime returned error: {e.response.status_code}',
- extra={'session_id': sid},
- )
- raise
-
- async def _fetch_select_file_from_nested(
- self,
- sid: str,
- nested_url: str,
- session_api_key: str | None,
- file: str,
- ) -> tuple[str | None, str | None]:
- """Fetch file content from a nested runtime container.
-
- Args:
- sid: The session/conversation ID (for logging).
- nested_url: The base URL of the nested runtime.
- session_api_key: The session API key for authentication.
- file: The file path to read.
-
- Returns:
- A tuple of (content, error).
- """
- async with httpx.AsyncClient(
- verify=httpx_verify_option(),
- headers={'X-Session-API-Key': session_api_key} if session_api_key else {},
- ) as client:
- params = {'file': file}
- try:
- response = await client.get(f'{nested_url}/select-file', params=params)
- response.raise_for_status()
- data = response.json()
- return data.get('code'), None
- except httpx.HTTPStatusError as e:
- if e.response.status_code == 415:
- return None, f'BINARY_FILE:{file}'
- error_data = e.response.json() if e.response.content else {}
- return None, error_data.get('error', str(e))
- except httpx.TimeoutException:
- logger.error(
- 'Timeout fetching file from nested runtime',
- extra={'session_id': sid},
- )
- raise
- except httpx.ConnectError as e:
- logger.error(
- f'Failed to connect to nested runtime: {e}',
- extra={'session_id': sid},
- )
- raise
-
- async def _fetch_upload_files_to_nested(
- self,
- sid: str,
- nested_url: str,
- session_api_key: str | None,
- files: list[tuple[str, bytes]],
- ) -> tuple[list[str], list[dict[str, str]]]:
- """Upload files to a nested runtime container.
-
- Args:
- sid: The session/conversation ID (for logging).
- nested_url: The base URL of the nested runtime.
- session_api_key: The session API key for authentication.
- files: List of (filename, content) tuples to upload.
-
- Returns:
- A tuple of (uploaded_files, skipped_files).
- """
- async with httpx.AsyncClient(
- verify=httpx_verify_option(),
- headers={'X-Session-API-Key': session_api_key} if session_api_key else {},
- ) as client:
- try:
- # Build multipart form data
- multipart_files = [
- ('files', (filename, content)) for filename, content in files
- ]
- response = await client.post(
- f'{nested_url}/upload-files', files=multipart_files
- )
- response.raise_for_status()
- data = response.json()
- return data.get('uploaded_files', []), data.get('skipped_files', [])
- except httpx.TimeoutException:
- logger.error(
- 'Timeout uploading files to nested runtime',
- extra={'session_id': sid},
- )
- raise
- except httpx.ConnectError as e:
- logger.error(
- f'Failed to connect to nested runtime: {e}',
- extra={'session_id': sid},
- )
- raise
- except httpx.HTTPStatusError as e:
- logger.error(
- f'Nested runtime returned error: {e.response.status_code}',
- extra={'session_id': sid},
- )
- raise
-
- @classmethod
- @abstractmethod
- def get_instance(
- cls,
- sio: socketio.AsyncServer,
- config: OpenHandsConfig,
- file_store: FileStore,
- server_config: ServerConfig,
- monitoring_listener: MonitoringListener,
- ) -> ConversationManager:
- """Get a conversation manager instance"""
diff --git a/openhands/server/conversation_manager/docker_nested_conversation_manager.py b/openhands/server/conversation_manager/docker_nested_conversation_manager.py
deleted file mode 100644
index a4b4ce71cb..0000000000
--- a/openhands/server/conversation_manager/docker_nested_conversation_manager.py
+++ /dev/null
@@ -1,709 +0,0 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
-from __future__ import annotations
-
-import asyncio
-import hashlib
-import os
-from base64 import urlsafe_b64encode
-from dataclasses import dataclass, field
-from types import MappingProxyType
-from typing import Any, cast
-
-import docker
-import httpx
-import socketio
-from docker.models.containers import Container
-
-from openhands.controller.agent import Agent
-from openhands.core.config import OpenHandsConfig
-from openhands.core.config.llm_config import LLMConfig
-from openhands.core.logger import openhands_logger as logger
-from openhands.events.action import MessageAction
-from openhands.events.nested_event_store import NestedEventStore
-from openhands.events.stream import EventStream
-from openhands.integrations.provider import PROVIDER_TOKEN_TYPE, ProviderHandler
-from openhands.runtime import get_runtime_cls
-from openhands.runtime.impl.docker.docker_runtime import DockerRuntime
-from openhands.runtime.runtime_status import RuntimeStatus
-from openhands.server.config.server_config import ServerConfig
-from openhands.server.constants import ROOM_KEY
-from openhands.server.conversation_manager.conversation_manager import (
- ConversationManager,
-)
-from openhands.server.data_models.agent_loop_info import AgentLoopInfo
-from openhands.server.monitoring import MonitoringListener
-from openhands.server.session.conversation import ServerConversation
-from openhands.server.session.conversation_init_data import ConversationInitData
-from openhands.server.session.session import WebSession as Session
-from openhands.storage.conversation.conversation_store import ConversationStore
-from openhands.storage.data_models.conversation_metadata import ConversationMetadata
-from openhands.storage.data_models.conversation_status import ConversationStatus
-from openhands.storage.data_models.settings import Settings
-from openhands.storage.files import FileStore
-from openhands.storage.locations import get_conversation_dir
-from openhands.utils.async_utils import call_sync_from_async
-from openhands.utils.http_session import httpx_verify_option
-from openhands.utils.import_utils import get_impl
-from openhands.utils.utils import create_registry_and_conversation_stats
-
-
-@dataclass
-class DockerNestedConversationManager(ConversationManager):
- """ServerConversation manager where the agent loops exist inside the docker containers."""
-
- sio: socketio.AsyncServer
- config: OpenHandsConfig
- server_config: ServerConfig
- file_store: FileStore
- docker_client: docker.DockerClient = field(default_factory=docker.from_env)
- _conversation_store_class: type[ConversationStore] | None = None
- _starting_conversation_ids: set[str] = field(default_factory=set)
- _runtime_container_image: str | None = None
-
- async def __aenter__(self):
- runtime_cls = get_runtime_cls(self.config.runtime)
- runtime_cls.setup(self.config)
- return self
-
- async def __aexit__(self, exc_type, exc_value, traceback):
- runtime_cls = get_runtime_cls(self.config.runtime)
- runtime_cls.teardown(self.config)
-
- async def attach_to_conversation(
- self, sid: str, user_id: str | None = None
- ) -> ServerConversation | None:
- # Not supported - clients should connect directly to the nested server!
- raise ValueError('unsupported_operation')
-
- async def detach_from_conversation(self, conversation: ServerConversation):
- # Not supported - clients should connect directly to the nested server!
- raise ValueError('unsupported_operation')
-
- async def join_conversation(
- self,
- sid: str,
- connection_id: str,
- settings: Settings,
- user_id: str | None,
- ) -> AgentLoopInfo:
- # Not supported - clients should connect directly to the nested server!
- raise ValueError('unsupported_operation')
-
- async def get_running_agent_loops(
- self, user_id: str | None = None, filter_to_sids: set[str] | None = None
- ) -> set[str]:
- """Get the running agent loops directly from docker."""
- containers: list[Container] = self.docker_client.containers.list()
- names = (container.name or '' for container in containers)
- conversation_ids = {
- name[len('openhands-runtime-') :]
- for name in names
- if name.startswith('openhands-runtime-')
- }
- if filter_to_sids is not None:
- conversation_ids = {
- conversation_id
- for conversation_id in conversation_ids
- if conversation_id in filter_to_sids
- }
- return conversation_ids
-
- async def get_connections(
- self, user_id: str | None = None, filter_to_sids: set[str] | None = None
- ) -> dict[str, str]:
- # We don't monitor connections outside the nested server, though we could introduce an API for this.
- results: dict[str, str] = {}
- return results
-
- async def maybe_start_agent_loop(
- self,
- sid: str,
- settings: Settings,
- user_id: str | None,
- initial_user_msg: MessageAction | None = None,
- replay_json: str | None = None,
- ) -> AgentLoopInfo:
- if not await self.is_agent_loop_running(sid):
- await self._start_agent_loop(
- sid, settings, user_id, initial_user_msg, replay_json
- )
-
- nested_url = self._get_nested_url(sid)
- session_api_key = self._get_session_api_key_for_conversation(sid)
- return AgentLoopInfo(
- conversation_id=sid,
- url=nested_url,
- session_api_key=session_api_key,
- event_store=NestedEventStore(
- base_url=nested_url,
- sid=sid,
- user_id=user_id,
- session_api_key=session_api_key,
- ),
- status=(
- ConversationStatus.STARTING
- if sid in self._starting_conversation_ids
- else ConversationStatus.RUNNING
- ),
- )
-
- async def _start_agent_loop(
- self,
- sid: str,
- settings: Settings,
- user_id: str | None,
- initial_user_msg: MessageAction | None,
- replay_json: str | None,
- ):
- logger.info(f'starting_agent_loop:{sid}', extra={'session_id': sid})
- await self.ensure_num_conversations_below_limit(sid, user_id)
- runtime = await self._create_runtime(sid, user_id, settings)
- self._starting_conversation_ids.add(sid)
- try:
- # Build the runtime container image if it is missing
- await call_sync_from_async(runtime.maybe_build_runtime_container_image)
- self._runtime_container_image = runtime.runtime_container_image
-
- # check that the container already exists...
- if await self._start_existing_container(runtime):
- self._starting_conversation_ids.discard(sid)
- return
-
- # initialize the container but dont wait for it to start
- await call_sync_from_async(runtime.init_container)
-
- # Start the conversation in a background task.
- asyncio.create_task(
- self._start_conversation(
- sid,
- settings,
- runtime,
- initial_user_msg,
- replay_json,
- runtime.api_url,
- )
- )
-
- except Exception:
- self._starting_conversation_ids.discard(sid)
- raise
-
- async def _start_conversation(
- self,
- sid: str,
- settings: Settings,
- runtime: DockerRuntime,
- initial_user_msg: MessageAction | None,
- replay_json: str | None,
- api_url: str,
- ):
- try:
- await call_sync_from_async(runtime.wait_until_alive)
- await call_sync_from_async(runtime.setup_initial_env)
- async with httpx.AsyncClient(
- verify=httpx_verify_option(),
- headers={
- 'X-Session-API-Key': self._get_session_api_key_for_conversation(sid)
- },
- ) as client:
- # setup the settings...
- settings_json = settings.model_dump(context={'expose_secrets': True})
- settings_json.pop('custom_secrets', None)
- settings_json.pop('git_provider_tokens', None)
- if settings_json.get('git_provider'):
- settings_json['git_provider'] = settings_json['git_provider'].value
- settings_json.pop('secrets_store', None) or {}
- response = await client.post(
- f'{api_url}/api/settings', json=settings_json
- )
- response.raise_for_status()
-
- # Setup provider tokens
- provider_handler = self._get_provider_handler(settings)
- provider_tokens = provider_handler.provider_tokens
- if provider_tokens:
- provider_tokens_json = {
- k.value: {
- 'token': v.token.get_secret_value(),
- 'user_id': v.user_id,
- 'host': v.host,
- }
- for k, v in provider_tokens.items()
- if v.token
- }
- response = await client.post(
- f'{api_url}/api/add-git-providers',
- json={
- 'provider_tokens': provider_tokens_json,
- },
- )
- response.raise_for_status()
-
- # Setup custom secrets
- custom_secrets = settings.custom_secrets # type: ignore
- if custom_secrets:
- for key, secret in custom_secrets.items():
- response = await client.post(
- f'{api_url}/api/secrets',
- json={
- 'name': key,
- 'description': secret.description,
- 'value': secret.secret.get_secret_value(),
- },
- )
- response.raise_for_status()
-
- init_conversation: dict[str, Any] = {
- 'initial_user_msg': (
- initial_user_msg.content
- if initial_user_msg and initial_user_msg.content
- else None
- ),
- 'image_urls': [],
- 'replay_json': replay_json,
- 'conversation_id': sid,
- }
-
- if isinstance(settings, ConversationInitData):
- init_conversation['repository'] = settings.selected_repository
- init_conversation['selected_branch'] = settings.selected_branch
- init_conversation['git_provider'] = (
- settings.git_provider.value if settings.git_provider else None
- )
-
- # Create conversation
- response = await client.post(
- f'{api_url}/api/conversations', json=init_conversation
- )
- logger.info(
- f'_start_agent_loop:{response.status_code}:{response.json()}'
- )
- response.raise_for_status()
- finally:
- self._starting_conversation_ids.discard(sid)
-
- async def send_to_event_stream(self, connection_id: str, data: dict):
- # Not supported - clients should connect directly to the nested server!
- raise ValueError('unsupported_operation')
-
- async def request_llm_completion(
- self,
- sid: str,
- service_id: str,
- llm_config: LLMConfig,
- messages: list[dict[str, str]],
- ) -> str:
- # Not supported - clients should connect directly to the nested server!
- raise ValueError('unsupported_operation')
-
- async def send_event_to_conversation(self, sid, data):
- async with httpx.AsyncClient(
- verify=httpx_verify_option(),
- headers={
- 'X-Session-API-Key': self._get_session_api_key_for_conversation(sid)
- },
- ) as client:
- nested_url = self._get_nested_url(sid)
- response = await client.post(
- f'{nested_url}/api/conversations/{sid}/events', json=data
- )
- response.raise_for_status()
-
- async def disconnect_from_session(self, connection_id: str):
- # Not supported - clients should connect directly to the nested server!
- raise ValueError('unsupported_operation')
-
- async def close_session(self, sid: str):
- # First try to graceful stop server.
- try:
- container = self.docker_client.containers.get(f'openhands-runtime-{sid}')
- except docker.errors.NotFound:
- return
- try:
- nested_url = self.get_nested_url_for_container(container)
- async with httpx.AsyncClient(
- verify=httpx_verify_option(),
- headers={
- 'X-Session-API-Key': self._get_session_api_key_for_conversation(sid)
- },
- ) as client:
- # Stop conversation
- response = await client.post(
- f'{nested_url}/api/conversations/{sid}/stop'
- )
- response.raise_for_status()
-
- # Check up to 3 times that client has closed
- for _ in range(3):
- response = await client.get(f'{nested_url}/api/conversations/{sid}')
- response.raise_for_status()
- if response.json().get('status') == 'STOPPED':
- break
- await asyncio.sleep(1)
-
- except Exception as e:
- logger.warning(
- 'error_stopping_container', extra={'sid': sid, 'error': str(e)}
- )
- container.stop()
-
- async def _get_runtime_status_from_nested_runtime(
- self, conversation_id: str, nested_url: str
- ) -> RuntimeStatus | None:
- """Get runtime status from the nested runtime via API call.
-
- Args:
- conversation_id: The conversation ID to query
- nested_url: The base URL of the nested runtime
-
- Returns:
- The runtime status if available, None otherwise
- """
- try:
- async with httpx.AsyncClient(
- verify=httpx_verify_option(),
- headers={
- 'X-Session-API-Key': self._get_session_api_key_for_conversation(
- conversation_id
- )
- },
- ) as client:
- # Query the nested runtime for conversation info
- response = await client.get(nested_url)
- if response.status_code == 200:
- conversation_data = response.json()
- runtime_status_str = conversation_data.get('runtime_status')
- if runtime_status_str:
- # Convert string back to RuntimeStatus enum
- return RuntimeStatus(runtime_status_str)
- else:
- logger.debug(
- f'Failed to get conversation info for {conversation_id}: {response.status_code}'
- )
- except ValueError:
- logger.debug(f'Invalid runtime status value: {runtime_status_str}')
- except Exception as e:
- logger.debug(f'Could not get runtime status for {conversation_id}: {e}')
-
- return None
-
- async def get_agent_loop_info(
- self, user_id: str | None = None, filter_to_sids: set[str] | None = None
- ) -> list[AgentLoopInfo]:
- results = []
- containers: list[Container] = self.docker_client.containers.list()
- for container in containers:
- if not container.name or not container.name.startswith(
- 'openhands-runtime-'
- ):
- continue
- conversation_id = container.name[len('openhands-runtime-') :]
- if filter_to_sids is not None and conversation_id not in filter_to_sids:
- continue
- nested_url = self.get_nested_url_for_container(container)
- if os.getenv('NESTED_RUNTIME_BROWSER_HOST', '') != '':
- # This should be set to http://localhost if you're running OH inside a docker container
- nested_url = nested_url.replace(
- self.config.sandbox.local_runtime_url,
- os.getenv('NESTED_RUNTIME_BROWSER_HOST', ''),
- )
-
- # Get runtime status from nested runtime
- runtime_status = await self._get_runtime_status_from_nested_runtime(
- conversation_id, nested_url
- )
-
- agent_loop_info = AgentLoopInfo(
- conversation_id=conversation_id,
- url=nested_url,
- session_api_key=self._get_session_api_key_for_conversation(
- conversation_id
- ),
- event_store=NestedEventStore(
- base_url=nested_url,
- sid=conversation_id,
- user_id=user_id,
- ),
- status=(
- ConversationStatus.STARTING
- if conversation_id in self._starting_conversation_ids
- else ConversationStatus.RUNNING
- ),
- runtime_status=runtime_status,
- )
- results.append(agent_loop_info)
- return results
-
- @classmethod
- def get_instance(
- cls,
- sio: socketio.AsyncServer,
- config: OpenHandsConfig,
- file_store: FileStore,
- server_config: ServerConfig,
- monitoring_listener: MonitoringListener,
- ) -> ConversationManager:
- return DockerNestedConversationManager(
- sio=sio,
- config=config,
- server_config=server_config,
- file_store=file_store,
- )
-
- def get_agent_session(self, sid: str):
- """Get the agent session for a given session ID.
-
- Args:
- sid: The session ID.
-
- Returns:
- The agent session, or None if not found.
- """
- raise ValueError('unsupported_operation')
-
- async def _get_conversation_store(self, user_id: str | None) -> ConversationStore:
- conversation_store_class = self._conversation_store_class
- if not conversation_store_class:
- self._conversation_store_class = conversation_store_class = get_impl(
- ConversationStore, # type: ignore
- self.server_config.conversation_store_class,
- )
- store = await conversation_store_class.get_instance(self.config, user_id)
- return store
-
- def _get_nested_url(self, sid: str) -> str:
- container = self.docker_client.containers.get(f'openhands-runtime-{sid}')
- return self.get_nested_url_for_container(container)
-
- def get_nested_url_for_container(self, container: Container) -> str:
- env = container.attrs['Config']['Env']
- container_port = int(next(e[5:] for e in env if e.startswith('port=')))
- container_name = container.name or ''
- conversation_id = container_name[len('openhands-runtime-') :]
- nested_url = f'{self.config.sandbox.local_runtime_url}:{container_port}/api/conversations/{conversation_id}'
- return nested_url
-
- def _get_session_api_key_for_conversation(self, conversation_id: str) -> str:
- jwt_secret = self.config.jwt_secret.get_secret_value() # type:ignore
- conversation_key = f'{jwt_secret}:{conversation_id}'.encode()
- session_api_key = (
- urlsafe_b64encode(hashlib.sha256(conversation_key).digest())
- .decode()
- .replace('=', '')
- )
- return session_api_key
-
- async def ensure_num_conversations_below_limit(
- self, sid: str, user_id: str | None
- ) -> None:
- response_ids = await self.get_running_agent_loops(user_id)
- if len(response_ids) >= self.config.max_concurrent_conversations:
- logger.info(
- f'too_many_sessions_for:{user_id or ""}',
- extra={'session_id': sid, 'user_id': user_id},
- )
- # Get the conversations sorted (oldest first)
- conversation_store = await self._get_conversation_store(user_id)
- conversations = await conversation_store.get_all_metadata(response_ids)
- conversations.sort(key=_last_updated_at_key, reverse=True)
-
- while len(conversations) >= self.config.max_concurrent_conversations:
- oldest_conversation_id = conversations.pop().conversation_id
- logger.debug(
- f'closing_from_too_many_sessions:{user_id or ""}:{oldest_conversation_id}',
- extra={'session_id': oldest_conversation_id, 'user_id': user_id},
- )
- # Send status message to client and close session.
- status_update_dict = {
- 'status_update': True,
- 'type': 'error',
- 'id': 'AGENT_ERROR$TOO_MANY_CONVERSATIONS',
- 'message': 'Too many conversations at once. If you are still using this one, try reactivating it by prompting the agent to continue',
- }
- await self.sio.emit(
- 'oh_event',
- status_update_dict,
- to=ROOM_KEY.format(sid=oldest_conversation_id),
- )
- await self.close_session(oldest_conversation_id)
-
- def _get_provider_handler(self, settings: Settings) -> ProviderHandler:
- provider_tokens = None
- if isinstance(settings, ConversationInitData):
- provider_tokens = settings.git_provider_tokens
- provider_handler = ProviderHandler(
- provider_tokens=provider_tokens
- or cast(PROVIDER_TOKEN_TYPE, MappingProxyType({}))
- )
- return provider_handler
-
- async def _create_runtime(
- self, sid: str, user_id: str | None, settings: Settings
- ) -> DockerRuntime:
- # This session is created here only because it is the easiest way to get a runtime, which
- # is the easiest way to create the needed docker container
-
- llm_registry, conversation_stats, config = (
- create_registry_and_conversation_stats(self.config, sid, user_id, settings)
- )
-
- session = Session(
- sid=sid,
- llm_registry=llm_registry,
- conversation_stats=conversation_stats,
- file_store=self.file_store,
- config=config,
- sio=self.sio,
- user_id=user_id,
- )
- llm_registry.retry_listner = session._notify_on_llm_retry
- agent_cls = settings.agent_settings.agent or config.default_agent
- agent_config = config.get_agent_config(agent_cls)
- agent = Agent.get_cls(agent_cls)(agent_config, llm_registry)
-
- config = config.model_copy(deep=True)
- env_vars = config.sandbox.runtime_startup_env_vars
- env_vars['CONVERSATION_MANAGER_CLASS'] = (
- 'openhands.server.conversation_manager.standalone_conversation_manager.StandaloneConversationManager'
- )
- env_vars['SERVE_FRONTEND'] = '0'
- env_vars['RUNTIME'] = 'local'
- # TODO: In the long term we may come up with a more secure strategy for user management within the nested runtime.
- env_vars['USER'] = 'openhands' if config.run_as_openhands else 'root'
- env_vars['SANDBOX_USER_ID'] = str(config.sandbox.user_id)
- env_vars['SESSION_API_KEY'] = self._get_session_api_key_for_conversation(sid)
- # We need to be able to specify the nested conversation id within the nested runtime
- env_vars['ALLOW_SET_CONVERSATION_ID'] = '1'
- env_vars['WORKSPACE_BASE'] = '/workspace'
- env_vars['SANDBOX_CLOSE_DELAY'] = '0'
- env_vars['SKIP_DEPENDENCY_CHECK'] = '1'
- env_vars['INITIAL_NUM_WARM_SERVERS'] = '1'
-
- volumes: list[str | None]
- if not config.sandbox.volumes:
- volumes = []
- else:
- volumes = [v.strip() for v in config.sandbox.volumes.split(',')]
- conversation_dir = get_conversation_dir(sid, user_id)
-
- # Set up mounted volume for conversation directory within workspace
- if config.file_store == 'local':
- # Resolve ~ from path as the docker container does not work otherwise
- file_store_path = os.path.realpath(
- os.path.expanduser(config.file_store_path)
- )
-
- volumes.append(
- f'{file_store_path}/{conversation_dir}:/root/.openhands/{conversation_dir}:rw'
- )
-
- config.sandbox.volumes = ','.join([v for v in volumes if v is not None])
- if not config.sandbox.runtime_container_image:
- config.sandbox.runtime_container_image = self._runtime_container_image
-
- # Currently this eventstream is never used and only exists because one is required in order to create a docker runtime
- event_stream = EventStream(sid, self.file_store, user_id)
-
- runtime = DockerRuntime(
- config=config,
- event_stream=event_stream,
- sid=sid,
- plugins=agent.sandbox_plugins,
- headless_mode=False,
- attach_to_existing=False,
- main_module='openhands.server',
- llm_registry=llm_registry,
- )
-
- # Hack - disable setting initial env.
- runtime.setup_initial_env = lambda: None # type:ignore
-
- return runtime
-
- async def _start_existing_container(self, runtime: DockerRuntime) -> bool:
- try:
- container = self.docker_client.containers.get(runtime.container_name)
- if container:
- status = container.status
- if status == 'exited':
- await call_sync_from_async(container.start)
- return True
- return False
- except docker.errors.NotFound:
- return False
-
- async def list_files(self, sid: str, path: str | None = None) -> list[str]:
- """List files in the workspace for a conversation.
-
- Delegates to the nested container's list-files endpoint.
-
- Args:
- sid: The session/conversation ID.
- path: Optional path to list files from. If None, lists from workspace root.
-
- Returns:
- A list of file paths.
-
- Raises:
- ValueError: If the conversation is not running.
- httpx.HTTPError: If there's an error communicating with the nested runtime.
- """
- if not await self.is_agent_loop_running(sid):
- raise ValueError(f'Conversation {sid} is not running')
-
- nested_url = self._get_nested_url(sid)
- session_api_key = self._get_session_api_key_for_conversation(sid)
-
- return await self._fetch_list_files_from_nested(
- sid, nested_url, session_api_key, path
- )
-
- async def select_file(self, sid: str, file: str) -> tuple[str | None, str | None]:
- """Read a file from the workspace via nested container.
-
- Raises:
- ValueError: If the conversation is not running.
- httpx.HTTPError: If there's an error communicating with the nested runtime.
- """
- if not await self.is_agent_loop_running(sid):
- raise ValueError(f'Conversation {sid} is not running')
-
- nested_url = self._get_nested_url(sid)
- session_api_key = self._get_session_api_key_for_conversation(sid)
-
- return await self._fetch_select_file_from_nested(
- sid, nested_url, session_api_key, file
- )
-
- async def upload_files(
- self, sid: str, files: list[tuple[str, bytes]]
- ) -> tuple[list[str], list[dict[str, str]]]:
- """Upload files to the workspace via nested container.
-
- Raises:
- ValueError: If the conversation is not running.
- httpx.HTTPError: If there's an error communicating with the nested runtime.
- """
- if not await self.is_agent_loop_running(sid):
- raise ValueError(f'Conversation {sid} is not running')
-
- nested_url = self._get_nested_url(sid)
- session_api_key = self._get_session_api_key_for_conversation(sid)
-
- return await self._fetch_upload_files_to_nested(
- sid, nested_url, session_api_key, files
- )
-
-
-def _last_updated_at_key(conversation: ConversationMetadata) -> float:
- last_updated_at = conversation.last_updated_at
- if last_updated_at is None:
- return 0.0
- return last_updated_at.timestamp()
diff --git a/openhands/server/conversation_manager/standalone_conversation_manager.py b/openhands/server/conversation_manager/standalone_conversation_manager.py
deleted file mode 100644
index a4b2efad0a..0000000000
--- a/openhands/server/conversation_manager/standalone_conversation_manager.py
+++ /dev/null
@@ -1,901 +0,0 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
-import asyncio
-import os
-import time
-from dataclasses import dataclass, field
-from datetime import datetime, timezone
-from typing import Any, Callable, Iterable
-
-import socketio
-from pathspec import PathSpec
-from pathspec.patterns import GitWildMatchPattern
-
-from openhands.core.config.llm_config import LLMConfig
-from openhands.core.config.openhands_config import OpenHandsConfig
-from openhands.core.exceptions import AgentRuntimeUnavailableError
-from openhands.core.logger import openhands_logger as logger
-from openhands.core.schema.agent import AgentState
-from openhands.core.schema.observation import ObservationType
-from openhands.events.action import FileReadAction, MessageAction
-from openhands.events.observation.commands import CmdOutputObservation
-from openhands.events.stream import EventStreamSubscriber, session_exists
-from openhands.llm.llm_registry import LLMRegistry
-from openhands.runtime import get_runtime_cls
-from openhands.server.config.server_config import ServerConfig
-from openhands.server.constants import ROOM_KEY
-from openhands.server.data_models.agent_loop_info import AgentLoopInfo
-from openhands.server.monitoring import MonitoringListener
-from openhands.server.session.agent_session import WAIT_TIME_BEFORE_CLOSE, AgentSession
-from openhands.server.session.conversation import ServerConversation
-from openhands.server.session.session import WebSession as Session
-from openhands.storage.conversation.conversation_store import ConversationStore
-from openhands.storage.data_models.conversation_metadata import ConversationMetadata
-from openhands.storage.data_models.conversation_status import ConversationStatus
-from openhands.storage.data_models.settings import Settings
-from openhands.storage.files import FileStore
-from openhands.utils.async_utils import (
- call_sync_from_async,
- run_in_loop,
- wait_all,
-)
-from openhands.utils.conversation_summary import (
- auto_generate_title,
- get_default_conversation_title,
-)
-from openhands.utils.import_utils import get_impl
-from openhands.utils.shutdown_listener import should_continue
-from openhands.utils.utils import create_registry_and_conversation_stats
-
-from .conversation_manager import ConversationManager
-
-_CLEANUP_INTERVAL = 15
-UPDATED_AT_CALLBACK_ID = 'updated_at_callback_id'
-
-
-@dataclass
-class StandaloneConversationManager(ConversationManager):
- """Default implementation of ConversationManager for single-server deployments.
-
- See ConversationManager for extensibility details.
- """
-
- sio: socketio.AsyncServer
- config: OpenHandsConfig
- file_store: FileStore
- server_config: ServerConfig
- # Defaulting monitoring_listener for temp backward compatibility.
- monitoring_listener: MonitoringListener = MonitoringListener()
- _local_agent_loops_by_sid: dict[str, Session] = field(default_factory=dict)
- _local_connection_id_to_session_id: dict[str, str] = field(default_factory=dict)
- _active_conversations: dict[str, tuple[ServerConversation, int]] = field(
- default_factory=dict
- )
- _detached_conversations: dict[str, tuple[ServerConversation, float]] = field(
- default_factory=dict
- )
- _conversations_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
- _cleanup_task: asyncio.Task | None = None
- _conversation_store_class: type[ConversationStore] | None = None
- _loop: asyncio.AbstractEventLoop | None = None
-
- async def __aenter__(self):
- # Grab a reference to the main event loop. This is the loop in which `await sio.emit` must be called
- self._loop = asyncio.get_event_loop()
- self._cleanup_task = asyncio.create_task(self._cleanup_stale())
- get_runtime_cls(self.config.runtime).setup(self.config)
- return self
-
- async def __aexit__(self, exc_type, exc_value, traceback):
- if self._cleanup_task:
- self._cleanup_task.cancel()
- self._cleanup_task = None
- get_runtime_cls(self.config.runtime).teardown(self.config)
-
- async def attach_to_conversation(
- self, sid: str, user_id: str | None = None
- ) -> ServerConversation | None:
- start_time = time.time()
- if not await session_exists(sid, self.file_store, user_id=user_id):
- return None
-
- async with self._conversations_lock:
- # Check if we have an active conversation we can reuse
- if sid in self._active_conversations:
- conversation, count = self._active_conversations[sid]
- self._active_conversations[sid] = (conversation, count + 1)
- logger.info(
- f'Reusing active conversation {sid}', extra={'session_id': sid}
- )
- return conversation
-
- # Check if we have a detached conversation we can reuse
- if sid in self._detached_conversations:
- conversation, _ = self._detached_conversations.pop(sid)
- self._active_conversations[sid] = (conversation, 1)
- logger.info(
- f'Reusing detached conversation {sid}', extra={'session_id': sid}
- )
- return conversation
-
- # Get the event stream for the conversation - required to keep the cur_id up to date
- event_stream = None
- runtime = None
- session = self._local_agent_loops_by_sid.get(sid)
- if session:
- event_stream = session.agent_session.event_stream
- runtime = session.agent_session.runtime
-
- # Create new conversation if none exists
- c = ServerConversation(
- sid,
- file_store=self.file_store,
- config=self.config,
- user_id=user_id,
- event_stream=event_stream,
- runtime=runtime,
- )
- try:
- await c.connect()
- except AgentRuntimeUnavailableError as e:
- logger.error(
- f'Error connecting to conversation {c.sid}: {e}',
- extra={'session_id': sid},
- )
- await c.disconnect()
- return None
- end_time = time.time()
- logger.info(
- f'ServerConversation {c.sid} connected in {end_time - start_time} seconds',
- extra={'session_id': sid},
- )
- self._active_conversations[sid] = (c, 1)
- return c
-
- async def join_conversation(
- self,
- sid: str,
- connection_id: str,
- settings: Settings,
- user_id: str | None,
- ) -> AgentLoopInfo:
- logger.info(
- f'join_conversation:{sid}:{connection_id}',
- extra={'session_id': sid, 'user_id': user_id},
- )
- await self.sio.enter_room(connection_id, ROOM_KEY.format(sid=sid))
- self._local_connection_id_to_session_id[connection_id] = sid
- agent_loop_info = await self.maybe_start_agent_loop(sid, settings, user_id)
- return agent_loop_info
-
- async def detach_from_conversation(self, conversation: ServerConversation):
- sid = conversation.sid
- async with self._conversations_lock:
- if sid in self._active_conversations:
- conv, count = self._active_conversations[sid]
- if count > 1:
- self._active_conversations[sid] = (conv, count - 1)
- return
- else:
- self._active_conversations.pop(sid)
- self._detached_conversations[sid] = (conversation, time.time())
-
- async def _cleanup_stale(self):
- while should_continue():
- try:
- async with self._conversations_lock:
- # Create a list of items to process to avoid modifying dict during iteration
- items = list(self._detached_conversations.items())
- for sid, (conversation, detach_time) in items:
- await conversation.disconnect()
- self._detached_conversations.pop(sid, None)
-
- # Implies disconnected sandboxes stay open indefinitely
- if not self.config.sandbox.close_delay:
- return
-
- close_threshold = time.time() - self.config.sandbox.close_delay
- running_loops = list(self._local_agent_loops_by_sid.items())
- running_loops.sort(key=lambda item: item[1].last_active_ts)
- sid_to_close: list[str] = []
- for sid, session in running_loops:
- state = session.agent_session.get_state()
- if session.last_active_ts < close_threshold and state not in [
- AgentState.RUNNING,
- None,
- ]:
- sid_to_close.append(sid)
-
- connections = await self.get_connections(
- filter_to_sids=set(sid_to_close) # get_connections expects a set
- )
- connected_sids = {sid for _, sid in connections.items()}
- sid_to_close = [
- sid for sid in sid_to_close if sid not in connected_sids
- ]
- await wait_all(
- (self._close_session(sid) for sid in sid_to_close),
- timeout=WAIT_TIME_BEFORE_CLOSE,
- )
- await asyncio.sleep(_CLEANUP_INTERVAL)
- except asyncio.CancelledError:
- async with self._conversations_lock:
- for conversation, _ in self._detached_conversations.values():
- await conversation.disconnect()
- self._detached_conversations.clear()
- await wait_all(
- self._close_session(sid) for sid in self._local_agent_loops_by_sid
- )
- return
- except Exception:
- logger.error('error_cleaning_stale')
- await asyncio.sleep(_CLEANUP_INTERVAL)
-
- async def _get_conversation_store(self, user_id: str | None) -> ConversationStore:
- conversation_store_class = self._conversation_store_class
- if not conversation_store_class:
- self._conversation_store_class = conversation_store_class = get_impl(
- ConversationStore,
- self.server_config.conversation_store_class,
- )
- store = await conversation_store_class.get_instance(self.config, user_id)
- return store
-
- async def get_running_agent_loops(
- self, user_id: str | None = None, filter_to_sids: set[str] | None = None
- ) -> set[str]:
- """Get the running session ids in chronological order (oldest first).
-
- If a user is supplied, then the results are limited to session ids for that user.
- If a set of filter_to_sids is supplied, then results are limited to these ids of interest.
-
- Returns:
- A set of session IDs
- """
- # Get all items and convert to list for sorting
- items: Iterable[tuple[str, Session]] = self._local_agent_loops_by_sid.items()
-
- # Filter items if needed
- if filter_to_sids is not None:
- items = (item for item in items if item[0] in filter_to_sids)
- if user_id:
- items = (item for item in items if item[1].user_id == user_id)
-
- sids = {sid for sid, _ in items}
- return sids
-
- async def get_connections(
- self, user_id: str | None = None, filter_to_sids: set[str] | None = None
- ) -> dict[str, str]:
- connections = dict(**self._local_connection_id_to_session_id)
- if filter_to_sids is not None:
- connections = {
- connection_id: sid
- for connection_id, sid in connections.items()
- if sid in filter_to_sids
- }
- if user_id:
- for connection_id, sid in list(connections.items()):
- session = self._local_agent_loops_by_sid.get(sid)
- if not session or session.user_id != user_id:
- connections.pop(connection_id)
- return connections
-
- async def maybe_start_agent_loop(
- self,
- sid: str,
- settings: Settings,
- user_id: str | None,
- initial_user_msg: MessageAction | None = None,
- replay_json: str | None = None,
- ) -> AgentLoopInfo:
- logger.info(f'maybe_start_agent_loop:{sid}', extra={'session_id': sid})
- session = self._local_agent_loops_by_sid.get(sid)
- if not session:
- session = await self._start_agent_loop(
- sid, settings, user_id, initial_user_msg, replay_json
- )
- return self._agent_loop_info_from_session(session)
-
- async def _start_agent_loop(
- self,
- sid: str,
- settings: Settings,
- user_id: str | None,
- initial_user_msg: MessageAction | None = None,
- replay_json: str | None = None,
- ) -> Session:
- logger.info(f'starting_agent_loop:{sid}', extra={'session_id': sid})
-
- response_ids = await self.get_running_agent_loops(user_id)
- if len(response_ids) >= self.config.max_concurrent_conversations:
- logger.info(
- f'too_many_sessions_for:{user_id or ""}',
- extra={'session_id': sid, 'user_id': user_id},
- )
- # Get the conversations sorted (oldest first)
- conversation_store = await self._get_conversation_store(user_id)
- conversations = await conversation_store.get_all_metadata(response_ids)
- conversations.sort(key=_last_updated_at_key, reverse=True)
-
- while len(conversations) >= self.config.max_concurrent_conversations:
- oldest_conversation_id = conversations.pop().conversation_id
- logger.debug(
- f'closing_from_too_many_sessions:{user_id or ""}:{oldest_conversation_id}',
- extra={'session_id': oldest_conversation_id, 'user_id': user_id},
- )
- # Send status message to client and close session.
- status_update_dict = {
- 'status_update': True,
- 'type': 'error',
- 'id': 'AGENT_ERROR$TOO_MANY_CONVERSATIONS',
- 'message': 'Too many conversations at once. If you are still using this one, try reactivating it by prompting the agent to continue',
- }
- await run_in_loop(
- self.sio.emit(
- 'oh_event',
- status_update_dict,
- to=ROOM_KEY.format(sid=oldest_conversation_id),
- ),
- self._loop, # type:ignore
- )
- await self.close_session(oldest_conversation_id)
-
- llm_registry, conversation_stats, config = (
- create_registry_and_conversation_stats(self.config, sid, user_id, settings)
- )
- session = Session(
- sid=sid,
- file_store=self.file_store,
- config=config,
- llm_registry=llm_registry,
- conversation_stats=conversation_stats,
- sio=self.sio,
- user_id=user_id,
- )
- self._local_agent_loops_by_sid[sid] = session
- asyncio.create_task(
- session.initialize_agent(settings, initial_user_msg, replay_json)
- )
- # This does not get added when resuming an existing conversation
- try:
- session.agent_session.event_stream.subscribe(
- EventStreamSubscriber.SERVER,
- self._create_conversation_update_callback(
- user_id,
- sid,
- settings,
- session.llm_registry,
- asyncio.get_running_loop(),
- ),
- UPDATED_AT_CALLBACK_ID,
- )
- except ValueError:
- pass # Already subscribed - take no action
- return session
-
- async def send_to_event_stream(self, connection_id: str, data: dict):
- # If there is a local session running, send to that
- sid = self._local_connection_id_to_session_id.get(connection_id)
- if not sid:
- raise RuntimeError(f'no_connected_session:{connection_id}')
- await self.send_event_to_conversation(sid, data)
-
- async def send_event_to_conversation(self, sid: str, data: dict):
- session = self._local_agent_loops_by_sid.get(sid)
- if not session:
- raise RuntimeError(f'no_conversation:{sid}')
- await session.dispatch(data)
-
- async def request_llm_completion(
- self,
- sid: str,
- service_id: str,
- llm_config: LLMConfig,
- messages: list[dict[str, str]],
- ):
- session = self._local_agent_loops_by_sid.get(sid)
- if not session:
- raise RuntimeError(f'no_conversation:{sid}')
- llm_registry = session.llm_registry
- return llm_registry.request_extraneous_completion(
- service_id, llm_config, messages
- )
-
- async def disconnect_from_session(self, connection_id: str):
- sid = self._local_connection_id_to_session_id.pop(connection_id, None)
- logger.info(
- f'disconnect_from_session:{connection_id}:{sid}', extra={'session_id': sid}
- )
- if not sid:
- # This can occur if the init action was never run.
- logger.warning(
- f'disconnect_from_uninitialized_session:{connection_id}',
- extra={'session_id': sid},
- )
- return
-
- async def close_session(self, sid: str):
- session = self._local_agent_loops_by_sid.get(sid)
- if session:
- await self._close_session(sid)
-
- def get_agent_session(self, sid: str) -> AgentSession | None:
- """Get the agent session for a given session ID.
-
- Args:
- sid: The session ID.
-
- Returns:
- The agent session, or None if not found.
- """
- session = self._local_agent_loops_by_sid.get(sid)
- if session:
- return session.agent_session
- return None
-
- async def list_files(self, sid: str, path: str | None = None) -> list[str]:
- """List files in the workspace for a conversation.
-
- Args:
- sid: The session/conversation ID.
- path: Optional path to list files from. If None, lists from workspace root.
-
- Returns:
- A list of file paths, filtered by .gitignore rules if present.
-
- Raises:
- ValueError: If the runtime is not available.
- """
- agent_session = self.get_agent_session(sid)
- if not agent_session or not agent_session.runtime:
- raise ValueError(f'Runtime not available for conversation {sid}')
-
- runtime = agent_session.runtime
- file_list = await call_sync_from_async(runtime.list_files, path)
-
- # runtime.list_files returns relative filenames within the specified directory,
- # so we need to join with the path to get paths relative to workspace root
- if path:
- file_list = [os.path.join(path, f) for f in file_list]
-
- file_list = await self._filter_for_gitignore(runtime, file_list)
- return file_list
-
- async def _filter_for_gitignore(
- self, runtime: Any, file_list: list[str]
- ) -> list[str]:
- """Filter file list based on root-level .gitignore rules.
-
- Note: Only the .gitignore file at the workspace root is supported.
- Nested .gitignore files in subdirectories are not processed.
-
- Args:
- runtime: The runtime to read the .gitignore file from.
- file_list: List of file paths to filter.
-
- Returns:
- Filtered list of files excluding those matching .gitignore patterns.
- """
- try:
- read_action = FileReadAction('.gitignore')
- observation = await call_sync_from_async(runtime.run_action, read_action)
- spec = PathSpec.from_lines(
- GitWildMatchPattern, observation.content.splitlines()
- )
- file_list = [entry for entry in file_list if not spec.match_file(entry)]
- except Exception as e:
- logger.warning(f'Could not read .gitignore for filtering: {e}')
- return file_list
-
- async def select_file(self, sid: str, file: str) -> tuple[str | None, str | None]:
- """Read a file from the workspace.
-
- Args:
- sid: The session/conversation ID.
- file: The file path relative to the workspace root.
-
- Returns:
- A tuple of (content, error). If successful, content is the file content
- and error is None. If failed, content is None and error is the error message.
-
- Raises:
- ValueError: If the runtime is not available.
- """
- from openhands.events.observation import ErrorObservation, FileReadObservation
-
- agent_session = self.get_agent_session(sid)
- if not agent_session or not agent_session.runtime:
- raise ValueError(f'Runtime not available for conversation {sid}')
-
- runtime = agent_session.runtime
- file_path = os.path.join(runtime.config.workspace_mount_path_in_sandbox, file)
- read_action = FileReadAction(file_path)
-
- observation = await call_sync_from_async(runtime.run_action, read_action)
-
- if isinstance(observation, FileReadObservation):
- return observation.content, None
- elif isinstance(observation, ErrorObservation):
- if 'ERROR_BINARY_FILE' in observation.message:
- return None, f'BINARY_FILE:{file}'
- return None, str(observation)
- else:
- return None, f'Unexpected observation type: {type(observation)}'
-
- async def upload_files(
- self, sid: str, files: list[tuple[str, bytes]]
- ) -> tuple[list[str], list[dict[str, str]]]:
- """Upload files to the workspace.
-
- Args:
- sid: The session/conversation ID.
- files: List of (filename, content) tuples to upload.
-
- Returns:
- A tuple of (uploaded_files, skipped_files).
-
- Raises:
- ValueError: If the runtime is not available.
- """
- from openhands.events.action.files import FileWriteAction
-
- agent_session = self.get_agent_session(sid)
- if not agent_session or not agent_session.runtime:
- raise ValueError(f'Runtime not available for conversation {sid}')
-
- runtime = agent_session.runtime
- uploaded_files: list[str] = []
- skipped_files: list[dict[str, str]] = []
-
- for filename, content in files:
- file_path = os.path.join(
- runtime.config.workspace_mount_path_in_sandbox, filename
- )
- try:
- write_action = FileWriteAction(
- path=file_path,
- content=content.decode('utf-8', errors='replace'),
- )
- await call_sync_from_async(runtime.run_action, write_action)
- uploaded_files.append(file_path)
- except Exception as e:
- skipped_files.append({'name': filename, 'reason': str(e)})
-
- return uploaded_files, skipped_files
-
- async def _close_session(self, sid: str):
- logger.info(f'_close_session:{sid}', extra={'session_id': sid})
-
- # Clear up local variables
- connection_ids_to_remove = list(
- connection_id
- for connection_id, conn_sid in self._local_connection_id_to_session_id.items()
- if sid == conn_sid
- )
- logger.info(
- f'removing connections: {connection_ids_to_remove}',
- extra={'session_id': sid},
- )
- # Perform a graceful shutdown of each connection
- for connection_id in connection_ids_to_remove:
- await self.sio.disconnect(connection_id)
- self._local_connection_id_to_session_id.pop(connection_id, None)
-
- session = self._local_agent_loops_by_sid.pop(sid, None)
- if not session:
- logger.warning(f'no_session_to_close:{sid}', extra={'session_id': sid})
- return
-
- logger.info(f'closing_session:{session.sid}', extra={'session_id': sid})
- await session.close()
- logger.info(f'closed_session:{session.sid}', extra={'session_id': sid})
-
- @classmethod
- def get_instance(
- cls,
- sio: socketio.AsyncServer,
- config: OpenHandsConfig,
- file_store: FileStore,
- server_config: ServerConfig,
- monitoring_listener: MonitoringListener | None,
- ) -> ConversationManager:
- return StandaloneConversationManager(
- sio,
- config,
- file_store,
- server_config,
- monitoring_listener or MonitoringListener(),
- )
-
- def _create_conversation_update_callback(
- self,
- user_id: str | None,
- conversation_id: str,
- settings: Settings,
- llm_registry: LLMRegistry,
- loop: asyncio.AbstractEventLoop,
- ) -> Callable:
- def callback(event, *args, **kwargs):
- try:
- asyncio.run_coroutine_threadsafe(
- self._update_conversation_for_event(
- user_id,
- conversation_id,
- settings,
- llm_registry,
- event,
- ),
- loop,
- )
- except Exception as e:
- logger.error(f'Error in conversation update callback: {e}')
-
- return callback
-
- async def _update_conversation_for_event(
- self,
- user_id: str | None,
- conversation_id: str,
- settings: Settings,
- llm_registry: LLMRegistry,
- event=None,
- ):
- conversation_store = await self._get_conversation_store(user_id)
- conversation = await conversation_store.get_metadata(conversation_id)
- conversation.last_updated_at = datetime.now(timezone.utc)
-
- # Update cost/token metrics if event has llm_metrics
- if event and hasattr(event, 'llm_metrics') and event.llm_metrics:
- metrics = event.llm_metrics
-
- # Update accumulated cost
- if hasattr(metrics, 'accumulated_cost'):
- conversation.accumulated_cost = metrics.accumulated_cost
-
- # Update token usage
- if hasattr(metrics, 'accumulated_token_usage'):
- token_usage = metrics.accumulated_token_usage
- conversation.prompt_tokens = token_usage.prompt_tokens
- conversation.completion_tokens = token_usage.completion_tokens
- conversation.total_tokens = (
- token_usage.prompt_tokens + token_usage.completion_tokens
- )
-
- # Check for branch changes if this is a git-related event
- if event and self._is_git_related_event(event):
- logger.info(
- f'Git-related event detected, updating conversation branch for {conversation_id}',
- extra={
- 'session_id': conversation_id,
- 'command': getattr(event, 'command', 'unknown'),
- },
- )
- await self._update_conversation_branch(conversation)
-
- default_title = get_default_conversation_title(conversation_id)
- if (
- conversation.title == default_title
- ): # attempt to autogenerate if default title is in use
- title = await auto_generate_title(
- conversation_id, user_id, self.file_store, settings, llm_registry
- )
- if title and not title.isspace():
- conversation.title = title
- try:
- # Emit a status update to the client with the new title
- status_update_dict = {
- 'status_update': True,
- 'type': 'info',
- 'message': conversation_id,
- 'conversation_title': conversation.title,
- }
- await run_in_loop(
- self.sio.emit(
- 'oh_event',
- status_update_dict,
- to=ROOM_KEY.format(sid=conversation_id),
- ),
- self._loop, # type:ignore
- )
- except Exception as e:
- logger.error(f'Error emitting title update event: {e}')
- else:
- conversation.title = default_title
-
- await conversation_store.save_metadata(conversation)
-
- def _is_git_related_event(self, event) -> bool:
- """
- Determine if an event is related to git operations that could change the branch.
-
- Args:
- event: The event to check
-
- Returns:
- True if the event is git-related and could change the branch, False otherwise
- """
- # Early return if event is None or not the correct type
- if not event or not isinstance(event, CmdOutputObservation):
- return False
-
- # Check CmdOutputObservation for git commands that change branches
- # We check the observation result, not the action request, to ensure the command actually succeeded
- if (
- event.observation == ObservationType.RUN
- and event.metadata.exit_code == 0 # Only consider successful commands
- ):
- command = event.command.lower()
-
- # Check if any git command that changes branches is present anywhere in the command
- # This handles compound commands like "cd workspace && git checkout feature-branch"
- git_commands = [
- 'git checkout',
- 'git switch',
- 'git merge',
- 'git rebase',
- 'git reset',
- 'git branch',
- ]
-
- is_git_related = any(git_cmd in command for git_cmd in git_commands)
-
- if is_git_related:
- logger.debug(
- f'Detected git-related command: {command} with exit code {event.metadata.exit_code}',
- extra={'command': command, 'exit_code': event.metadata.exit_code},
- )
-
- return is_git_related
-
- return False
-
- async def _update_conversation_branch(self, conversation: ConversationMetadata):
- """
- Update the conversation's current branch if it has changed.
-
- Args:
- conversation: The conversation metadata to update
- """
- try:
- # Get the session and runtime for this conversation
- session, runtime = self._get_session_and_runtime(
- conversation.conversation_id
- )
- if not session or not runtime:
- return
-
- # Get the current branch from the workspace
- current_branch = self._get_current_workspace_branch(
- runtime, conversation.selected_repository
- )
-
- # Update branch if it has changed
- if self._should_update_branch(conversation.selected_branch, current_branch):
- self._update_branch_in_conversation(conversation, current_branch)
-
- except Exception as e:
- # Log an error that occurred during branch update
- logger.warning(
- f'Failed to update conversation branch: {e}',
- extra={'session_id': conversation.conversation_id},
- )
-
- def _get_session_and_runtime(
- self, conversation_id: str
- ) -> tuple[Session | None, Any | None]:
- """
- Get the session and runtime for a conversation.
-
- Args:
- conversation_id: The conversation ID
-
- Returns:
- Tuple of (session, runtime) or (None, None) if not found
- """
- session = self._local_agent_loops_by_sid.get(conversation_id)
- if not session or not session.agent_session.runtime:
- return None, None
- return session, session.agent_session.runtime
-
- def _get_current_workspace_branch(
- self, runtime: Any, selected_repository: str | None
- ) -> str | None:
- """
- Get the current branch from the workspace.
-
- Args:
- runtime: The runtime instance
- selected_repository: The selected repository path or None
-
- Returns:
- The current branch name or None if not found
- """
- # Extract the repository name from the full repository path
- if not selected_repository:
- primary_repo_path = None
- else:
- # Extract the repository name from the full path (e.g., "org/repo" -> "repo")
- primary_repo_path = selected_repository.split('/')[-1]
-
- return runtime.get_workspace_branch(primary_repo_path)
-
- def _should_update_branch(
- self, current_branch: str | None, new_branch: str | None
- ) -> bool:
- """
- Determine if the branch should be updated.
-
- Args:
- current_branch: The current branch in conversation metadata
- new_branch: The new branch from the workspace
-
- Returns:
- True if the branch should be updated, False otherwise
- """
- return new_branch is not None and new_branch != current_branch
-
- def _update_branch_in_conversation(
- self, conversation: ConversationMetadata, new_branch: str | None
- ):
- """
- Update the branch in the conversation metadata.
-
- Args:
- conversation: The conversation metadata to update
- new_branch: The new branch name
- """
- old_branch = conversation.selected_branch
- conversation.selected_branch = new_branch
-
- logger.info(
- f'Branch changed from {old_branch} to {new_branch}',
- extra={'session_id': conversation.conversation_id},
- )
-
- async def get_agent_loop_info(
- self, user_id: str | None = None, filter_to_sids: set[str] | None = None
- ):
- results = []
- for session in self._local_agent_loops_by_sid.values():
- if user_id and session.user_id != user_id:
- continue
- if filter_to_sids and session.sid not in filter_to_sids:
- continue
- results.append(self._agent_loop_info_from_session(session))
- return results
-
- def _agent_loop_info_from_session(self, session: Session):
- return AgentLoopInfo(
- conversation_id=session.sid,
- url=self._get_conversation_url(session.sid),
- session_api_key=None,
- event_store=session.agent_session.event_stream,
- status=_get_status_from_session(session),
- runtime_status=getattr(
- session.agent_session.runtime, 'runtime_status', None
- ),
- )
-
- def _get_conversation_url(self, conversation_id: str):
- return f'/api/conversations/{conversation_id}'
-
-
-def _get_status_from_session(session: Session) -> ConversationStatus:
- agent_session = session.agent_session
- if agent_session.runtime and agent_session.runtime.runtime_initialized:
- return ConversationStatus.RUNNING
- return ConversationStatus.STARTING
-
-
-def _last_updated_at_key(conversation: ConversationMetadata) -> float:
- last_updated_at = conversation.last_updated_at
- if last_updated_at is None:
- return 0.0
- return last_updated_at.timestamp()
diff --git a/openhands/server/conversation_manager/utils.py b/openhands/server/conversation_manager/utils.py
deleted file mode 100644
index 9aadfc8568..0000000000
--- a/openhands/server/conversation_manager/utils.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
diff --git a/openhands/server/listen_socket.py b/openhands/server/listen_socket.py
index 9ef5da396f..b00fa1cd2c 100644
--- a/openhands/server/listen_socket.py
+++ b/openhands/server/listen_socket.py
@@ -6,171 +6,8 @@
# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
# Tag: Legacy-V0
# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
-import asyncio
-import os
-from typing import Any
-from urllib.parse import parse_qs
-from socketio.exceptions import ConnectionRefusedError
+# Re-export sio for backward compatibility with listen.py and enterprise code
+from openhands.server.shared import sio
-from openhands.core.logger import openhands_logger as logger
-from openhands.events.action import (
- NullAction,
-)
-from openhands.events.action.agent import RecallAction
-from openhands.events.async_event_store_wrapper import AsyncEventStoreWrapper
-from openhands.events.event_store import EventStore
-from openhands.events.observation import (
- NullObservation,
-)
-from openhands.events.observation.agent import (
- AgentStateChangedObservation,
-)
-from openhands.events.serialization import event_to_dict
-from openhands.integrations.service_types import ProviderType
-from openhands.server.services.conversation_service import (
- setup_init_conversation_settings,
-)
-from openhands.server.shared import (
- conversation_manager,
- sio,
-)
-from openhands.storage.conversation.conversation_validator import (
- create_conversation_validator,
-)
-
-
-async def connect(connection_id: str, environ: dict) -> None:
- try:
- logger.info(f'sio:connect: {connection_id}')
- query_params = parse_qs(environ.get('QUERY_STRING', ''))
- latest_event_id_str = query_params.get('latest_event_id', [-1])[0]
- try:
- latest_event_id = int(latest_event_id_str)
- except ValueError:
- logger.debug(
- f'Invalid latest_event_id value: {latest_event_id_str}, defaulting to -1'
- )
- latest_event_id = -1
- conversation_id = query_params.get('conversation_id', [None])[0]
- logger.info(
- f'Socket request for conversation {conversation_id} with connection_id {connection_id}'
- )
- raw_list = query_params.get('providers_set', [])
- providers_list = []
- for item in raw_list:
- providers_list.extend(item.split(',') if isinstance(item, str) else [])
- providers_list = [p for p in providers_list if p]
- providers_set = [ProviderType(p) for p in providers_list]
-
- if not conversation_id:
- logger.error('No conversation_id in query params')
- raise ConnectionRefusedError('No conversation_id in query params')
-
- if _invalid_session_api_key(query_params):
- raise ConnectionRefusedError('invalid_session_api_key')
-
- cookies_str = environ.get('HTTP_COOKIE', '')
- # Get Authorization header from the environment
- # Headers in WSGI/ASGI are prefixed with 'HTTP_' and have dashes replaced with underscores
- authorization_header = environ.get('HTTP_AUTHORIZATION', None)
- conversation_validator = create_conversation_validator()
- user_id = await conversation_validator.validate(
- conversation_id, cookies_str, authorization_header
- )
- logger.info(
- f'User {user_id} is allowed to connect to conversation {conversation_id}'
- )
-
- try:
- event_store = EventStore(
- conversation_id, conversation_manager.file_store, user_id
- )
- except FileNotFoundError as e:
- logger.error(
- f'Failed to create EventStore for conversation {conversation_id}: {e}'
- )
- raise ConnectionRefusedError(f'Failed to access conversation events: {e}')
-
- logger.info(
- f'Replaying event stream for conversation {conversation_id} with connection_id {connection_id}...'
- )
- agent_state_changed = None
-
- # Create an async store to replay events
- async_store = AsyncEventStoreWrapper(event_store, latest_event_id + 1)
-
- # Process all available events
- async for event in async_store:
- logger.debug(f'oh_event: {event.__class__.__name__}')
-
- if isinstance(
- event,
- (NullAction, NullObservation, RecallAction),
- ):
- continue
- elif isinstance(event, AgentStateChangedObservation):
- agent_state_changed = event
- else:
- await sio.emit('oh_event', event_to_dict(event), to=connection_id)
-
- # Send the agent state changed event last if we have one
- if agent_state_changed:
- await sio.emit(
- 'oh_event', event_to_dict(agent_state_changed), to=connection_id
- )
-
- logger.info(
- f'Finished replaying event stream for conversation {conversation_id}'
- )
-
- conversation_init_data = await setup_init_conversation_settings(
- user_id, conversation_id, providers_set
- )
-
- agent_loop_info = await conversation_manager.join_conversation(
- conversation_id,
- connection_id,
- conversation_init_data,
- user_id,
- )
-
- if agent_loop_info is None:
- raise ConnectionRefusedError('Failed to join conversation')
-
- logger.info(
- f'Successfully joined conversation {conversation_id} with connection_id {connection_id}'
- )
- except ConnectionRefusedError:
- # Close the broken connection after sending an error message
- asyncio.create_task(sio.disconnect(connection_id))
- raise
-
-
-async def oh_user_action(connection_id: str, data: dict[str, Any]) -> None:
- await conversation_manager.send_to_event_stream(connection_id, data)
-
-
-async def oh_action(connection_id: str, data: dict[str, Any]) -> None:
- # TODO: Remove this handler once all clients are updated to use oh_user_action
- # Keeping for backward compatibility with in-progress sessions
- await conversation_manager.send_to_event_stream(connection_id, data)
-
-
-async def disconnect(connection_id: str) -> None:
- logger.info(f'sio:disconnect:{connection_id}')
- await conversation_manager.disconnect_from_session(connection_id)
-
-
-def _invalid_session_api_key(query_params: dict[str, list[Any]]):
- session_api_key = os.getenv('SESSION_API_KEY')
- if not session_api_key:
- return False
- query_api_keys = query_params['session_api_key']
- if not query_api_keys:
- return True
- return query_api_keys[0] != session_api_key
+__all__ = ['sio']
diff --git a/openhands/server/services/conversation_service.py b/openhands/server/services/conversation_service.py
index 4cb7694a67..52359765a1 100644
--- a/openhands/server/services/conversation_service.py
+++ b/openhands/server/services/conversation_service.py
@@ -8,30 +8,22 @@
# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
import uuid
from types import MappingProxyType
-from typing import Any
-from pydantic import SecretStr
-
-from openhands.core.config.mcp_config import MCPConfig
from openhands.core.logger import openhands_logger as logger
-from openhands.events.action.message import MessageAction
from openhands.integrations.provider import (
- CUSTOM_SECRETS_TYPE,
PROVIDER_TOKEN_TYPE,
ProviderToken,
)
from openhands.integrations.service_types import ProviderType
-from openhands.server.data_models.agent_loop_info import AgentLoopInfo
from openhands.server.session.conversation_init_data import ConversationInitData
from openhands.server.shared import (
ConversationStoreImpl,
SecretsStoreImpl,
SettingsStoreImpl,
config,
- conversation_manager,
server_config,
)
-from openhands.server.types import AppMode, LLMAuthenticationError, MissingSettingsError
+from openhands.server.types import AppMode
from openhands.storage.data_models.conversation_metadata import (
ConversationMetadata,
ConversationTrigger,
@@ -79,137 +71,6 @@ async def initialize_conversation(
return conversation_metadata
-async def start_conversation(
- user_id: str | None,
- git_provider_tokens: PROVIDER_TOKEN_TYPE | None,
- custom_secrets: CUSTOM_SECRETS_TYPE | None,
- initial_user_msg: str | None,
- image_urls: list[str] | None,
- replay_json: str | None,
- conversation_id: str,
- conversation_metadata: ConversationMetadata,
- conversation_instructions: str | None,
- mcp_config: MCPConfig | None = None,
-) -> AgentLoopInfo:
- logger.info(
- 'Creating conversation',
- extra={
- 'signal': 'create_conversation',
- 'user_id': user_id,
- 'trigger': conversation_metadata.trigger,
- },
- )
- logger.info('Loading settings')
- settings_store = await SettingsStoreImpl.get_instance(config, user_id)
- settings = await settings_store.load()
- logger.info('Settings loaded')
-
- session_init_args: dict[str, Any] = {}
- if settings:
- session_init_args = settings.model_dump()
- agent_settings = settings.agent_settings
- # We could use litellm.check_valid_key for a more accurate check,
- # but that would run a tiny inference.
- model_name = agent_settings.llm.model
- llm_api_key = settings.agent_settings.llm.api_key
- is_bedrock_model = model_name.startswith('bedrock/')
- is_lemonade_model = model_name.startswith('lemonade/')
-
- key_value: str | None = None
- if isinstance(llm_api_key, SecretStr):
- key_value = llm_api_key.get_secret_value()
- elif isinstance(llm_api_key, str):
- key_value = llm_api_key
- if (
- not is_bedrock_model
- and not is_lemonade_model
- and (not key_value or key_value.isspace())
- ):
- logger.warning(f'Missing api key for model {model_name}')
- raise LLMAuthenticationError(
- 'Error authenticating with the LLM provider. Please check your API key'
- )
- elif is_bedrock_model:
- logger.info(f'Bedrock model detected ({model_name}), API key not required')
-
- else:
- logger.warning('Settings not present, not starting conversation')
- raise MissingSettingsError('Settings not found')
-
- session_init_args['git_provider_tokens'] = git_provider_tokens
- session_init_args['selected_repository'] = conversation_metadata.selected_repository
- session_init_args['custom_secrets'] = custom_secrets
- session_init_args['selected_branch'] = conversation_metadata.selected_branch
- session_init_args['git_provider'] = conversation_metadata.git_provider
- session_init_args['conversation_instructions'] = conversation_instructions
- if mcp_config:
- agent_settings_payload = dict(session_init_args.get('agent_settings') or {})
- agent_settings_payload['mcp_config'] = mcp_config.model_dump(mode='python')
- session_init_args['agent_settings'] = agent_settings_payload
-
- conversation_init_data = ConversationInitData(**session_init_args)
-
- logger.info(
- f'Starting agent loop for conversation {conversation_id}',
- extra={'user_id': user_id, 'session_id': conversation_id},
- )
-
- initial_message_action = None
- if initial_user_msg or image_urls:
- initial_message_action = MessageAction(
- content=initial_user_msg or '',
- image_urls=image_urls or [],
- )
-
- agent_loop_info = await conversation_manager.maybe_start_agent_loop(
- conversation_id,
- conversation_init_data,
- user_id,
- initial_user_msg=initial_message_action,
- replay_json=replay_json,
- )
- logger.info(f'Finished initializing conversation {agent_loop_info.conversation_id}')
- return agent_loop_info
-
-
-async def create_new_conversation(
- user_id: str | None,
- git_provider_tokens: PROVIDER_TOKEN_TYPE | None,
- custom_secrets: CUSTOM_SECRETS_TYPE | None,
- selected_repository: str | None,
- selected_branch: str | None,
- initial_user_msg: str | None,
- image_urls: list[str] | None,
- replay_json: str | None,
- conversation_instructions: str | None = None,
- conversation_trigger: ConversationTrigger = ConversationTrigger.GUI,
- git_provider: ProviderType | None = None,
- conversation_id: str | None = None,
- mcp_config: MCPConfig | None = None,
-) -> AgentLoopInfo:
- conversation_metadata = await initialize_conversation(
- user_id,
- conversation_id,
- selected_repository,
- selected_branch,
- conversation_trigger,
- git_provider,
- )
-
- return await start_conversation(
- user_id,
- git_provider_tokens,
- custom_secrets,
- initial_user_msg,
- image_urls,
- replay_json,
- conversation_metadata.conversation_id,
- conversation_metadata,
- conversation_instructions,
- mcp_config,
- )
-
-
def create_provider_tokens_object(
providers_set: list[ProviderType],
) -> PROVIDER_TOKEN_TYPE:
diff --git a/openhands/server/shared.py b/openhands/server/shared.py
index 0e61588d7e..78da2c3c83 100644
--- a/openhands/server/shared.py
+++ b/openhands/server/shared.py
@@ -14,9 +14,6 @@ from dotenv import load_dotenv
from openhands.core.config import load_openhands_config
from openhands.core.config.openhands_config import OpenHandsConfig
from openhands.server.config.server_config import ServerConfig, load_server_config
-from openhands.server.conversation_manager.conversation_manager import (
- ConversationManager,
-)
from openhands.server.monitoring import MonitoringListener
from openhands.server.types import ServerConfigInterface
from openhands.storage import get_file_store
@@ -66,15 +63,6 @@ MonitoringListenerImpl = get_impl(
monitoring_listener = MonitoringListenerImpl.get_instance(config)
-ConversationManagerImpl = get_impl(
- ConversationManager,
- server_config.conversation_manager_class,
-)
-
-conversation_manager = ConversationManagerImpl.get_instance(
- sio, config, file_store, server_config, monitoring_listener
-)
-
SettingsStoreImpl = get_impl(SettingsStore, server_config.settings_store_class)
SecretsStoreImpl = get_impl(SecretsStore, server_config.secret_store_class)
diff --git a/openhands/server/utils.py b/openhands/server/utils.py
index 91dd77e140..a97b1bf809 100644
--- a/openhands/server/utils.py
+++ b/openhands/server/utils.py
@@ -10,11 +10,9 @@ import uuid
from fastapi import Depends, HTTPException, Request, status
-from openhands.core.logger import openhands_logger as logger
from openhands.server.shared import (
ConversationStoreImpl,
config,
- conversation_manager,
)
from openhands.server.user_auth import get_user_id
from openhands.storage.conversation.conversation_store import ConversationStore
@@ -99,25 +97,3 @@ async def get_conversation_metadata(
status_code=status.HTTP_404_NOT_FOUND,
detail=f'Conversation {conversation_id} not found',
)
-
-
-async def get_conversation(
- conversation_id: str, user_id: str | None = Depends(get_user_id)
-):
- """Grabs conversation id set by middleware. Adds the conversation_id to the openapi schema."""
- conversation = await conversation_manager.attach_to_conversation(
- conversation_id, user_id
- )
- if not conversation:
- logger.warning(
- f'get_conversation: conversation {conversation_id} not found, attach_to_conversation returned None',
- extra={'session_id': conversation_id, 'user_id': user_id},
- )
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f'Conversation {conversation_id} not found',
- )
- try:
- yield conversation
- finally:
- await conversation_manager.detach_from_conversation(conversation)
diff --git a/openhands/utils/import_utils.py b/openhands/utils/import_utils.py
index de2bd0ca85..0b119f9474 100644
--- a/openhands/utils/import_utils.py
+++ b/openhands/utils/import_utils.py
@@ -52,20 +52,20 @@ def get_impl(cls: type[T], impl_name: str | None) -> type[T]:
Args:
cls: The base class that defines the interface
impl_name: Fully qualified name of the implementation class, or None to use the base class
- e.g. 'openhands.server.conversation_manager.StandaloneConversationManager'
+ e.g. 'openhands.storage.settings.file_settings_store.FileSettingsStore'
Returns:
The implementation class, which is guaranteed to be a subclass of cls
Example:
>>> # Get default implementation
- >>> ConversationManager = get_impl(ConversationManager, None)
+ >>> SettingsStore = get_impl(SettingsStore, None)
>>> # Get custom implementation
- >>> CustomManager = get_impl(ConversationManager, 'myapp.CustomConversationManager')
+ >>> CustomStore = get_impl(SettingsStore, 'myapp.CustomSettingsStore')
Common Use Cases:
- - Server components (ConversationManager, UserAuth, etc.)
- - Storage implementations (ConversationStore, SettingsStore, etc.)
+ - Server components (UserAuth, MonitoringListener, etc.)
+ - Storage implementations (ConversationStore, SettingsStore, SecretsStore, etc.)
- Service integrations (GitHub, GitLab, Bitbucket, Azure DevOps services)
The implementation is cached to avoid repeated imports of the same class.
diff --git a/tests/unit/server/conversation_manager/test_standalone_conversation_manager.py b/tests/unit/server/conversation_manager/test_standalone_conversation_manager.py
deleted file mode 100644
index e584691852..0000000000
--- a/tests/unit/server/conversation_manager/test_standalone_conversation_manager.py
+++ /dev/null
@@ -1,197 +0,0 @@
-import asyncio
-import json
-from dataclasses import dataclass
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pytest
-
-from openhands.core.config.openhands_config import OpenHandsConfig
-from openhands.server.conversation_manager.standalone_conversation_manager import (
- StandaloneConversationManager,
-)
-from openhands.server.monitoring import MonitoringListener
-from openhands.server.session.conversation_init_data import ConversationInitData
-from openhands.storage.memory import InMemoryFileStore
-
-
-@dataclass
-class GetMessageMock:
- message: dict | None
- sleep_time: int = 0.01
-
- async def get_message(self, **kwargs):
- await asyncio.sleep(self.sleep_time)
- return {'data': json.dumps(self.message)}
-
-
-def get_mock_sio(get_message: GetMessageMock | None = None):
- sio = MagicMock()
- sio.enter_room = AsyncMock()
- sio.manager.redis = MagicMock()
- sio.manager.redis.publish = AsyncMock()
- pubsub = AsyncMock()
- pubsub.get_message = (get_message or GetMessageMock(None)).get_message
- sio.manager.redis.pubsub.return_value = pubsub
- return sio
-
-
-async def test_init_new_local_session():
- session_instance = AsyncMock()
- session_instance.agent_session = MagicMock()
- session_instance.agent_session.event_stream.cur_id = 1
- mock_session = MagicMock()
- mock_session.return_value = session_instance
- sio = get_mock_sio()
- get_running_agent_loops_mock = AsyncMock()
- get_running_agent_loops_mock.return_value = set()
- is_agent_loop_running_mock = AsyncMock()
- is_agent_loop_running_mock.return_value = True
- with (
- patch(
- 'openhands.server.conversation_manager.standalone_conversation_manager.Session',
- mock_session,
- ),
- patch(
- 'openhands.server.conversation_manager.standalone_conversation_manager.StandaloneConversationManager.get_running_agent_loops',
- get_running_agent_loops_mock,
- ),
- ):
- async with StandaloneConversationManager(
- sio, OpenHandsConfig(), InMemoryFileStore(), MonitoringListener()
- ) as conversation_manager:
- await conversation_manager.maybe_start_agent_loop(
- 'new-session-id', ConversationInitData(), 1
- )
- with (
- patch(
- 'openhands.server.conversation_manager.standalone_conversation_manager.StandaloneConversationManager.is_agent_loop_running',
- is_agent_loop_running_mock,
- ),
- ):
- await conversation_manager.join_conversation(
- 'new-session-id',
- 'new-session-id',
- ConversationInitData(),
- 1,
- )
- assert session_instance.initialize_agent.call_count == 1
- assert sio.enter_room.await_count == 1
-
-
-async def test_join_local_session():
- session_instance = AsyncMock()
- session_instance.agent_session = MagicMock()
- mock_session = MagicMock()
- mock_session.return_value = session_instance
- session_instance.agent_session.event_stream.cur_id = 1
- sio = get_mock_sio()
- get_running_agent_loops_mock = AsyncMock()
- get_running_agent_loops_mock.return_value = set()
- is_agent_loop_running_mock = AsyncMock()
- is_agent_loop_running_mock.return_value = True
- with (
- patch(
- 'openhands.server.conversation_manager.standalone_conversation_manager.Session',
- mock_session,
- ),
- patch(
- 'openhands.server.conversation_manager.standalone_conversation_manager.StandaloneConversationManager.get_running_agent_loops',
- get_running_agent_loops_mock,
- ),
- ):
- async with StandaloneConversationManager(
- sio, OpenHandsConfig(), InMemoryFileStore(), MonitoringListener()
- ) as conversation_manager:
- await conversation_manager.maybe_start_agent_loop(
- 'new-session-id', ConversationInitData(), None
- )
- with (
- patch(
- 'openhands.server.conversation_manager.standalone_conversation_manager.StandaloneConversationManager.is_agent_loop_running',
- is_agent_loop_running_mock,
- ),
- ):
- await conversation_manager.join_conversation(
- 'new-session-id',
- 'new-session-id',
- ConversationInitData(),
- None,
- )
- await conversation_manager.join_conversation(
- 'new-session-id',
- 'new-session-id',
- ConversationInitData(),
- None,
- )
- assert session_instance.initialize_agent.call_count == 1
- assert sio.enter_room.await_count == 2
-
-
-async def test_add_to_local_event_stream():
- session_instance = AsyncMock()
- session_instance.agent_session = MagicMock()
- mock_session = MagicMock()
- mock_session.return_value = session_instance
- session_instance.agent_session.event_stream.cur_id = 1
- sio = get_mock_sio()
- get_running_agent_loops_mock = AsyncMock()
- get_running_agent_loops_mock.return_value = set()
- with (
- patch(
- 'openhands.server.conversation_manager.standalone_conversation_manager.Session',
- mock_session,
- ),
- patch(
- 'openhands.server.conversation_manager.standalone_conversation_manager.StandaloneConversationManager.get_running_agent_loops',
- get_running_agent_loops_mock,
- ),
- ):
- async with StandaloneConversationManager(
- sio, OpenHandsConfig(), InMemoryFileStore(), MonitoringListener()
- ) as conversation_manager:
- await conversation_manager.maybe_start_agent_loop(
- 'new-session-id', ConversationInitData(), 1
- )
- await conversation_manager.join_conversation(
- 'new-session-id', 'connection-id', ConversationInitData(), 1
- )
- await conversation_manager.send_to_event_stream(
- 'connection-id', {'event_type': 'some_event'}
- )
- session_instance.dispatch.assert_called_once_with({'event_type': 'some_event'})
-
-
-async def test_cleanup_session_connections():
- sio = get_mock_sio()
- sio.disconnect = AsyncMock() # Mock the disconnect method
- async with StandaloneConversationManager(
- sio, OpenHandsConfig(), InMemoryFileStore(), MonitoringListener()
- ) as conversation_manager:
- conversation_manager._local_connection_id_to_session_id.update(
- {
- 'conn1': 'session1',
- 'conn2': 'session1',
- 'conn3': 'session2',
- 'conn4': 'session2',
- }
- )
-
- await conversation_manager._close_session('session1')
-
- # Check that connections were removed from the dictionary
- remaining_connections = conversation_manager._local_connection_id_to_session_id
- assert 'conn1' not in remaining_connections
- assert 'conn2' not in remaining_connections
- assert 'conn3' in remaining_connections
- assert 'conn4' in remaining_connections
- assert remaining_connections['conn3'] == 'session2'
- assert remaining_connections['conn4'] == 'session2'
-
- # Check that disconnect was called for each connection
- assert sio.disconnect.await_count == 2
- sio.disconnect.assert_any_call('conn1')
- sio.disconnect.assert_any_call('conn2')
diff --git a/tests/unit/server/test_socket_events.py b/tests/unit/server/test_socket_events.py
deleted file mode 100644
index 1c50396cbb..0000000000
--- a/tests/unit/server/test_socket_events.py
+++ /dev/null
@@ -1,43 +0,0 @@
-from unittest.mock import AsyncMock, patch
-
-import pytest
-
-from openhands.server.listen_socket import oh_action, oh_user_action
-
-
-async def test_oh_user_action():
- """Test that oh_user_action correctly forwards data to the conversation manager."""
- connection_id = 'test_connection_id'
- test_data = {'action': 'test_action', 'data': 'test_data'}
-
- # Mock the conversation_manager
- with patch('openhands.server.listen_socket.conversation_manager') as mock_manager:
- mock_manager.send_to_event_stream = AsyncMock()
-
- # Call the function
- await oh_user_action(connection_id, test_data)
-
- # Verify the conversation manager was called with the correct arguments
- mock_manager.send_to_event_stream.assert_called_once_with(
- connection_id, test_data
- )
-
-
-async def test_oh_action():
- """Test that oh_action (legacy handler) correctly forwards data to the conversation manager."""
- connection_id = 'test_connection_id'
- test_data = {'action': 'test_action', 'data': 'test_data'}
-
- # Mock the conversation_manager
- with patch('openhands.server.listen_socket.conversation_manager') as mock_manager:
- mock_manager.send_to_event_stream = AsyncMock()
-
- # Call the function
- await oh_action(connection_id, test_data)
-
- # Verify the conversation manager was called with the correct arguments
- mock_manager.send_to_event_stream.assert_called_once_with(
- connection_id, test_data
- )
diff --git a/tests/unit/utils/test_auto_generate_title.py b/tests/unit/utils/test_auto_generate_title.py
index 5d684bd9c0..d5207a4416 100644
--- a/tests/unit/utils/test_auto_generate_title.py
+++ b/tests/unit/utils/test_auto_generate_title.py
@@ -1,19 +1,14 @@
"""Tests for the auto-generate title functionality."""
from datetime import datetime, timezone
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import MagicMock, patch
import pytest
-from openhands.core.config.openhands_config import OpenHandsConfig
from openhands.events.action import MessageAction
from openhands.events.event import EventSource
from openhands.events.event_store import EventStore
from openhands.llm.llm_registry import LLMRegistry
-from openhands.server.conversation_manager.standalone_conversation_manager import (
- StandaloneConversationManager,
-)
-from openhands.server.monitoring import MonitoringListener
from openhands.storage.data_models.settings import Settings
from openhands.storage.memory import InMemoryFileStore
from openhands.utils.conversation_summary import auto_generate_title
@@ -167,65 +162,3 @@ async def test_auto_generate_title_no_messages():
mock_event_store_cls.assert_called_once_with(
conversation_id, file_store, user_id
)
-
-
-async def test_update_conversation_with_title():
- """Test that _update_conversation_for_event updates the title when needed."""
- # Mock dependencies
- sio = MagicMock()
- sio.emit = AsyncMock()
- file_store = InMemoryFileStore()
- server_config = MagicMock()
- llm_registry = MagicMock(spec=LLMRegistry)
-
- # Create test conversation
- conversation_id = 'test-conversation'
- user_id = 'test-user'
-
- # Create test settings
- settings = Settings(
- llm_model='test-model',
- llm_api_key='test-key',
- llm_base_url='test-url',
- )
-
- # Mock the conversation store and metadata
- mock_conversation_store = AsyncMock()
- mock_metadata = MagicMock()
- mock_metadata.title = f'Conversation {conversation_id[:5]}' # Default title
- mock_conversation_store.get_metadata.return_value = mock_metadata
-
- # Create the conversation manager
- manager = StandaloneConversationManager(
- sio=sio,
- config=OpenHandsConfig(),
- file_store=file_store,
- server_config=server_config,
- monitoring_listener=MonitoringListener(),
- )
-
- # Mock the _get_conversation_store method
- manager._get_conversation_store = AsyncMock(return_value=mock_conversation_store)
-
- # Mock the auto_generate_title function
- with patch(
- 'openhands.server.conversation_manager.standalone_conversation_manager.auto_generate_title',
- AsyncMock(return_value='Generated Title'),
- ):
- # Call the method
- await manager._update_conversation_for_event(
- user_id, conversation_id, settings, llm_registry
- )
-
- # Verify the title was updated
- assert mock_metadata.title == 'Generated Title'
-
- # Verify the socket.io emit was called with the correct parameters
- sio.emit.assert_called_once()
- call_args = sio.emit.call_args[0]
- assert call_args[0] == 'oh_event'
- assert call_args[1]['status_update'] is True
- assert call_args[1]['type'] == 'info'
- assert call_args[1]['message'] == conversation_id
- assert call_args[1]['conversation_title'] == 'Generated Title'