π OpenHands: AI-Driven Development
APP-1170: Jira : add V1 conversation support and multiple bug fixes (#13909)
Tim O'Farrell0eafa9fd15ee
diff --git a/enterprise/integrations/jira/jira_manager.py b/enterprise/integrations/jira/jira_manager.pyindex e83431fa08..735f2a5bcf 100644--- a/enterprise/integrations/jira/jira_manager.py+++ b/enterprise/integrations/jira/jira_manager.py@@ -24,21 +24,20 @@ from integrations.jira.jira_types import (RepositoryNotFoundError,StartingConvoException,)-from integrations.jira.jira_view import JiraFactory, JiraNewConversationView+from integrations.jira.jira_view import JiraFactoryfrom integrations.manager import Managerfrom integrations.models import Messagefrom integrations.utils import (HOST,HOST_URL,OPENHANDS_RESOLVER_TEMPLATES_DIR,+ format_jira_comment_body,get_oh_labels,get_session_expired_message,- markdown_to_jira_markup,)from jinja2 import Environment, FileSystemLoaderfrom server.auth.saas_user_auth import get_user_auth_from_keycloak_idfrom server.auth.token_manager import TokenManager-from server.utils.conversation_callback_utils import register_callback_processorfrom storage.jira_integration_store import JiraIntegrationStorefrom storage.jira_user import JiraUserfrom storage.jira_workspace import JiraWorkspace@@ -260,11 +259,6 @@ class JiraManager(Manager[JiraViewInterface]):async def start_job(self, view: JiraViewInterface) -> None:"""Start a Jira job/conversation."""- # Import here to prevent circular import- from server.conversation_callback_processor.jira_callback_processor import (- JiraCallbackProcessor,- )-try:logger.info('[Jira] Starting job',@@ -286,19 +280,7 @@ class JiraManager(Manager[JiraViewInterface]):},)- # Register callback processor for updates- if isinstance(view, JiraNewConversationView):- processor = JiraCallbackProcessor(- issue_key=view.payload.issue_key,- workspace_name=view.jira_workspace.name,- )- register_callback_processor(conversation_id, processor)- logger.info(- '[Jira] Callback processor registered',- extra={'conversation_id': conversation_id},- )-- # Send success response+ # Create success messagemsg_info = view.get_response_msg()except MissingSettingsError as e:@@ -360,8 +342,7 @@ class JiraManager(Manager[JiraViewInterface]):url = (f'{JIRA_CLOUD_API_URL}/{jira_cloud_id}/rest/api/2/issue/{issue_key}/comment')- # Convert standard Markdown to Jira Wiki Markup for proper rendering- data = {'body': markdown_to_jira_markup(message)}+ data = format_jira_comment_body(message)async with httpx.AsyncClient(verify=httpx_verify_option()) as client:response = await client.post(url, auth=(svc_acc_email, svc_acc_api_key), json=datadiff --git a/enterprise/integrations/jira/jira_payload.py b/enterprise/integrations/jira/jira_payload.pyindex 9b0d75ecd0..c34ca4a494 100644--- a/enterprise/integrations/jira/jira_payload.py+++ b/enterprise/integrations/jira/jira_payload.py@@ -136,11 +136,10 @@ class JiraPayloadParser:items = changelog.get('items', [])# Extract labels that were added- labels = [- item.get('toString', '')- for item in items- if item.get('field') == 'labels' and 'toString' in item- ]+ labels = set()+ for item in items:+ if item.get('field') == 'labels' and item.get('toString'):+ labels.update(item['toString'].split())if self.oh_label not in labels:return JiraPayloadSkipped(diff --git a/enterprise/integrations/jira/jira_v1_callback_processor.py b/enterprise/integrations/jira/jira_v1_callback_processor.pynew file mode 100644index 0000000000..04b4697291--- /dev/null+++ b/enterprise/integrations/jira/jira_v1_callback_processor.py@@ -0,0 +1,238 @@+import logging+from uuid import UUID++import httpx+from integrations.utils import format_jira_comment_body, 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+from openhands.utils.http_session import httpx_verify_option++_logger = logging.getLogger(__name__)++JIRA_CLOUD_API_URL = 'https://api.atlassian.com/ex/jira'+++class JiraV1CallbackProcessor(EventCallbackProcessor):+ """Callback processor for Jira V1 integrations."""++ should_request_summary: bool = Field(default=True)+ svc_acc_email: str+ decrypted_api_key: str+ issue_key: str+ jira_cloud_id: str++ async def __call__(+ self,+ conversation_id: UUID,+ callback: EventCallback,+ event: Event,+ ) -> EventCallbackResult | None:+ """Process events for Jira 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] Callback agent state was %s', event)++ # Only request summary when execution has finished successfully+ if event.value != 'finished':+ return None++ _logger.info('[Jira] 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] Requesting summary {conversation_id}')+ summary = await self._request_summary(conversation_id)+ _logger.info(+ f'[Jira] Posting summary {conversation_id}',+ extra={'summary': summary},+ )+ await self._post_summary_to_jira(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] 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] 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] 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(self, summary: str):+ """Post the summary back to the Jira issue."""+ if not all(+ [+ self.svc_acc_email,+ self.decrypted_api_key,+ self.issue_key,+ self.jira_cloud_id,+ ]+ ):+ _logger.warning('[Jira] Missing required data for posting summary')+ return++ # Add a comment to the Jira issue with the summary+ comment_url = (+ f'{JIRA_CLOUD_API_URL}/{self.jira_cloud_id}'+ f'/rest/api/2/issue/{self.issue_key}/comment'+ )++ message = f'OpenHands resolved this issue:\n\n{summary}'+ comment_body = format_jira_comment_body(message)++ async with httpx.AsyncClient(verify=httpx_verify_option()) as client:+ response = await client.post(+ comment_url,+ auth=(self.svc_acc_email, self.decrypted_api_key),+ json=comment_body,+ )+ response.raise_for_status()+ _logger.info(f'[Jira] Posted summary to {self.issue_key}')diff --git a/enterprise/integrations/jira/jira_view.py b/enterprise/integrations/jira/jira_view.pyindex 2a94a15624..5088a4e1e1 100644--- a/enterprise/integrations/jira/jira_view.py+++ b/enterprise/integrations/jira/jira_view.py@@ -7,7 +7,7 @@ Views are responsible for:"""from dataclasses import dataclass, field-from uuid import uuid4+from uuid import UUID, uuid4import httpxfrom integrations.jira.jira_payload import JiraWebhookPayload@@ -16,25 +16,37 @@ from integrations.jira.jira_types import (RepositoryNotFoundError,StartingConvoException,)+from integrations.jira.jira_v1_callback_processor import (+ JiraV1CallbackProcessor,+)+from integrations.resolver_context import ResolverUserContextfrom integrations.resolver_org_router import resolve_org_for_repo-from integrations.utils import CONVERSATION_URL, infer_repo_from_message+from integrations.utils import (+ CONVERSATION_URL,+ infer_repo_from_message,+)from jinja2 import Environment-from server.config import get_configfrom storage.jira_conversation import JiraConversationfrom storage.jira_integration_store import JiraIntegrationStorefrom storage.jira_user import JiraUserfrom storage.jira_workspace import JiraWorkspace-from storage.saas_conversation_store import SaasConversationStore+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 logger-from openhands.integrations.provider import ProviderHandler-from openhands.server.services.conversation_service import start_conversation+from openhands.integrations.provider import ProviderHandler, ProviderType+from openhands.sdk import TextContentfrom openhands.server.user_auth.user_auth import UserAuthfrom openhands.storage.data_models.conversation_metadata import (ConversationMetadata,ConversationTrigger,)-from openhands.utils.conversation_summary import get_default_conversation_titlefrom openhands.utils.http_session import httpx_verify_optionJIRA_CLOUD_API_URL = 'https://api.atlassian.com/ex/jira'@@ -54,7 +66,7 @@ class JiraNewConversationView(JiraViewInterface):saas_user_auth: UserAuthjira_user: JiraUserjira_workspace: JiraWorkspace- selected_repo: str | None = None+ selected_repo: str = ''conversation_id: str = ''# Lazy-loaded issue details (cached after first fetch)@@ -64,6 +76,9 @@ class JiraNewConversationView(JiraViewInterface):# Decrypted API key (set by factory)_decrypted_api_key: str = field(default='', repr=False)+ # Resolved org ID for V1 conversations+ resolved_org_id: UUID | None = None+async def get_issue_details(self) -> tuple[str, str]:"""Fetch issue details from Jira API (cached after first call).@@ -169,107 +184,131 @@ class JiraNewConversationView(JiraViewInterface):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)+ jira_conversation = JiraConversation(+ conversation_id=self.conversation_id,+ issue_id=self.payload.issue_id,+ issue_key=self.payload.issue_key,+ jira_user_id=self.jira_user.id,+ )+ await integration_store.create_conversation(jira_conversation)- try:- user_id = self.jira_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'[Jira] Failed to resolve git provider for {self.selected_repo}: {e}'- )+ conversation_metadata = await self._create_v1_metadata()+ await self._create_v1_conversation(jinja_env, conversation_metadata)+ return self.conversation_id- # 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'[Jira] Failed to resolve org for {self.selected_repo}: {e}'- )+ async def _create_v1_metadata(self) -> ConversationMetadata:+ """Create conversation metadata for V1 conversations.- # Create the conversation store with resolver org routing- store = await SaasConversationStore.get_resolver_instance(- get_config(),- user_id,- resolved_org_id,- )+ The JiraConversation mapping is saved to the integration store (above), but+ V1 conversation metadata is managed by the app conversation system, not+ the legacy conversation store.+ """+ logger.info('[Jira]: Creating V1 metadata')- conversation_id = uuid4().hex- conversation_metadata = ConversationMetadata(- trigger=ConversationTrigger.JIRA,- 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,- )+ # Generate a dummy conversation for V1 (not saved to store)+ self.conversation_id = uuid4().hex+ self.resolved_org_id = await self._get_resolved_org_id()- self.conversation_id = conversation_id+ return ConversationMetadata(+ conversation_id=self.conversation_id,+ selected_repository=self.selected_repo,+ )- logger.info(- '[Jira] Created conversation',- extra={- 'conversation_id': self.conversation_id,- 'issue_key': self.payload.issue_key,- 'selected_repo': self.selected_repo,- 'resolved_org_id': str(resolved_org_id)- if resolved_org_id- else None,- },- )+ async def _create_v1_conversation(+ self,+ jinja_env: Environment,+ conversation_metadata: ConversationMetadata,+ ):+ """Create conversation using the new V1 app conversation system."""+ logger.info('[Jira]: Creating V1 conversation')- # Store Jira conversation mapping- jira_conversation = JiraConversation(- conversation_id=self.conversation_id,- issue_id=self.payload.issue_id,- issue_key=self.payload.issue_key,- jira_user_id=self.jira_user.id,- )+ initial_user_text = await self._get_v1_initial_user_message(jinja_env)++ # Create the initial message request+ initial_message = SendMessageRequest(+ role='user', content=[TextContent(text=initial_user_text)]+ )++ # Create the Jira V1 callback processor+ jira_callback_processor = self._create_jira_v1_callback_processor()++ injector_state = InjectorState()++ # Create the V1 conversation start request+ start_request = AppConversationStartRequest(+ conversation_id=UUID(conversation_metadata.conversation_id),+ system_message_suffix=None,+ initial_message=initial_message,+ selected_repository=self.selected_repo,+ selected_branch=None,+ git_provider=ProviderType.GITHUB,+ title=f'Jira Issue {self.payload.issue_key}: {self._issue_title or "Unknown"}',+ trigger=ConversationTrigger.JIRA,+ processors=[jira_callback_processor],+ )++ # Set up the Jira user context for the V1 system+ jira_user_context = ResolverUserContext(+ saas_user_auth=self.saas_user_auth,+ resolver_org_id=self.resolved_org_id,+ )+ setattr(injector_state, USER_CONTEXT_ATTR, jira_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}'+ )++ async def _get_v1_initial_user_message(self, jinja_env: Environment) -> str:+ """Build the initial user message for V1 resolver conversations."""+ issue_title, issue_description = await self.get_issue_details()++ user_msg_template = jinja_env.get_template('jira_new_conversation.j2')+ user_msg = user_msg_template.render(+ issue_key=self.payload.issue_key,+ issue_title=issue_title,+ issue_description=issue_description,+ user_message=self.payload.user_msg,+ )- await integration_store.create_conversation(jira_conversation)+ return user_msg- return self.conversation_id+ def _create_jira_v1_callback_processor(self):+ """Create a V1 callback processor for Jira integration."""+ return JiraV1CallbackProcessor(+ svc_acc_email=self.jira_workspace.svc_acc_email,+ decrypted_api_key=self._decrypted_api_key,+ issue_key=self.payload.issue_key,+ jira_cloud_id=self.jira_workspace.jira_cloud_id,+ )+ 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:+ return None++ 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_user.keycloak_user_id,+ )+ return resolved_org_idexcept Exception as e:- if isinstance(e, StartingConvoException):- raise- logger.error(- '[Jira] Failed to create conversation',- extra={'issue_key': self.payload.issue_key, 'error': str(e)},- exc_info=True,+ logger.warning(+ f'[Jira] Failed to resolve org for {self.selected_repo}: {e}')- raise StartingConvoException(f'Failed to create conversation: {str(e)}')+ return Nonedef get_response_msg(self) -> str:"""Get the response message to send back to Jira."""diff --git a/enterprise/integrations/utils.py b/enterprise/integrations/utils.pyindex 9adadd5ae6..74ab7b62ff 100644--- a/enterprise/integrations/utils.py+++ b/enterprise/integrations/utils.py@@ -436,12 +436,13 @@ def infer_repo_from_message(user_msg: str) -> list[str]:r'(?=\s|$|}}|[\]\)\'",.:`])' # right boundary)- matches: list[str] = []+ # Use dict to preserve ordering+ matches: dict[str, bool] = {}# Git URLs first (highest priority)for owner, repo in re.findall(git_url_pattern, normalized_msg):repo = re.sub(r'\.git$', '', repo)- matches.append(f'{owner}/{repo}')+ matches[f'{owner}/{repo}'] = True# Direct mentionsfor owner, repo in re.findall(direct_pattern, normalized_msg):@@ -457,9 +458,10 @@ def infer_repo_from_message(user_msg: str) -> list[str]:continueif full_match not in matches:- matches.append(full_match)+ matches[full_match] = True- return matches+ result = list(matches)+ return resultdef filter_potential_repos_by_user_msg(@@ -595,3 +597,18 @@ def markdown_to_jira_markup(markdown_text: str) -> str:# Log the error but don't raise it - return original text as fallbackprint(f'Error converting markdown to Jira markup: {str(e)}')return markdown_text or ''+++def format_jira_comment_body(message: str) -> dict:+ """Format a message as a Jira API v2 comment body.++ This helper ensures consistent comment formatting across all Jira integrations.+ Converts markdown to Jira Wiki Markup and wraps in the expected API structure.++ Args:+ message: The message content to send (may contain markdown)++ Returns:+ dict: The comment body in Jira API v2 format {'body': ...}+ """+ return {'body': markdown_to_jira_markup(message)}diff --git a/enterprise/server/routes/integration/jira.py b/enterprise/server/routes/integration/jira.pyindex 715128b193..e635efa491 100644--- a/enterprise/server/routes/integration/jira.py+++ b/enterprise/server/routes/integration/jira.py@@ -149,7 +149,12 @@ async def verify_jira_signature(body: bytes, signature: str, payload: dict):workspace_name = jira_manager.get_workspace_name_from_payload(payload)if workspace_name is None:- logger.warning('[Jira] No workspace name found in webhook payload')+ logger.warning(+ '[Jira] No workspace name found in webhook payload',+ extra={+ 'payload': payload,+ },+ )raise HTTPException(status_code=403, detail='Workspace name not found in payload')diff --git a/enterprise/tests/unit/integrations/jira/conftest.py b/enterprise/tests/unit/integrations/jira/conftest.pyindex b2387bb6ac..d465903eb3 100644--- a/enterprise/tests/unit/integrations/jira/conftest.py+++ b/enterprise/tests/unit/integrations/jira/conftest.py@@ -206,7 +206,7 @@ def new_conversation_view(sample_webhook_payload, sample_user_auth, sample_jira_user, sample_jira_workspace):"""JiraNewConversationView instance for testing"""- return JiraNewConversationView(+ view = JiraNewConversationView(payload=sample_webhook_payload,saas_user_auth=sample_user_auth,jira_user=sample_jira_user,@@ -215,6 +215,8 @@ def new_conversation_view(conversation_id='conv-123',_decrypted_api_key='decrypted_key',)+ view.v1_enabled = False+ return view@pytest.fixturediff --git a/enterprise/tests/unit/integrations/jira/test_jira_manager.py b/enterprise/tests/unit/integrations/jira/test_jira_manager.pyindex 8a4d5015b6..ab25afa7ec 100644--- a/enterprise/tests/unit/integrations/jira/test_jira_manager.py+++ b/enterprise/tests/unit/integrations/jira/test_jira_manager.py@@ -202,14 +202,10 @@ class TestStartJob:)jira_manager._send_comment = AsyncMock()- with patch(- 'integrations.jira.jira_manager.register_callback_processor'- ) as mock_register:- await jira_manager.start_job(new_conversation_view)+ await jira_manager.start_job(new_conversation_view)- new_conversation_view.create_or_update_conversation.assert_called_once()- mock_register.assert_called_once()- jira_manager._send_comment.assert_called_once()+ new_conversation_view.create_or_update_conversation.assert_called_once()+ jira_manager._send_comment.assert_called_once()@pytest.mark.asyncioasync def test_start_job_missing_settings_error(diff --git a/enterprise/tests/unit/integrations/jira/test_jira_v1_callback_processor.py b/enterprise/tests/unit/integrations/jira/test_jira_v1_callback_processor.pynew file mode 100644index 0000000000..a1ab6c57d5--- /dev/null+++ b/enterprise/tests/unit/integrations/jira/test_jira_v1_callback_processor.py@@ -0,0 +1,368 @@+"""Tests for JiraV1CallbackProcessor.++This module tests the V1 callback processor that handles Jira integration+callbacks when conversations complete.+"""++from unittest.mock import AsyncMock, MagicMock, patch+from uuid import UUID, uuid4++import httpx+import pytest+from integrations.jira.jira_v1_callback_processor import (+ JIRA_CLOUD_API_URL,+ JiraV1CallbackProcessor,+)++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.sdk.event import ConversationStateUpdateEvent+++def callback_processor():+ """Create a JiraV1CallbackProcessor for testing."""+ return JiraV1CallbackProcessor(+ svc_acc_email='[email protected]',+ decrypted_api_key='test_api_key',+ issue_key='TEST-123',+ jira_cloud_id='cloud-123',+ )+++def mock_event_callback():+ """Create a mock EventCallback."""+ callback = MagicMock(spec=EventCallback)+ callback.id = UUID('12345678-1234-5678-1234-567812345678')+ callback.conversation_id = UUID('87654321-4321-8765-4321-876543218765')+ return callback+++def finished_event():+ """Create a ConversationStateUpdateEvent for finished state."""+ return ConversationStateUpdateEvent(+ id='event-123',+ key='execution_status',+ value='finished',+ )+++def running_event():+ """Create a ConversationStateUpdateEvent for running state."""+ return ConversationStateUpdateEvent(+ id='event-456',+ key='execution_status',+ value='running',+ )+++class TestJiraV1CallbackProcessor:+ """Tests for JiraV1CallbackProcessor."""++ @pytest.mark.asyncio+ async def test_ignores_non_conversation_state_events(+ self, callback_processor, mock_event_callback+ ):+ """Test that non-ConversationStateUpdateEvent events are ignored."""+ # Use a different event type (mock)+ other_event = MagicMock()+ other_event.__class__ = object # Not ConversationStateUpdateEvent++ result = await callback_processor(+ conversation_id=uuid4(),+ callback=mock_event_callback,+ event=other_event,+ )++ assert result is None++ @pytest.mark.asyncio+ async def test_ignores_non_execution_status_keys(+ self, callback_processor, mock_event_callback+ ):+ """Test that events with keys other than 'execution_status' are ignored."""+ event = ConversationStateUpdateEvent(+ id='event-123',+ key='agent_status', # Different key+ value='finished',+ )++ result = await callback_processor(+ conversation_id=uuid4(),+ callback=mock_event_callback,+ event=event,+ )++ assert result is None++ @pytest.mark.asyncio+ async def test_ignores_non_finished_status(+ self, callback_processor, mock_event_callback, running_event+ ):+ """Test that non-finished execution statuses are ignored."""+ result = await callback_processor(+ conversation_id=uuid4(),+ callback=mock_event_callback,+ event=running_event,+ )++ assert result is None++ @pytest.mark.asyncio+ async def test_only_requests_summary_once(+ self, callback_processor, mock_event_callback, finished_event+ ):+ """Test that summary is only requested once (should_request_summary flag)."""+ callback_processor.should_request_summary = False++ result = await callback_processor(+ conversation_id=uuid4(),+ callback=mock_event_callback,+ event=finished_event,+ )++ assert result is None++ @pytest.mark.asyncio+ @patch.object(JiraV1CallbackProcessor, '_request_summary')+ @patch.object(JiraV1CallbackProcessor, '_post_summary_to_jira')+ async def test_successful_summary_flow(+ self,+ mock_post_summary,+ mock_request_summary,+ callback_processor,+ mock_event_callback,+ finished_event,+ ):+ """Test successful summary request and posting flow."""+ conversation_id = uuid4()+ mock_request_summary.return_value = 'Test summary content'+ mock_post_summary.return_value = None++ result = await callback_processor(+ conversation_id=conversation_id,+ callback=mock_event_callback,+ event=finished_event,+ )++ assert result is not None+ assert result.status == EventCallbackResultStatus.SUCCESS+ assert result.detail == 'Test summary content'+ assert callback_processor.should_request_summary is False+ mock_request_summary.assert_called_once_with(conversation_id)+ mock_post_summary.assert_called_once_with('Test summary content')++ @pytest.mark.asyncio+ @patch.object(JiraV1CallbackProcessor, '_request_summary')+ async def test_error_handling_on_summary_request_failure(+ self,+ mock_request_summary,+ callback_processor,+ mock_event_callback,+ finished_event,+ ):+ """Test error handling when summary request fails."""+ conversation_id = uuid4()+ mock_request_summary.side_effect = Exception('Agent server unavailable')++ result = await callback_processor(+ conversation_id=conversation_id,+ callback=mock_event_callback,+ event=finished_event,+ )++ assert result is not None+ assert result.status == EventCallbackResultStatus.ERROR+ assert 'Agent server unavailable' in result.detail++ @pytest.mark.asyncio+ @patch.object(JiraV1CallbackProcessor, '_request_summary')+ @patch.object(JiraV1CallbackProcessor, '_post_summary_to_jira')+ async def test_error_handling_on_post_failure(+ self,+ mock_post_summary,+ mock_request_summary,+ callback_processor,+ mock_event_callback,+ finished_event,+ ):+ """Test error handling when posting to Jira fails."""+ conversation_id = uuid4()+ mock_request_summary.return_value = 'Test summary'+ mock_post_summary.side_effect = Exception('Jira API error')++ result = await callback_processor(+ conversation_id=conversation_id,+ callback=mock_event_callback,+ event=finished_event,+ )++ assert result is not None+ assert result.status == EventCallbackResultStatus.ERROR+ assert 'Jira API error' in result.detail+++class TestPostSummaryToJira:+ """Tests for _post_summary_to_jira method."""++ @pytest.mark.asyncio+ async def test_skips_when_missing_credentials(self, callback_processor):+ """Test that posting is skipped when credentials are missing."""+ callback_processor.svc_acc_email = ''++ # Should not raise, just log and return+ await callback_processor._post_summary_to_jira('Test summary')++ @pytest.mark.asyncio+ async def test_skips_when_missing_issue_key(self, callback_processor):+ """Test that posting is skipped when issue key is missing."""+ callback_processor.issue_key = ''++ # Should not raise, just log and return+ await callback_processor._post_summary_to_jira('Test summary')++ @pytest.mark.asyncio+ async def test_skips_when_missing_cloud_id(self, callback_processor):+ """Test that posting is skipped when cloud ID is missing."""+ callback_processor.jira_cloud_id = ''++ # Should not raise, just log and return+ await callback_processor._post_summary_to_jira('Test summary')++ @pytest.mark.asyncio+ @patch('httpx.AsyncClient')+ async def test_posts_comment_with_correct_format(+ self, mock_async_client, callback_processor+ ):+ """Test that comment is posted with correct format (plain string body)."""+ mock_response = MagicMock()+ mock_response.raise_for_status = MagicMock()++ mock_client_instance = AsyncMock()+ mock_client_instance.post = AsyncMock(return_value=mock_response)+ mock_async_client.return_value.__aenter__.return_value = mock_client_instance++ await callback_processor._post_summary_to_jira('Test summary content')++ # Verify the post was called+ mock_client_instance.post.assert_called_once()+ call_args = mock_client_instance.post.call_args++ # Check URL+ expected_url = (+ f'{JIRA_CLOUD_API_URL}/cloud-123/rest/api/2/issue/TEST-123/comment'+ )+ assert call_args[0][0] == expected_url++ # Check that body contains the summary message+ json_body = call_args[1]['json']+ assert 'body' in json_body+ assert 'OpenHands resolved this issue' in json_body['body']+ assert 'Test summary content' in json_body['body']++ # Check auth+ assert call_args[1]['auth'] == ('[email protected]', 'test_api_key')++ @pytest.mark.asyncio+ @patch('httpx.AsyncClient')+ async def test_raises_on_http_error(self, mock_async_client, callback_processor):+ """Test that HTTP errors are propagated."""+ mock_response = MagicMock()+ mock_response.raise_for_status.side_effect = httpx.HTTPStatusError(+ 'Bad Request',+ request=MagicMock(),+ response=MagicMock(status_code=400),+ )++ mock_client_instance = AsyncMock()+ mock_client_instance.post = AsyncMock(return_value=mock_response)+ mock_async_client.return_value.__aenter__.return_value = mock_client_instance++ with pytest.raises(httpx.HTTPStatusError):+ await callback_processor._post_summary_to_jira('Test summary')+++class TestAskQuestion:+ """Tests for _ask_question method."""++ @pytest.mark.asyncio+ async def test_sends_request_with_correct_payload(self, callback_processor):+ """Test that ask_question sends correct request to agent server."""+ mock_httpx_client = AsyncMock()+ mock_response = MagicMock()+ mock_response.json.return_value = {'response': 'Agent response text'}+ mock_response.raise_for_status = MagicMock()+ mock_httpx_client.post = AsyncMock(return_value=mock_response)++ conversation_id = uuid4()+ agent_server_url = 'http://localhost:8000'+ session_api_key = 'test_session_key'+ message_content = 'Please summarize your work'++ result = await callback_processor._ask_question(+ httpx_client=mock_httpx_client,+ agent_server_url=agent_server_url,+ conversation_id=conversation_id,+ session_api_key=session_api_key,+ message_content=message_content,+ )++ assert result == 'Agent response text'++ # Verify request+ mock_httpx_client.post.assert_called_once()+ call_args = mock_httpx_client.post.call_args++ expected_url = (+ f'{agent_server_url}/api/conversations/{conversation_id}/ask_agent'+ )+ assert call_args[0][0] == expected_url+ assert call_args[1]['headers'] == {'X-Session-API-Key': session_api_key}+ assert call_args[1]['json'] == {'question': message_content}+ assert call_args[1]['timeout'] == 30.0++ @pytest.mark.asyncio+ async def test_handles_http_error(self, callback_processor):+ """Test that HTTP errors are handled and wrapped."""+ mock_httpx_client = AsyncMock()+ mock_response = MagicMock()+ mock_response.status_code = 500+ mock_response.text = 'Internal Server Error'+ mock_response.headers = {}+ mock_error = httpx.HTTPStatusError(+ 'Server Error',+ request=MagicMock(),+ response=mock_response,+ )+ mock_httpx_client.post = AsyncMock(side_effect=mock_error)++ with pytest.raises(Exception, match='Failed to send message to agent server'):+ await callback_processor._ask_question(+ httpx_client=mock_httpx_client,+ agent_server_url='http://localhost:8000',+ conversation_id=uuid4(),+ session_api_key='test_key',+ message_content='test message',+ )++ @pytest.mark.asyncio+ async def test_handles_timeout(self, callback_processor):+ """Test that timeout errors are handled and wrapped."""+ mock_httpx_client = AsyncMock()+ mock_httpx_client.post = AsyncMock(+ side_effect=httpx.TimeoutException('Timeout')+ )++ with pytest.raises(Exception, match='Failed to send message to agent server'):+ await callback_processor._ask_question(+ httpx_client=mock_httpx_client,+ agent_server_url='http://localhost:8000',+ conversation_id=uuid4(),+ session_api_key='test_key',+ message_content='test message',+ )diff --git a/enterprise/tests/unit/integrations/jira/test_jira_view.py b/enterprise/tests/unit/integrations/jira/test_jira_view.pyindex 2dc323ae04..eced07503f 100644--- a/enterprise/tests/unit/integrations/jira/test_jira_view.py+++ b/enterprise/tests/unit/integrations/jira/test_jira_view.py@@ -3,7 +3,6 @@ Tests for Jira view classes and factory."""from unittest.mock import AsyncMock, MagicMock, patch-from uuid import UUIDimport pytestfrom integrations.jira.jira_payload import (@@ -19,9 +18,6 @@ from integrations.jira.jira_view import (JiraNewConversationView,)-from openhands.integrations.service_types import ProviderType-from openhands.server.user_auth.user_auth import UserAuth-class TestJiraNewConversationView:"""Tests for JiraNewConversationView"""@@ -89,51 +85,6 @@ class TestJiraNewConversationView:assert 'TEST-123' in user_msgassert 'Test Issue' in user_msg- @pytest.mark.asyncio- @patch('integrations.jira.jira_view.resolve_org_for_repo', new_callable=AsyncMock)- @patch('integrations.jira.jira_view.ProviderHandler')- @patch(- 'integrations.jira.jira_view.SaasConversationStore.get_resolver_instance',- new_callable=AsyncMock,- )- @patch('integrations.jira.jira_view.start_conversation', new_callable=AsyncMock)- @patch('integrations.jira.jira_view.integration_store')- async def test_create_or_update_conversation_success(- self,- mock_integration_store,- mock_start_convo,- mock_get_resolver_instance,- mock_provider_handler_cls,- mock_resolve_org,- new_conversation_view,- mock_jinja_env,- ):- """Test successful conversation creation"""- new_conversation_view._issue_title = 'Test Issue'- new_conversation_view._issue_description = 'Test description'-- 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()-- result = await new_conversation_view.create_or_update_conversation(- mock_jinja_env- )-- assert result is not None- assert isinstance(result, str)- assert len(result) == 32 # uuid4().hex format- mock_start_convo.assert_called_once()- mock_integration_store.create_conversation.assert_called_once()-@pytest.mark.asyncioasync def test_create_or_update_conversation_no_repo(self, new_conversation_view, mock_jinja_env@@ -372,125 +323,6 @@ class TestJiraFactory:)-CLAIMING_ORG_ID = UUID('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa')---class TestJiraV0ConversationRouting:- """Test V0 conversation routing logic based on claimed git organizations."""-- @pytest.fixture- def routing_view(- self,- sample_webhook_payload,- sample_jira_user,- sample_jira_workspace,- ):- """View with non-empty provider tokens for routing tests."""- user_auth = MagicMock(spec=UserAuth)- user_auth.get_provider_tokens = AsyncMock(- return_value={ProviderType.GITHUB: MagicMock()}- )- user_auth.get_secrets = AsyncMock(return_value=None)- return JiraNewConversationView(- payload=sample_webhook_payload,- saas_user_auth=user_auth,- jira_user=sample_jira_user,- jira_workspace=sample_jira_workspace,- selected_repo='test/repo1',- _issue_title='Test Issue',- _issue_description='Test description',- _decrypted_api_key='decrypted_key',- )-- @pytest.mark.asyncio- @patch('integrations.jira.jira_view.resolve_org_for_repo', new_callable=AsyncMock)- @patch('integrations.jira.jira_view.ProviderHandler')- @patch(- 'integrations.jira.jira_view.SaasConversationStore.get_resolver_instance',- new_callable=AsyncMock,- )- @patch('integrations.jira.jira_view.start_conversation', new_callable=AsyncMock)- @patch('integrations.jira.jira_view.integration_store')- async def test_routes_to_claimed_org_when_user_is_member(- self,- mock_integration_store,- mock_start_convo,- mock_get_resolver_instance,- mock_provider_handler_cls,- mock_resolve_org,- routing_view,- mock_jinja_env,- ):- """When repo belongs to a claimed org and user is a member, conversation is created in that org."""- # 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()-- # Act- await routing_view.create_or_update_conversation(mock_jinja_env)-- # Assert- mock_resolve_org.assert_called_once_with(- provider='github',- full_repo_name='test/repo1',- keycloak_user_id='test_keycloak_id',- )- call_args = mock_get_resolver_instance.call_args- assert call_args[0][1] == 'test_keycloak_id' # user_id- assert call_args[0][2] == CLAIMING_ORG_ID # resolver_org_id- saved_metadata = mock_store.save_metadata.call_args[0][0]- assert saved_metadata.git_provider == ProviderType.GITHUB-- @pytest.mark.asyncio- @patch('integrations.jira.jira_view.resolve_org_for_repo', new_callable=AsyncMock)- @patch('integrations.jira.jira_view.ProviderHandler')- @patch(- 'integrations.jira.jira_view.SaasConversationStore.get_resolver_instance',- new_callable=AsyncMock,- )- @patch('integrations.jira.jira_view.start_conversation', new_callable=AsyncMock)- @patch('integrations.jira.jira_view.integration_store')- async def test_falls_back_to_personal_workspace_when_no_claim(- self,- mock_integration_store,- mock_start_convo,- mock_get_resolver_instance,- mock_provider_handler_cls,- mock_resolve_org,- routing_view,- mock_jinja_env,- ):- """When no org has claimed the git org, conversation goes 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.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()-- # Act- await routing_view.create_or_update_conversation(mock_jinja_env)-- # Assert- call_args = mock_get_resolver_instance.call_args- assert call_args[0][2] is None # resolver_org_id is None--class TestJiraPayloadParser:"""Tests for JiraPayloadParser"""@@ -606,3 +438,164 @@ class TestJiraPayloadParserStagingLabels:result = staging_parser.parse(payload)assert isinstance(result, JiraPayloadSkipped)+++class TestJiraV1Conversation:+ """Tests for V1 conversation creation and callback processor registration."""++ @pytest.mark.asyncio+ async def test_create_v1_metadata_generates_conversation_id(+ self, new_conversation_view+ ):+ """Test that _create_v1_metadata generates a new conversation ID."""+ new_conversation_view.conversation_id = ''++ with patch.object(+ new_conversation_view, '_get_resolved_org_id', new_callable=AsyncMock+ ) as mock_get_org:+ mock_get_org.return_value = None++ metadata = await new_conversation_view._create_v1_metadata()++ # Conversation ID should be generated+ assert new_conversation_view.conversation_id != ''+ assert len(new_conversation_view.conversation_id) == 32 # UUID hex format+ assert metadata.conversation_id == new_conversation_view.conversation_id+ mock_get_org.assert_called_once()++ @pytest.mark.asyncio+ async def test_create_v1_metadata_sets_resolved_org(self, new_conversation_view):+ """Test that _create_v1_metadata sets resolved_org_id."""+ from uuid import UUID++ test_org_id = UUID('12345678-1234-5678-1234-567812345678')++ with patch.object(+ new_conversation_view, '_get_resolved_org_id', new_callable=AsyncMock+ ) as mock_get_org:+ mock_get_org.return_value = test_org_id++ await new_conversation_view._create_v1_metadata()++ assert new_conversation_view.resolved_org_id == test_org_id++ def test_create_jira_v1_callback_processor(+ self, new_conversation_view, sample_jira_workspace+ ):+ """Test that _create_jira_v1_callback_processor creates correctly configured processor."""+ from integrations.jira.jira_v1_callback_processor import JiraV1CallbackProcessor++ processor = new_conversation_view._create_jira_v1_callback_processor()++ assert isinstance(processor, JiraV1CallbackProcessor)+ assert processor.svc_acc_email == sample_jira_workspace.svc_acc_email+ assert processor.decrypted_api_key == 'decrypted_key'+ assert processor.issue_key == 'TEST-123'+ assert processor.jira_cloud_id == sample_jira_workspace.jira_cloud_id++ @pytest.mark.asyncio+ async def test_get_v1_initial_user_message(+ self, new_conversation_view, mock_jinja_env+ ):+ """Test _get_v1_initial_user_message renders the template correctly."""+ new_conversation_view._issue_title = 'Test Bug'+ new_conversation_view._issue_description = 'Description of the bug'++ message = await new_conversation_view._get_v1_initial_user_message(+ mock_jinja_env+ )++ assert 'TEST-123' in message+ assert 'Test Bug' in message++ @pytest.mark.asyncio+ @patch('integrations.jira.jira_view.get_app_conversation_service')+ @patch('integrations.jira.jira_view.integration_store')+ async def test_create_or_update_conversation_v1_flow(+ self,+ mock_store,+ mock_get_service,+ new_conversation_view,+ mock_jinja_env,+ ):+ """Test create_or_update_conversation creates V1 conversation correctly."""+ from unittest.mock import AsyncMock, MagicMock+ from uuid import UUID++ from openhands.app_server.app_conversation.app_conversation_models import (+ AppConversationStartTaskStatus,+ )++ # Setup mocks+ mock_store.create_conversation = AsyncMock()++ # Mock the app conversation service+ mock_service = AsyncMock()++ async def mock_start_generator(*args, **kwargs):+ yield MagicMock(status=AppConversationStartTaskStatus.WORKING)+ yield MagicMock(status=AppConversationStartTaskStatus.READY)++ mock_service.start_app_conversation = mock_start_generator+ mock_get_service.return_value.__aenter__.return_value = mock_service++ # Set issue details to avoid fetch+ new_conversation_view._issue_title = 'Test Issue'+ new_conversation_view._issue_description = 'Test description'++ with patch.object(+ new_conversation_view, '_get_resolved_org_id', new_callable=AsyncMock+ ) as mock_get_org:+ mock_get_org.return_value = UUID('12345678-1234-5678-1234-567812345678')++ result = await new_conversation_view.create_or_update_conversation(+ mock_jinja_env+ )++ # Verify conversation was created+ assert result is not None+ mock_store.create_conversation.assert_called_once()++ @pytest.mark.asyncio+ @patch('integrations.jira.jira_view.get_app_conversation_service')+ @patch('integrations.jira.jira_view.integration_store')+ async def test_create_or_update_conversation_handles_error(+ self,+ mock_store,+ mock_get_service,+ new_conversation_view,+ mock_jinja_env,+ ):+ """Test create_or_update_conversation handles V1 errors correctly."""+ from unittest.mock import AsyncMock, MagicMock++ from openhands.app_server.app_conversation.app_conversation_models import (+ AppConversationStartTaskStatus,+ )++ mock_store.create_conversation = AsyncMock()++ # Mock the app conversation service to return error+ mock_service = AsyncMock()++ async def mock_error_generator(*args, **kwargs):+ yield MagicMock(+ status=AppConversationStartTaskStatus.ERROR,+ detail='Sandbox allocation failed',+ )++ mock_service.start_app_conversation = mock_error_generator+ mock_get_service.return_value.__aenter__.return_value = mock_service++ new_conversation_view._issue_title = 'Test Issue'+ new_conversation_view._issue_description = 'Test description'++ with patch.object(+ new_conversation_view, '_get_resolved_org_id', new_callable=AsyncMock+ ) as mock_get_org:+ mock_get_org.return_value = None++ with pytest.raises(RuntimeError, match='Failed to start V1 conversation'):+ await new_conversation_view.create_or_update_conversation(+ mock_jinja_env+ )