π OpenHands: AI-Driven Development
Fix type signatures for mypy compliance + V1 GitLab Support (#13171)
Rohit Malhotra6822169594b7
diff --git a/enterprise/integrations/gitlab/gitlab_manager.py b/enterprise/integrations/gitlab/gitlab_manager.pyindex be6cb49a6f..9fbe5d46eb 100644--- a/enterprise/integrations/gitlab/gitlab_manager.py+++ b/enterprise/integrations/gitlab/gitlab_manager.py@@ -20,6 +20,7 @@ from integrations.utils import (OPENHANDS_RESOLVER_TEMPLATES_DIR,get_session_expired_message,)+from integrations.v1_utils import get_saas_user_authfrom jinja2 import Environment, FileSystemLoaderfrom pydantic import SecretStrfrom server.auth.token_manager import TokenManager@@ -214,8 +215,18 @@ class GitlabManager(Manager[GitlabViewType]):))+ # Initialize conversation and get metadata (following GitHub pattern)+ convo_metadata = await gitlab_view.initialize_new_conversation()++ saas_user_auth = await get_saas_user_auth(+ gitlab_view.user_info.keycloak_user_id, self.token_manager+ )+await gitlab_view.create_new_conversation(- self.jinja_env, secret_store.provider_tokens+ self.jinja_env,+ secret_store.provider_tokens,+ convo_metadata,+ saas_user_auth,)conversation_id = gitlab_view.conversation_id@@ -224,18 +235,19 @@ class GitlabManager(Manager[GitlabViewType]):f'[GitLab] Created conversation {conversation_id} for user {user_info.username}')- # Create a GitlabCallbackProcessor for this conversation- processor = GitlabCallbackProcessor(- gitlab_view=gitlab_view,- send_summary_instruction=True,- )+ 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)+ # Register the callback processor+ register_callback_processor(conversation_id, processor)- logger.info(- f'[GitLab] Created callback processor for conversation {conversation_id}'- )+ logger.info(+ f'[GitLab] Created callback processor for conversation {conversation_id}'+ )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_v1_callback_processor.py b/enterprise/integrations/gitlab/gitlab_v1_callback_processor.pynew file mode 100644index 0000000000..fcb3c24cb2--- /dev/null+++ b/enterprise/integrations/gitlab/gitlab_v1_callback_processor.py@@ -0,0 +1,277 @@+import logging+from typing import Any+from uuid import UUID++import httpx+from integrations.utils import CONVERSATION_URL, get_summary_instruction+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++_logger = logging.getLogger(__name__)+++class GitlabV1CallbackProcessor(EventCallbackProcessor):+ """Callback processor for GitLab V1 integrations."""++ gitlab_view_data: dict[str, Any] = Field(default_factory=dict)+ should_request_summary: bool = Field(default=True)+ inline_mr_comment: bool = Field(default=False)++ async def __call__(+ self,+ conversation_id: UUID,+ callback: EventCallback,+ event: Event,+ ) -> EventCallbackResult | None:+ """Process events for GitLab V1 integration."""+ # Only handle ConversationStateUpdateEvent+ if not isinstance(event, ConversationStateUpdateEvent):+ return None++ # Only act when execution has finished+ if not (event.key == 'execution_status' and event.value == 'finished'):+ return None++ _logger.info('[GitLab V1] Callback agent state was %s', event)+ _logger.info(+ '[GitLab V1] 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'[GitLab V1] Requesting summary {conversation_id}')+ summary = await self._request_summary(conversation_id)+ _logger.info(+ f'[GitLab V1] Posting summary {conversation_id}',+ extra={'summary': summary},+ )+ await self._post_summary_to_gitlab(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('[GitLab V1] Error processing callback: %s', e)++ # Only try to post error to GitLab if we have basic requirements+ try:+ if self.gitlab_view_data.get('keycloak_user_id'):+ await self._post_summary_to_gitlab(+ f'OpenHands encountered an error: **{str(e)}**.\n\n'+ f'[See the conversation]({CONVERSATION_URL.format(conversation_id)}) '+ 'for more information.'+ )+ except Exception as post_error:+ _logger.warning(+ '[GitLab V1] Failed to post error message to GitLab: %s', post_error+ )++ return EventCallbackResult(+ status=EventCallbackResultStatus.ERROR,+ event_callback_id=callback.id,+ event_id=event.id,+ conversation_id=conversation_id,+ detail=str(e),+ )++ # -------------------------------------------------------------------------+ # GitLab helpers+ # -------------------------------------------------------------------------++ async def _post_summary_to_gitlab(self, summary: str) -> None:+ """Post a summary comment to the configured GitLab issue or MR."""+ # Import here to avoid circular imports+ from integrations.gitlab.gitlab_service import SaaSGitLabService++ from openhands.integrations.gitlab.gitlab_service import GitLabServiceImpl++ keycloak_user_id = self.gitlab_view_data.get('keycloak_user_id')+ if not keycloak_user_id:+ raise RuntimeError('Missing keycloak user ID for GitLab')++ gitlab_service: SaaSGitLabService = GitLabServiceImpl(+ external_auth_id=keycloak_user_id+ )++ project_id = self.gitlab_view_data['project_id']+ issue_number = self.gitlab_view_data['issue_number']+ discussion_id = self.gitlab_view_data.get('discussion_id')+ is_mr = self.gitlab_view_data.get('is_mr', False)++ if is_mr:+ await gitlab_service.reply_to_mr(+ project_id,+ issue_number,+ discussion_id,+ summary,+ )+ else:+ await gitlab_service.reply_to_issue(+ project_id,+ issue_number,+ discussion_id,+ summary,+ )++ # -------------------------------------------------------------------------+ # Agent / sandbox helpers+ # -------------------------------------------------------------------------++ 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: # noqa: BLE001+ pass++ _logger.error(+ '[GitLab V1] HTTP error sending message to %s: %s. '+ 'Request payload: %s. Response headers: %s',+ url,+ error_detail,+ payload,+ dict(e.response.headers),+ exc_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.error(+ '[GitLab V1] %s. Request payload: %s',+ error_detail,+ payload,+ exc_info=True,+ )+ raise Exception(error_detail)++ except httpx.RequestError as e:+ error_detail = f'Request error to {url}: {str(e)}'+ _logger.error(+ '[GitLab V1] %s. Request payload: %s',+ error_detail,+ payload,+ exc_info=True,+ )+ raise Exception(error_detail)++ # -------------------------------------------------------------------------+ # Summary orchestration+ # -------------------------------------------------------------------------++ async def _request_summary(self, conversation_id: UUID) -> str:+ """Ask the agent to produce a summary of its work and return the agent response.++ NOTE: This method now returns a string (the agent server's response text)+ and raises exceptions on errors. The wrapping into EventCallbackResult+ is handled by __call__.+ """+ # 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,+ )diff --git a/enterprise/integrations/gitlab/gitlab_view.py b/enterprise/integrations/gitlab/gitlab_view.pyindex 924d18dcd6..8bb0f22868 100644--- a/enterprise/integrations/gitlab/gitlab_view.py+++ b/enterprise/integrations/gitlab/gitlab_view.py@@ -1,24 +1,53 @@from dataclasses import dataclass+from uuid import UUID, uuid4from integrations.models import Message+from integrations.resolver_context import ResolverUserContextfrom integrations.types import ResolverViewInterface, UserData-from integrations.utils import HOST, get_oh_labels, has_exact_mention+from integrations.utils import (+ ENABLE_V1_GITLAB_RESOLVER,+ HOST,+ get_oh_labels,+ get_user_v1_enabled_setting,+ has_exact_mention,+)from jinja2 import Environmentfrom server.auth.token_manager import TokenManagerfrom server.config import get_configfrom storage.saas_secrets_store import SaasSecretsStore+from openhands.agent_server.models import SendMessageRequest+from openhands.app_server.app_conversation.app_conversation_models import (+ AppConversationStartRequest,+ AppConversationStartTaskStatus,+)+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_ATTRfrom openhands.core.logger import openhands_logger as loggerfrom openhands.integrations.gitlab.gitlab_service import GitLabServiceImplfrom openhands.integrations.provider import PROVIDER_TOKEN_TYPE, ProviderTypefrom openhands.integrations.service_types import Comment-from openhands.server.services.conversation_service import create_new_conversation-from openhands.storage.data_models.conversation_metadata import ConversationTrigger+from openhands.sdk import TextContent+from openhands.server.services.conversation_service import (+ initialize_conversation,+ start_conversation,+)+from openhands.server.user_auth.user_auth import UserAuth+from openhands.storage.data_models.conversation_metadata import (+ ConversationMetadata,+ ConversationTrigger,+)OH_LABEL, INLINE_OH_LABEL = get_oh_labels(HOST)CONFIDENTIAL_NOTE = 'confidential_note'NOTE_TYPES = ['note', CONFIDENTIAL_NOTE]++async def is_v1_enabled_for_gitlab_resolver(user_id: str) -> bool:+ return await get_user_v1_enabled_setting(user_id) and ENABLE_V1_GITLAB_RESOLVER++# =================================================# SECTION: Factory to create appriorate Gitlab view# =================================================@@ -40,6 +69,10 @@ class GitlabIssue(ResolverViewInterface):description: strprevious_comments: list[Comment]is_mr: bool+ v1_enabled: bool++ def _get_branch_name(self) -> str | None:+ return getattr(self, 'branch_name', None)async def _load_resolver_context(self):gitlab_service = GitLabServiceImpl(@@ -82,28 +115,153 @@ class GitlabIssue(ResolverViewInterface):return user_secrets.custom_secrets if user_secrets else None+ async def initialize_new_conversation(self) -> ConversationMetadata:+ # v1_enabled is already set at construction time in the factory method+ # This is the source of truth for the conversation type+ if self.v1_enabled:+ # Create dummy conversation metadata+ # Don't save to conversation store+ # V1 conversations are stored in a separate table+ self.conversation_id = uuid4().hex+ return ConversationMetadata(+ conversation_id=self.conversation_id,+ selected_repository=self.full_repo_name,+ )++ conversation_metadata: ConversationMetadata = await initialize_conversation( # type: ignore[assignment]+ user_id=self.user_info.keycloak_user_id,+ conversation_id=None,+ selected_repository=self.full_repo_name,+ selected_branch=self._get_branch_name(),+ conversation_trigger=ConversationTrigger.RESOLVER,+ git_provider=ProviderType.GITLAB,+ )++ self.conversation_id = conversation_metadata.conversation_id+ return conversation_metadata+async def create_new_conversation(- self, jinja_env: Environment, git_provider_tokens: PROVIDER_TOKEN_TYPE+ self,+ jinja_env: Environment,+ git_provider_tokens: PROVIDER_TOKEN_TYPE,+ 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)- agent_loop_info = await create_new_conversation(++ await start_conversation(user_id=self.user_info.keycloak_user_id,git_provider_tokens=git_provider_tokens,custom_secrets=custom_secrets,- selected_repository=self.full_repo_name,- selected_branch=None,initial_user_msg=user_instructions,- conversation_instructions=conversation_instructions,image_urls=None,- conversation_trigger=ConversationTrigger.RESOLVER,replay_json=None,+ conversation_id=conversation_metadata.conversation_id,+ conversation_metadata=conversation_metadata,+ conversation_instructions=conversation_instructions,+ )++ async def _create_v1_conversation(+ self,+ jinja_env: Environment,+ saas_user_auth: UserAuth,+ conversation_metadata: ConversationMetadata,+ ):+ """Create conversation using the new V1 app conversation system."""+ logger.info('[GitLab V1]: Creating V1 conversation')++ user_instructions, conversation_instructions = await self._get_instructions(+ jinja_env+ )++ # Create the initial message request+ initial_message = SendMessageRequest(+ role='user', content=[TextContent(text=user_instructions)]+ )++ # Create the GitLab V1 callback processor+ gitlab_callback_processor = self._create_gitlab_v1_callback_processor()++ # Get the app conversation service and start the conversation+ injector_state = InjectorState()++ # Determine the title based on whether it's an MR or issue+ title_prefix = 'GitLab MR' if self.is_mr else 'GitLab Issue'+ title = f'{title_prefix} #{self.issue_number}: {self.title}'++ # Create the V1 conversation start request with the callback processor+ start_request = AppConversationStartRequest(+ conversation_id=UUID(conversation_metadata.conversation_id),+ system_message_suffix=conversation_instructions,+ initial_message=initial_message,+ selected_repository=self.full_repo_name,+ selected_branch=self._get_branch_name(),+ git_provider=ProviderType.GITLAB,+ title=title,+ trigger=ConversationTrigger.RESOLVER,+ processors=[+ gitlab_callback_processor+ ], # Pass the callback processor directly+ )++ # Set up the GitLab user context for the V1 system+ gitlab_user_context = ResolverUserContext(saas_user_auth=saas_user_auth)+ setattr(injector_state, USER_CONTEXT_ATTR, gitlab_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}'+ )++ def _create_gitlab_v1_callback_processor(self):+ """Create a V1 callback processor for GitLab integration."""+ from integrations.gitlab.gitlab_v1_callback_processor import (+ GitlabV1CallbackProcessor,+ )++ # Create and return the GitLab V1 callback processor+ return GitlabV1CallbackProcessor(+ gitlab_view_data={+ 'issue_number': self.issue_number,+ 'project_id': self.project_id,+ 'full_repo_name': self.full_repo_name,+ 'installation_id': self.installation_id,+ 'keycloak_user_id': self.user_info.keycloak_user_id,+ 'is_mr': self.is_mr,+ 'discussion_id': getattr(self, 'discussion_id', None),+ },+ send_summary_instruction=self.send_summary_instruction,)- self.conversation_id = agent_loop_info.conversation_id- return self.conversation_id@dataclass@@ -138,6 +296,9 @@ class GitlabIssueComment(GitlabIssue):class GitlabMRComment(GitlabIssueComment):branch_name: str+ def _get_branch_name(self) -> str | None:+ return self.branch_name+async def _get_instructions(self, jinja_env: Environment) -> tuple[str, str]:user_instructions_template = jinja_env.get_template('mr_update_prompt.j2')await self._load_resolver_context()@@ -159,29 +320,6 @@ class GitlabMRComment(GitlabIssueComment):return user_instructions, conversation_instructions- async def create_new_conversation(- self, jinja_env: Environment, git_provider_tokens: PROVIDER_TOKEN_TYPE- ):- custom_secrets = await self._get_user_secrets()-- user_instructions, conversation_instructions = await self._get_instructions(- jinja_env- )- agent_loop_info = await create_new_conversation(- user_id=self.user_info.keycloak_user_id,- git_provider_tokens=git_provider_tokens,- custom_secrets=custom_secrets,- selected_repository=self.full_repo_name,- selected_branch=self.branch_name,- initial_user_msg=user_instructions,- conversation_instructions=conversation_instructions,- image_urls=None,- conversation_trigger=ConversationTrigger.RESOLVER,- replay_json=None,- )- self.conversation_id = agent_loop_info.conversation_id- return self.conversation_id-@dataclassclass GitlabInlineMRComment(GitlabMRComment):@@ -322,6 +460,12 @@ class GitlabFactory:user_id=user_id, username=username, keycloak_user_id=keycloak_user_id)+ # Check v1_enabled at construction time - this is the source of truth+ v1_enabled = await is_v1_enabled_for_gitlab_resolver(keycloak_user_id)+ logger.info(+ f'[GitLab V1]: User flag found for {keycloak_user_id} is {v1_enabled}'+ )+if GitlabFactory.is_labeled_issue(message):issue_iid = payload['object_attributes']['iid']@@ -343,6 +487,7 @@ class GitlabFactory:description='',previous_comments=[],is_mr=False,+ v1_enabled=v1_enabled,)elif GitlabFactory.is_issue_comment(message):@@ -373,6 +518,7 @@ class GitlabFactory:description='',previous_comments=[],is_mr=False,+ v1_enabled=v1_enabled,)elif GitlabFactory.is_mr_comment(message):@@ -405,6 +551,7 @@ class GitlabFactory:description='',previous_comments=[],is_mr=True,+ v1_enabled=v1_enabled,)elif GitlabFactory.is_mr_comment(message, inline=True):@@ -445,6 +592,7 @@ class GitlabFactory:description='',previous_comments=[],is_mr=True,+ v1_enabled=v1_enabled,)raise ValueError(f'Unhandled GitLab webhook event: {message}')diff --git a/enterprise/integrations/types.py b/enterprise/integrations/types.pyindex 7b7446fe82..6ecd83a93e 100644--- a/enterprise/integrations/types.py+++ b/enterprise/integrations/types.py@@ -1,9 +1,17 @@from dataclasses import dataclassfrom enum import Enum+from typing import TYPE_CHECKINGfrom jinja2 import Environmentfrom pydantic import BaseModel+if TYPE_CHECKING:+ from integrations.models import Message++ from openhands.integrations.provider import PROVIDER_TOKEN_TYPE+ from openhands.server.user_auth.user_auth import UserAuth+ from openhands.storage.data_models.conversation_metadata import ConversationMetadata+class GitLabResourceType(Enum):GROUP = 'group'@@ -31,17 +39,41 @@ class SummaryExtractionTracker:@dataclassclass ResolverViewInterface(SummaryExtractionTracker):- installation_id: int+ # installation_id type varies by provider:+ # - GitHub: int (GitHub App installation ID)+ # - GitLab: str (webhook installation ID from our DB)+ installation_id: int | struser_info: UserDataissue_number: intfull_repo_name: stris_public_repo: bool- raw_payload: dict+ raw_payload: 'Message'async def _get_instructions(self, jinja_env: Environment) -> tuple[str, str]:- "Instructions passed when conversation is first initialized"+ """Instructions passed when conversation is first initialized."""+ raise NotImplementedError()++ async def initialize_new_conversation(self) -> 'ConversationMetadata':+ """Initialize a new conversation and return metadata.++ For V1 conversations, creates a dummy ConversationMetadata.+ For V0 conversations, initializes through the conversation store.+ """raise NotImplementedError()- async def create_new_conversation(self, jinja_env: Environment, token: str):- "Create a new conversation"+ async def create_new_conversation(+ self,+ jinja_env: Environment,+ git_provider_tokens: 'PROVIDER_TOKEN_TYPE',+ conversation_metadata: 'ConversationMetadata',+ saas_user_auth: 'UserAuth',+ ) -> None:+ """Create a new conversation.++ Args:+ jinja_env: Jinja2 environment for template rendering+ git_provider_tokens: Token mapping for git providers+ conversation_metadata: Metadata for the conversation+ saas_user_auth: User authentication for SaaS+ """raise NotImplementedError()diff --git a/enterprise/integrations/utils.py b/enterprise/integrations/utils.pyindex 6b2cbcd042..b038c0c542 100644--- a/enterprise/integrations/utils.py+++ b/enterprise/integrations/utils.py@@ -32,7 +32,8 @@ if TYPE_CHECKING:HOST = WEB_HOST# ---- DO NOT REMOVE -----HOST_URL = f'https://{HOST}' if 'localhost' not in HOST else f'http://{HOST}'+IS_LOCAL_DEPLOYMENT = 'localhost' in HOST+HOST_URL = f'https://{HOST}' if not IS_LOCAL_DEPLOYMENT else f'http://{HOST}'GITHUB_WEBHOOK_URL = f'{HOST_URL}/integration/github/events'GITLAB_WEBHOOK_URL = f'{HOST_URL}/integration/gitlab/events'conversation_prefix = 'conversations/{}'@@ -78,6 +79,11 @@ ENABLE_V1_SLACK_RESOLVER = (os.getenv('ENABLE_V1_SLACK_RESOLVER', 'false').lower() == 'true')+# Toggle for V1 GitLab resolver feature+ENABLE_V1_GITLAB_RESOLVER = (+ os.getenv('ENABLE_V1_GITLAB_RESOLVER', 'false').lower() == 'true'+)+OPENHANDS_RESOLVER_TEMPLATES_DIR = (os.getenv('OPENHANDS_RESOLVER_TEMPLATES_DIR')or 'openhands/integrations/templates/resolver/'diff --git a/enterprise/server/routes/integration/gitlab.py b/enterprise/server/routes/integration/gitlab.pyindex acdb93c6fa..2b6cbe6fd5 100644--- a/enterprise/server/routes/integration/gitlab.py+++ b/enterprise/server/routes/integration/gitlab.py@@ -13,7 +13,7 @@ from integrations.gitlab.webhook_installation import ()from integrations.models import Message, SourceTypefrom integrations.types import GitLabResourceType-from integrations.utils import GITLAB_WEBHOOK_URL+from integrations.utils import GITLAB_WEBHOOK_URL, IS_LOCAL_DEPLOYMENTfrom pydantic import BaseModelfrom server.auth.token_manager import TokenManagerfrom storage.gitlab_webhook import GitlabWebhook@@ -68,9 +68,12 @@ async def verify_gitlab_signature(if not header_webhook_secret or not webhook_uuid or not user_id:raise HTTPException(status_code=403, detail='Required payload headers missing!')- webhook_secret = await webhook_store.get_webhook_secret(- webhook_uuid=webhook_uuid, user_id=user_id- )+ if IS_LOCAL_DEPLOYMENT:+ webhook_secret = 'localdeploymentwebhooktesttoken'+ else:+ webhook_secret = await webhook_store.get_webhook_secret(+ webhook_uuid=webhook_uuid, user_id=user_id+ )if header_webhook_secret != webhook_secret:raise HTTPException(status_code=403, detail="Request signatures didn't match!")diff --git a/enterprise/tests/unit/integrations/gitlab/test_gitlab_manager.py b/enterprise/tests/unit/integrations/gitlab/test_gitlab_manager.pynew file mode 100644index 0000000000..535f44a0e1--- /dev/null+++ b/enterprise/tests/unit/integrations/gitlab/test_gitlab_manager.py@@ -0,0 +1,286 @@+"""+Tests for GitlabManager V0/V1 conditional job creation flow.++Covers:+- V0 path: register_callback_processor is called+- V1 path: register_callback_processor is NOT called (V1 uses event callbacks instead)+"""++from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from integrations.gitlab.gitlab_view import GitlabIssue+from integrations.types import UserData++from openhands.storage.data_models.conversation_metadata import ConversationMetadata+++def mock_gitlab_view_v0():+ """Create a mock GitlabIssue view with V1 disabled (V0 path)."""+ 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_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',+ should_extract=True,+ send_summary_instruction=True,+ title='Test Issue',+ description='Test description',+ previous_comments=[],+ is_mr=False,+ v1_enabled=True,+ )+++def mock_token_manager():+ """Create a mock TokenManager."""+ token_manager = MagicMock()+ token_manager.get_idp_token_from_idp_user_id = AsyncMock(return_value='test_token')+ token_manager.get_user_id_from_idp_user_id = AsyncMock(+ return_value='keycloak_test_user'+ )+ return token_manager+++def mock_saas_user_auth():+ """Create a mock SaasUserAuth."""+ return MagicMock()+++def mock_convo_metadata():+ """Create a mock ConversationMetadata."""+ return ConversationMetadata(+ conversation_id='test_conversation_id',+ selected_repository='test-group/test-repo',+ )+++class TestGitlabManagerV0V1ConditionalJobCreation:+ """Test the conditional V0/V1 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(+ 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 V0 path calls register_callback_processor for legacy callback handling."""+ 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(+ return_value=mock_convo_metadata+ )+ mock_gitlab_view_v0.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()++ # 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'++ # 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 Truediff --git a/enterprise/tests/unit/integrations/gitlab/test_gitlab_v1_callback_processor.py b/enterprise/tests/unit/integrations/gitlab/test_gitlab_v1_callback_processor.pynew file mode 100644index 0000000000..edc50f1477--- /dev/null+++ b/enterprise/tests/unit/integrations/gitlab/test_gitlab_v1_callback_processor.py@@ -0,0 +1,376 @@+"""+Tests for the GitlabV1CallbackProcessor.++Covers:+- Event filtering+- Successful summary + GitLab posting+- Error conditions (missing keycloak_user_id)+- Post to issue vs MR+"""++from unittest.mock import AsyncMock, MagicMock, patch+from uuid import uuid4++import pytest+from integrations.gitlab.gitlab_v1_callback_processor import (+ GitlabV1CallbackProcessor,+)++from openhands.app_server.app_conversation.app_conversation_models import (+ AppConversationInfo,+)+from openhands.app_server.event_callback.event_callback_models import EventCallback+from openhands.app_server.event_callback.event_callback_result_models import (+ EventCallbackResultStatus,+)+from openhands.app_server.sandbox.sandbox_models import (+ ExposedUrl,+ SandboxInfo,+ SandboxStatus,+)+from openhands.events.action.message import MessageAction+from openhands.sdk.event import ConversationStateUpdateEvent++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------+++def gitlab_callback_processor():+ return GitlabV1CallbackProcessor(+ gitlab_view_data={+ 'keycloak_user_id': 'test_keycloak_user',+ 'project_id': '12345',+ 'issue_number': '42',+ 'discussion_id': 'discussion_123',+ 'is_mr': False,+ },+ should_request_summary=True,+ inline_mr_comment=False,+ )+++def gitlab_callback_processor_mr():+ return GitlabV1CallbackProcessor(+ gitlab_view_data={+ 'keycloak_user_id': 'test_keycloak_user',+ 'project_id': '12345',+ 'issue_number': '42',+ 'discussion_id': 'discussion_123',+ 'is_mr': True,+ },+ should_request_summary=True,+ inline_mr_comment=True,+ )+++def conversation_state_update_event():+ return ConversationStateUpdateEvent(key='execution_status', value='finished')+++def wrong_event():+ return MessageAction(content='Hello world')+++def wrong_state_event():+ return ConversationStateUpdateEvent(key='execution_status', value='running')+++def event_callback():+ return EventCallback(+ id=uuid4(),+ conversation_id=uuid4(),+ processor=GitlabV1CallbackProcessor(),+ event_kind='ConversationStateUpdateEvent',+ )+++def mock_app_conversation_info():+ return AppConversationInfo(+ conversation_id=uuid4(),+ sandbox_id='sandbox_123',+ title='Test Conversation',+ created_by_user_id='test_user_123',+ )+++def mock_sandbox_info():+ return SandboxInfo(+ id='sandbox_123',+ status=SandboxStatus.RUNNING,+ session_api_key='test_api_key',+ created_by_user_id='test_user_123',+ sandbox_spec_id='spec_123',+ exposed_urls=[+ ExposedUrl(name='AGENT_SERVER', url='http://localhost:8000', port=8000),+ ],+ )+++# ---------------------------------------------------------------------------+# Helper for common service mocks+# ---------------------------------------------------------------------------+++async def _setup_happy_path_services(+ mock_get_app_conversation_info_service,+ mock_get_sandbox_service,+ mock_get_httpx_client,+ app_conversation_info,+ sandbox_info,+ agent_response_text='Test summary from agent',+):+ # app_conversation_info_service+ mock_app_conversation_info_service = AsyncMock()+ mock_app_conversation_info_service.get_app_conversation_info.return_value = (+ app_conversation_info+ )+ mock_get_app_conversation_info_service.return_value.__aenter__.return_value = (+ mock_app_conversation_info_service+ )++ # sandbox_service+ mock_sandbox_service = AsyncMock()+ mock_sandbox_service.get_sandbox.return_value = sandbox_info+ mock_get_sandbox_service.return_value.__aenter__.return_value = mock_sandbox_service++ # httpx_client+ mock_httpx_client = AsyncMock()+ mock_response = MagicMock()+ mock_response.json.return_value = {'response': agent_response_text}+ mock_response.raise_for_status.return_value = None+ mock_httpx_client.post.return_value = mock_response+ mock_get_httpx_client.return_value.__aenter__.return_value = mock_httpx_client++ return mock_httpx_client+++# ---------------------------------------------------------------------------+# Tests+# ---------------------------------------------------------------------------+++class TestGitlabV1CallbackProcessor:+ async def test_call_with_wrong_event_type(+ self, gitlab_callback_processor, wrong_event, event_callback+ ):+ result = await gitlab_callback_processor(+ conversation_id=uuid4(),+ callback=event_callback,+ event=wrong_event,+ )+ assert result is None++ async def test_call_with_wrong_state_event(+ self, gitlab_callback_processor, wrong_state_event, event_callback+ ):+ result = await gitlab_callback_processor(+ conversation_id=uuid4(),+ callback=event_callback,+ event=wrong_state_event,+ )+ assert result is None++ async def test_call_should_request_summary_false(+ self, gitlab_callback_processor, conversation_state_update_event, event_callback+ ):+ gitlab_callback_processor.should_request_summary = False++ result = await gitlab_callback_processor(+ conversation_id=uuid4(),+ callback=event_callback,+ event=conversation_state_update_event,+ )+ assert result is None++ # ------------------------------------------------------------------ #+ # Successful paths+ # ------------------------------------------------------------------ #++ @patch('openhands.app_server.config.get_app_conversation_info_service')+ @patch('openhands.app_server.config.get_sandbox_service')+ @patch('openhands.app_server.config.get_httpx_client')+ @patch('integrations.gitlab.gitlab_v1_callback_processor.get_summary_instruction')+ @patch('openhands.integrations.gitlab.gitlab_service.GitLabServiceImpl')+ async def test_successful_callback_execution_issue(+ self,+ mock_gitlab_service_impl,+ mock_get_summary_instruction,+ mock_get_httpx_client,+ mock_get_sandbox_service,+ mock_get_app_conversation_info_service,+ gitlab_callback_processor,+ conversation_state_update_event,+ event_callback,+ mock_app_conversation_info,+ mock_sandbox_info,+ ):+ conversation_id = uuid4()++ # Common service mocks+ mock_httpx_client = await _setup_happy_path_services(+ mock_get_app_conversation_info_service,+ mock_get_sandbox_service,+ mock_get_httpx_client,+ mock_app_conversation_info,+ mock_sandbox_info,+ )++ mock_get_summary_instruction.return_value = 'Please provide a summary'++ # GitLab service mock+ mock_gitlab_service = AsyncMock()+ mock_gitlab_service_impl.return_value = mock_gitlab_service++ result = await gitlab_callback_processor(+ conversation_id=conversation_id,+ callback=event_callback,+ event=conversation_state_update_event,+ )++ assert result is not None+ assert result.status == EventCallbackResultStatus.SUCCESS+ assert result.event_callback_id == event_callback.id+ assert result.event_id == conversation_state_update_event.id+ assert result.conversation_id == conversation_id+ assert result.detail == 'Test summary from agent'+ assert gitlab_callback_processor.should_request_summary is False++ # Verify GitLab service was called correctly for issue+ mock_gitlab_service_impl.assert_called_once_with(+ external_auth_id='test_keycloak_user'+ )+ mock_gitlab_service.reply_to_issue.assert_called_once_with(+ '12345', '42', 'discussion_123', 'Test summary from agent'+ )+ mock_gitlab_service.reply_to_mr.assert_not_called()++ # Verify httpx call+ mock_httpx_client.post.assert_called_once()+ url_arg, kwargs = mock_httpx_client.post.call_args+ url = url_arg[0] if url_arg else kwargs['url']+ assert 'ask_agent' in url+ assert kwargs['headers']['X-Session-API-Key'] == 'test_api_key'+ assert kwargs['json']['question'] == 'Please provide a summary'++ @patch('openhands.app_server.config.get_app_conversation_info_service')+ @patch('openhands.app_server.config.get_sandbox_service')+ @patch('openhands.app_server.config.get_httpx_client')+ @patch('integrations.gitlab.gitlab_v1_callback_processor.get_summary_instruction')+ @patch('openhands.integrations.gitlab.gitlab_service.GitLabServiceImpl')+ async def test_successful_callback_execution_mr(+ self,+ mock_gitlab_service_impl,+ mock_get_summary_instruction,+ mock_get_httpx_client,+ mock_get_sandbox_service,+ mock_get_app_conversation_info_service,+ gitlab_callback_processor_mr,+ conversation_state_update_event,+ event_callback,+ mock_app_conversation_info,+ mock_sandbox_info,+ ):+ conversation_id = uuid4()++ await _setup_happy_path_services(+ mock_get_app_conversation_info_service,+ mock_get_sandbox_service,+ mock_get_httpx_client,+ mock_app_conversation_info,+ mock_sandbox_info,+ )++ mock_get_summary_instruction.return_value = 'Please provide a summary'++ # GitLab service mock+ mock_gitlab_service = AsyncMock()+ mock_gitlab_service_impl.return_value = mock_gitlab_service++ result = await gitlab_callback_processor_mr(+ conversation_id=conversation_id,+ callback=event_callback,+ event=conversation_state_update_event,+ )++ assert result is not None+ assert result.status == EventCallbackResultStatus.SUCCESS++ # Verify GitLab service was called correctly for MR+ mock_gitlab_service.reply_to_mr.assert_called_once_with(+ '12345', '42', 'discussion_123', 'Test summary from agent'+ )+ mock_gitlab_service.reply_to_issue.assert_not_called()++ # ------------------------------------------------------------------ #+ # Error paths+ # ------------------------------------------------------------------ #++ async def test_post_summary_to_gitlab_missing_keycloak_user_id(+ self, gitlab_callback_processor+ ):+ gitlab_callback_processor.gitlab_view_data['keycloak_user_id'] = None++ with pytest.raises(RuntimeError, match='Missing keycloak user ID for GitLab'):+ await gitlab_callback_processor._post_summary_to_gitlab('Test summary')++ @patch('openhands.app_server.config.get_app_conversation_info_service')+ @patch('openhands.app_server.config.get_sandbox_service')+ @patch('openhands.app_server.config.get_httpx_client')+ @patch('integrations.gitlab.gitlab_v1_callback_processor.get_summary_instruction')+ @patch('openhands.integrations.gitlab.gitlab_service.GitLabServiceImpl')+ async def test_exception_handling_posts_error_to_gitlab(+ self,+ mock_gitlab_service_impl,+ mock_get_summary_instruction,+ mock_get_httpx_client,+ mock_get_sandbox_service,+ mock_get_app_conversation_info_service,+ gitlab_callback_processor,+ conversation_state_update_event,+ event_callback,+ mock_app_conversation_info,+ mock_sandbox_info,+ ):+ conversation_id = uuid4()++ # Setup services, but make httpx fail+ mock_httpx_client = await _setup_happy_path_services(+ mock_get_app_conversation_info_service,+ mock_get_sandbox_service,+ mock_get_httpx_client,+ mock_app_conversation_info,+ mock_sandbox_info,+ )+ mock_httpx_client.post.side_effect = Exception('Simulated agent server error')+ mock_get_summary_instruction.return_value = 'Please provide a summary'++ # GitLab service mock+ mock_gitlab_service = AsyncMock()+ mock_gitlab_service_impl.return_value = mock_gitlab_service++ result = await gitlab_callback_processor(+ conversation_id=conversation_id,+ callback=event_callback,+ event=conversation_state_update_event,+ )++ assert result is not None+ assert result.status == EventCallbackResultStatus.ERROR+ assert 'Simulated agent server error' in result.detail++ # Verify error was posted to GitLab+ mock_gitlab_service.reply_to_issue.assert_called_once()+ call_args = mock_gitlab_service.reply_to_issue.call_args+ error_comment = call_args[0][3] # 4th positional arg is the body+ assert 'OpenHands encountered an error' in error_comment+ assert 'Simulated agent server error' in error_comment+ assert f'conversations/{conversation_id}' in error_commentdiff --git a/enterprise/tests/unit/test_gitlab_callback_processor.py b/enterprise/tests/unit/test_gitlab_callback_processor.pyindex 3eac13b3d0..629c8cd72c 100644--- a/enterprise/tests/unit/test_gitlab_callback_processor.py+++ b/enterprise/tests/unit/test_gitlab_callback_processor.py@@ -40,6 +40,7 @@ def mock_gitlab_view():comment_body='sdfs',discussion_id='test_discussion',confidential=False,+ v1_enabled=False,)