Skip to content

🙌 OpenHands: AI-Driven Development

feat(azure-devops): add resolver mentions + org-level one-click webhook setup (#14991)

Alona89c0103c0537
diff --git a/.agents/skills/custom-codereview-guide.md b/.agents/skills/custom-codereview-guide.md
index 9f94e351c8..3b0d0c1a6e 100644
--- a/.agents/skills/custom-codereview-guide.md
+++ b/.agents/skills/custom-codereview-guide.md
@@ -62,3 +62,13 @@ UI components → TanStack Query hooks (frontend/src/hooks/query/ or mutation/)
```
Flag any component that imports directly from `#/api/` and calls fetch/mutation functions without a TanStack Query wrapper.
+
+## Review Verdict: Submit the Review State That Matches Your Verdict
+
+GitHub does not clear a prior `CHANGES_REQUESTED` from a reviewer when that reviewer later leaves a `COMMENT` — only an `APPROVE` supersedes it. So always submit the review with the state that matches your actual verdict, or PRs get stuck blocked by a stale decision:
+
+- **APPROVE** when the PR meets the merge bar — no critical or blocking issues remain (only optional/non-blocking suggestions). If you previously requested changes and those blocking issues are now resolved, submit an **APPROVE** (you may still list remaining non-blocking suggestions in the body) so your earlier `CHANGES_REQUESTED` is cleared.
+- **REQUEST_CHANGES** only when there are genuine blocking issues that must be fixed before merge.
+- **COMMENT** only for a purely informational pass where you are neither approving nor blocking.
+
+Do not leave a PR in `CHANGES_REQUESTED` once its blocking issues are resolved and your verdict is effectively "worth merging" — approve it.
diff --git a/enterprise/integrations/azure_devops/azure_devops_manager.py b/enterprise/integrations/azure_devops/azure_devops_manager.py
new file mode 100644
index 0000000000..bd5d32a4c0
--- /dev/null
+++ b/enterprise/integrations/azure_devops/azure_devops_manager.py
@@ -0,0 +1,238 @@
+from __future__ import annotations
+
+from types import MappingProxyType
+from typing import cast
+
+from integrations.azure_devops.azure_devops_service import SaaSAzureDevOpsService
+from integrations.azure_devops.azure_devops_view import (
+ AzureDevOpsFactory,
+ AzureDevOpsPRComment,
+ AzureDevOpsViewType,
+ actor_email,
+ mark_openhands_comment,
+)
+from integrations.manager import Manager
+from integrations.models import Message, SourceType
+from integrations.types import ResolverViewInterface
+from integrations.utils import (
+ CONVERSATION_URL,
+ HOST_URL,
+ OPENHANDS_RESOLVER_TEMPLATES_DIR,
+ get_session_expired_message,
+)
+from integrations.v1_utils import get_saas_user_auth
+from jinja2 import Environment, FileSystemLoader
+from pydantic import SecretStr
+from server.auth.token_manager import TokenManager
+
+from openhands.app_server.integrations.azure_devops.azure_devops_service import (
+ AzureDevOpsServiceImpl,
+)
+from openhands.app_server.integrations.provider import ProviderToken, ProviderType
+from openhands.app_server.secrets.secrets_models import Secrets
+from openhands.app_server.types import (
+ LLMAuthenticationError,
+ MissingSettingsError,
+ SessionExpiredError,
+)
+from openhands.app_server.utils.logger import openhands_logger as logger
+
+
+class AzureDevOpsManager(Manager[AzureDevOpsViewType]):
+ def __init__(self, token_manager: TokenManager, data_collector: None = None):
+ self.token_manager = token_manager
+ self.jinja_env = Environment(
+ loader=FileSystemLoader(OPENHANDS_RESOLVER_TEMPLATES_DIR + 'azure_devops')
+ )
+
+ def _confirm_incoming_source_type(self, message: Message) -> None:
+ if message.source != SourceType.AZURE_DEVOPS:
+ raise ValueError(f'Unexpected message source {message.source}')
+
+ async def _resolve_mentioner_keycloak_id(self, message: Message) -> str | None:
+ actor = AzureDevOpsFactory.extract_actor(message)
+ actor_id = str(actor.get('id') or '')
+ if actor_id:
+ try:
+ keycloak_id = await self.token_manager.get_user_id_from_idp_user_id(
+ actor_id, ProviderType.AZURE_DEVOPS
+ )
+ if keycloak_id:
+ return keycloak_id
+ except Exception as e:
+ logger.info(
+ f'[Azure DevOps] Keycloak id lookup failed for actor {actor_id}: {e}'
+ )
+
+ email = actor_email(actor)
+ if email:
+ try:
+ return await self.token_manager.get_user_id_from_user_email(email)
+ except Exception as e:
+ logger.info(
+ f'[Azure DevOps] Keycloak email lookup failed for actor '
+ f'{email}: {e}'
+ )
+
+ return None
+
+ def is_job_requested(self, message: Message) -> bool:
+ self._confirm_incoming_source_type(message)
+ return AzureDevOpsFactory.is_pr_comment(
+ message
+ ) or AzureDevOpsFactory.is_work_item_comment(message)
+
+ async def receive_message(self, message: Message) -> None:
+ self._confirm_incoming_source_type(message)
+ if not self.is_job_requested(message):
+ return
+
+ keycloak_user_id = await self._resolve_mentioner_keycloak_id(message)
+ actor = AzureDevOpsFactory.extract_actor(message)
+ if not keycloak_user_id:
+ logger.info(
+ f'[Azure DevOps] Mentioner {actor.get("displayName") or actor.get("uniqueName") or "unknown"} '
+ 'has no OpenHands account; ignoring event.'
+ )
+ return
+
+ azure_view = await AzureDevOpsFactory.create_azure_devops_view_from_payload(
+ message,
+ keycloak_user_id=keycloak_user_id,
+ )
+ if azure_view is None:
+ logger.info('[Azure DevOps] No repository resolved for event; ignoring.')
+ return
+
+ # Gate on write access, mirroring the GitHub/GitLab/Bitbucket resolvers.
+ # The lazy proxy is typed as the base; the enterprise impl adds the method.
+ azure_service = cast(
+ SaaSAzureDevOpsService,
+ AzureDevOpsServiceImpl(external_auth_id=keycloak_user_id),
+ )
+ if not await azure_service.has_contribute_access(
+ azure_view.project_id, azure_view.repository_id
+ ):
+ logger.info(
+ f'[Azure DevOps] {actor.get("displayName") or actor.get("uniqueName") or "unknown"} '
+ f'lacks write access to {azure_view.full_repo_name}; ignoring event.'
+ )
+ return
+
+ logger.info(
+ f'[Azure DevOps] Creating job for {azure_view.user_info.username} '
+ f'in {azure_view.full_repo_name}#{azure_view.issue_number}'
+ )
+ await self.start_job(azure_view)
+
+ async def send_message(
+ self, message: str, azure_view: ResolverViewInterface
+ ) -> None:
+ message = mark_openhands_comment(message)
+ azure_service = AzureDevOpsServiceImpl(
+ external_auth_id=azure_view.user_info.keycloak_user_id
+ )
+
+ if isinstance(azure_view, AzureDevOpsPRComment):
+ if azure_view.thread_id:
+ await azure_service.add_pr_comment_to_thread(
+ azure_view.full_repo_name,
+ azure_view.issue_number,
+ azure_view.thread_id,
+ message,
+ )
+ else:
+ await azure_service.add_pr_thread(
+ azure_view.full_repo_name,
+ azure_view.issue_number,
+ message,
+ )
+ else:
+ await azure_service.add_work_item_comment(
+ azure_view.full_repo_name,
+ azure_view.issue_number,
+ message,
+ )
+
+ async def start_job(self, azure_view: AzureDevOpsViewType) -> None:
+ try:
+ try:
+ user_info = azure_view.user_info
+ logger.info(
+ f'[Azure DevOps] Starting job for {user_info.username} '
+ f'in {azure_view.full_repo_name}#{azure_view.issue_number}'
+ )
+
+ offline_token = await self.token_manager.load_offline_token(
+ user_info.keycloak_user_id
+ )
+ if not offline_token:
+ raise MissingSettingsError('Missing settings')
+
+ user_token = await self.token_manager.get_idp_token_from_offline_token(
+ offline_token,
+ ProviderType.AZURE_DEVOPS,
+ )
+ if not user_token:
+ raise MissingSettingsError('Missing settings')
+
+ secret_store = Secrets(
+ provider_tokens=MappingProxyType(
+ {
+ ProviderType.AZURE_DEVOPS: ProviderToken(
+ token=SecretStr(user_token),
+ user_id=str(user_info.user_id),
+ )
+ }
+ )
+ )
+
+ conversation_id = await azure_view.initialize_new_conversation()
+ saas_user_auth = await get_saas_user_auth(
+ user_info.keycloak_user_id,
+ self.token_manager,
+ )
+ await azure_view.create_new_conversation(
+ self.jinja_env,
+ secret_store.provider_tokens,
+ conversation_id,
+ saas_user_auth,
+ )
+ conversation_link = CONVERSATION_URL.format(azure_view.conversation_id)
+ msg_info = (
+ f"I'm on it! {user_info.username} can [track my progress at "
+ f'all-hands.dev]({conversation_link})'
+ )
+ except MissingSettingsError as e:
+ logger.warning(
+ f'[Azure DevOps] Missing settings for '
+ f'{azure_view.user_info.username}: {e}'
+ )
+ msg_info = (
+ f'@{azure_view.user_info.username} please re-login into '
+ f'[OpenHands Cloud]({HOST_URL}) before starting a job.'
+ )
+ except LLMAuthenticationError as e:
+ logger.warning(
+ f'[Azure DevOps] LLM authentication error for '
+ f'{azure_view.user_info.username}: {e}'
+ )
+ msg_info = (
+ f'@{azure_view.user_info.username} please set a valid LLM API key '
+ f'in [OpenHands Cloud]({HOST_URL}) before starting a job.'
+ )
+ except SessionExpiredError as e:
+ logger.warning(
+ f'[Azure DevOps] Session expired for '
+ f'{azure_view.user_info.username}: {e}'
+ )
+ msg_info = get_session_expired_message(azure_view.user_info.username)
+
+ await self.send_message(msg_info, azure_view)
+
+ except Exception as e:
+ logger.exception(f'[Azure DevOps] Error starting job: {e}')
+ await self.send_message(
+ 'Uh oh! There was an unexpected error starting the job :(',
+ azure_view,
+ )
diff --git a/enterprise/integrations/azure_devops/azure_devops_service.py b/enterprise/integrations/azure_devops/azure_devops_service.py
index 5111fda90e..8d8f95643c 100644
--- a/enterprise/integrations/azure_devops/azure_devops_service.py
+++ b/enterprise/integrations/azure_devops/azure_devops_service.py
@@ -5,9 +5,13 @@ from server.auth.token_manager import TokenManager
from openhands.app_server.integrations.azure_devops.azure_devops_service import (
AzureDevOpsService,
)
-from openhands.app_server.integrations.service_types import ProviderType
+from openhands.app_server.integrations.service_types import ProviderType, RequestMethod
from openhands.app_server.utils.logger import openhands_logger as logger
+# Git Repositories security namespace + GenericContribute (write) permission bit.
+GIT_REPOSITORIES_NAMESPACE_ID = '2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87'
+GENERIC_CONTRIBUTE_PERMISSION = 4
+
class SaaSAzureDevOpsService(AzureDevOpsService):
def __init__(
@@ -122,3 +126,41 @@ class SaaSAzureDevOpsService(AzureDevOpsService):
installation_id=installation_id,
query=query,
)
+
+ async def has_contribute_access(self, project_id: str, repository_id: str) -> bool:
+ """Whether the caller has GenericContribute (write) on the repo.
+
+ Fails closed: missing ids or any error returns False.
+ """
+ if not project_id or not repository_id:
+ return False
+
+ url = (
+ f'{self.base_url}/_apis/security/permissionevaluationbatch'
+ '?api-version=7.1-preview.1'
+ )
+ payload = {
+ 'evaluations': [
+ {
+ 'securityNamespaceId': GIT_REPOSITORIES_NAMESPACE_ID,
+ 'token': f'repoV2/{project_id}/{repository_id}',
+ 'permissions': GENERIC_CONTRIBUTE_PERMISSION,
+ }
+ ]
+ }
+ try:
+ response, _ = await self._make_request(
+ url=url, params=payload, method=RequestMethod.POST
+ )
+ evaluations = response.get('evaluations') or []
+ return bool(evaluations and evaluations[0].get('value'))
+ except Exception as e:
+ logger.warning(f'[Azure DevOps] permission check failed: {e}')
+ return False
+
+ async def get_project_repositories(self, project: str) -> list[dict]:
+ """List a project's Git repositories as raw API dicts."""
+ project_enc = self._encode_url_component(project)
+ url = f'{self.base_url}/{project_enc}/_apis/git/repositories?api-version=7.1'
+ response, _ = await self._make_request(url)
+ return response.get('value') or []
diff --git a/enterprise/integrations/azure_devops/azure_devops_v1_callback_processor.py b/enterprise/integrations/azure_devops/azure_devops_v1_callback_processor.py
new file mode 100644
index 0000000000..a872ce6e35
--- /dev/null
+++ b/enterprise/integrations/azure_devops/azure_devops_v1_callback_processor.py
@@ -0,0 +1,190 @@
+import logging
+from typing import Any, ClassVar
+from uuid import UUID
+
+import httpx
+from integrations.azure_devops.azure_devops_view import mark_openhands_comment
+from integrations.utils import get_summary_instruction
+from integrations.v1_utils import handle_callback_error
+from pydantic import Field
+
+from openhands.agent_server.models import AskAgentRequest, AskAgentResponse
+from openhands.app_server.event_callback.event_callback_models import (
+ EventCallback,
+ EventCallbackProcessor,
+ EventKind,
+)
+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 AzureDevOpsV1CallbackProcessor(EventCallbackProcessor):
+ event_kind: ClassVar[EventKind] = 'ConversationStateUpdateEvent'
+
+ azure_devops_view_data: dict[str, Any] = Field(default_factory=dict)
+ should_request_summary: bool = Field(default=True)
+
+ async def __call__(
+ self,
+ conversation_id: UUID,
+ callback: EventCallback,
+ event: Event,
+ ) -> EventCallbackResult | None:
+ if not isinstance(event, ConversationStateUpdateEvent):
+ return None
+ if event.key != 'execution_status':
+ return None
+
+ _logger.info('[Azure DevOps V1] Callback agent state was %s', event)
+
+ if event.value != 'finished':
+ return None
+ if not self.should_request_summary:
+ return None
+
+ self.should_request_summary = False
+ try:
+ summary = await self._request_summary(conversation_id)
+ await self._post_summary_to_azure_devops(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:
+ can_post_error = bool(self.azure_devops_view_data.get('keycloak_user_id'))
+ await handle_callback_error(
+ error=e,
+ conversation_id=conversation_id,
+ service_name='Azure DevOps',
+ service_logger=_logger,
+ can_post_error=can_post_error,
+ post_error_func=self._post_summary_to_azure_devops,
+ )
+ return EventCallbackResult(
+ status=EventCallbackResultStatus.ERROR,
+ event_callback_id=callback.id,
+ event_id=event.id,
+ conversation_id=conversation_id,
+ detail=str(e),
+ )
+
+ async def _post_summary_to_azure_devops(self, summary: str) -> None:
+ from openhands.app_server.integrations.azure_devops.azure_devops_service import (
+ AzureDevOpsServiceImpl,
+ )
+
+ keycloak_user_id = self.azure_devops_view_data.get('keycloak_user_id')
+ if not keycloak_user_id:
+ raise RuntimeError('Missing keycloak user ID for Azure DevOps')
+
+ azure_service = AzureDevOpsServiceImpl(external_auth_id=keycloak_user_id)
+ summary = mark_openhands_comment(summary)
+ repository = self.azure_devops_view_data['repository']
+ issue_number = int(self.azure_devops_view_data['issue_number'])
+ if self.azure_devops_view_data.get('is_pr'):
+ thread_id = self.azure_devops_view_data.get('thread_id')
+ if thread_id:
+ await azure_service.add_pr_comment_to_thread(
+ repository,
+ issue_number,
+ int(thread_id),
+ summary,
+ )
+ else:
+ await azure_service.add_pr_thread(repository, issue_number, summary)
+ else:
+ await azure_service.add_work_item_comment(
+ repository,
+ issue_number,
+ summary,
+ )
+
+ 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_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()
+ return AskAgentResponse.model_validate(response.json()).response
+ except httpx.HTTPStatusError as e:
+ error_detail = f'HTTP {e.response.status_code} error'
+ try:
+ if e.response.text:
+ error_detail += f': {e.response.text}'
+ except Exception:
+ pass
+ _logger.error(
+ '[Azure DevOps V1] HTTP error: %s', error_detail, exc_info=True
+ )
+ raise Exception(f'Failed to send message to agent server: {error_detail}')
+ except httpx.TimeoutException:
+ raise Exception(f'Request timeout after 30 seconds to {url}')
+ except httpx.RequestError as e:
+ raise Exception(f'Request error to {url}: {e}')
+
+ async def _request_summary(self, conversation_id: UUID) -> str:
+ 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,
+ )
+
+ state = InjectorState()
+ setattr(state, USER_CONTEXT_ATTR, ADMIN)
+
+ async with (
+ get_app_conversation_info_service(state) as info_service,
+ get_sandbox_service(state) as sandbox_service,
+ get_httpx_client(state) as httpx_client,
+ ):
+ app_info = ensure_conversation_found(
+ await info_service.get_app_conversation_info(conversation_id),
+ conversation_id,
+ )
+ sandbox = ensure_running_sandbox(
+ await sandbox_service.get_sandbox(app_info.sandbox_id),
+ app_info.sandbox_id,
+ )
+ assert sandbox.session_api_key is not None
+ agent_server_url = get_agent_server_url_from_sandbox(sandbox)
+ 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=get_summary_instruction(),
+ )
diff --git a/enterprise/integrations/azure_devops/azure_devops_view.py b/enterprise/integrations/azure_devops/azure_devops_view.py
new file mode 100644
index 0000000000..1e6ad076d1
--- /dev/null
+++ b/enterprise/integrations/azure_devops/azure_devops_view.py
@@ -0,0 +1,516 @@
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from typing import Any, cast
+from urllib.parse import urlparse
+from uuid import UUID, uuid4
+
+from integrations.azure_devops.azure_devops_service import SaaSAzureDevOpsService
+from integrations.models import Message
+from integrations.resolver_context import ResolverUserContext
+from integrations.resolver_org_router import resolve_org_for_repo
+from integrations.types import ResolverViewInterface, UserData
+from integrations.utils import HOST, get_oh_labels, has_exact_mention
+from jinja2 import Environment
+
+from openhands.agent_server.models import SendMessageRequest
+from openhands.app_server.app_conversation.app_conversation_models import (
+ AppConversationStartRequest,
+ AppConversationStartTaskStatus,
+ ConversationTrigger,
+)
+from openhands.app_server.config import get_app_conversation_service
+from openhands.app_server.integrations.azure_devops.azure_devops_service import (
+ AzureDevOpsServiceImpl,
+)
+from openhands.app_server.integrations.azure_devops.service.webhooks import (
+ AZURE_DEVOPS_PR_COMMENT_EVENT as PR_COMMENT_EVENT,
+)
+from openhands.app_server.integrations.azure_devops.service.webhooks import (
+ AZURE_DEVOPS_WORK_ITEM_COMMENT_EVENT as WORK_ITEM_COMMENT_EVENT,
+)
+from openhands.app_server.integrations.provider import PROVIDER_TOKEN_TYPE, ProviderType
+from openhands.app_server.integrations.service_types import Comment
+from openhands.app_server.services.injector import InjectorState
+from openhands.app_server.user.specifiy_user_context import USER_CONTEXT_ATTR
+from openhands.app_server.user_auth.user_auth import UserAuth
+from openhands.app_server.utils.logger import openhands_logger as logger
+from openhands.sdk import TextContent
+
+OH_LABEL, INLINE_OH_LABEL = get_oh_labels(HOST)
+OPENHANDS_COMMENT_MARKER = '<!-- openhands-azure-devops-resolver -->'
+
+
+def mark_openhands_comment(comment: str) -> str:
+ if OPENHANDS_COMMENT_MARKER in comment:
+ return comment
+ return f'{OPENHANDS_COMMENT_MARKER}\n{comment}'
+
+
+def _is_openhands_comment(comment: str) -> bool:
+ return OPENHANDS_COMMENT_MARKER in comment
+
+
+def _strip_ref_prefix(ref_name: str | None) -> str | None:
+ if not ref_name:
+ return None
+ return ref_name.removeprefix('refs/heads/')
+
+
+def _extract_org_from_url(raw_url: str | None) -> str:
+ if not raw_url:
+ return ''
+
+ parsed = urlparse(raw_url)
+ hostname = parsed.hostname or ''
+ path_parts = [part for part in parsed.path.split('/') if part]
+
+ if hostname.endswith('dev.azure.com') and path_parts:
+ return path_parts[0]
+
+ if hostname.endswith('.visualstudio.com'):
+ return hostname.split('.')[0]
+
+ return ''
+
+
+def _extract_org(payload: dict[str, Any]) -> str:
+ resource_containers = payload.get('resourceContainers') or {}
+ for container_name in ('account', 'collection', 'project'):
+ org = _extract_org_from_url(
+ (resource_containers.get(container_name) or {}).get('baseUrl')
+ )
+ if org:
+ return org
+
+ resource = payload.get('resource') or {}
+ for candidate in (
+ ((resource.get('pullRequest') or {}).get('repository') or {}).get('remoteUrl'),
+ ((resource.get('pullRequest') or {}).get('repository') or {}).get('url'),
+ ((resource.get('comment') or {}).get('_links') or {})
+ .get('self', {})
+ .get('href'),
+ ((resource.get('_links') or {}).get('self') or {}).get('href'),
+ resource.get('url'),
+ ):
+ org = _extract_org_from_url(candidate)
+ if org:
+ return org
+
+ return ''
+
+
+def _extract_work_item_comment(payload: dict[str, Any]) -> str:
+ fields = (payload.get('resource') or {}).get('fields') or {}
+ history = fields.get('System.History') or ''
+ if history:
+ return history
+
+ detailed = (payload.get('detailedMessage') or {}).get('text') or ''
+ # detailedMessage is "<actor> commented\n<body>"; drop the first line.
+ return detailed.split('\n', 1)[-1].strip() if '\n' in detailed else ''
+
+
+def _select_project_repo(
+ repos: list[dict[str, Any]], project_name: str
+) -> dict[str, Any] | None:
+ """Resolve a project's repo deterministically: name match, else the sole
+ repo. Returns None when ambiguous (multiple repos, no name match) so we
+ fail closed rather than guess."""
+ if not repos:
+ return None
+ for repo in repos:
+ if (repo.get('name') or '').lower() == project_name.lower():
+ return repo
+ if len(repos) == 1:
+ return repos[0]
+ return None
+
+
+def _actor_username(actor: dict[str, Any]) -> str:
+ return (
+ actor.get('displayName')
+ or actor.get('uniqueName')
+ or actor.get('id')
+ or 'unknown'
+ )
+
+
+def actor_email(actor: dict[str, Any]) -> str:
+ unique_name = str(actor.get('uniqueName') or '').strip()
+ if '@' in unique_name:
+ return unique_name
+ display_name = str(actor.get('displayName') or '').strip()
+ match = re.search(r'[\w.+-]+@[\w.-]+\.\w+', display_name)
+ return match.group(0) if match else ''
+
+
+@dataclass
+class AzureDevOpsItem(ResolverViewInterface):
+ installation_id: str
+ issue_number: int
+ full_repo_name: str
+ is_public_repo: bool
+ user_info: UserData
+ raw_payload: Message
+ conversation_id: str
+ should_extract: bool
+ send_summary_instruction: bool
+ title: str
+ description: str
+ previous_comments: list[Comment]
+ project_name: str
+ project_id: str
+ repository_id: str
+
+ def _get_branch_name(self) -> str | None:
+ # Only PR comments carry a branch; overridden there.
+ return None
+
+ async def _load_resolver_context(self) -> None:
+ azure_service = AzureDevOpsServiceImpl(
+ external_auth_id=self.user_info.keycloak_user_id
+ )
+ self.previous_comments = await azure_service.get_issue_or_pr_comments(
+ self.full_repo_name,
+ self.issue_number,
+ max_comments=100,
+ )
+ (
+ self.title,
+ self.description,
+ ) = await azure_service.get_issue_or_pr_title_and_body(
+ self.full_repo_name,
+ self.issue_number,
+ )
+
+ async def initialize_new_conversation(self) -> UUID:
+ self.resolved_org_id = await resolve_org_for_repo(
+ provider=ProviderType.AZURE_DEVOPS.value,
+ full_repo_name=self.full_repo_name,
+ keycloak_user_id=self.user_info.keycloak_user_id,
+ )
+ conversation_id = uuid4()
+ self.conversation_id = conversation_id.hex
+ return conversation_id
+
+ async def create_new_conversation(
+ self,
+ jinja_env: Environment,
+ git_provider_tokens: PROVIDER_TOKEN_TYPE,
+ conversation_id: UUID,
+ saas_user_auth: UserAuth,
+ ) -> None:
+ user_instructions, conversation_instructions = await self._get_instructions(
+ jinja_env
+ )
+ initial_message = SendMessageRequest(
+ role='user', content=[TextContent(text=user_instructions)]
+ )
+
+ from integrations.azure_devops.azure_devops_v1_callback_processor import (
+ AzureDevOpsV1CallbackProcessor,
+ )
+
+ callback_processor = AzureDevOpsV1CallbackProcessor(
+ azure_devops_view_data={
+ 'repository': self.full_repo_name,
+ 'issue_number': self.issue_number,
+ 'keycloak_user_id': self.user_info.keycloak_user_id,
+ 'is_pr': isinstance(self, AzureDevOpsPRComment),
+ 'thread_id': getattr(self, 'thread_id', None),
+ },
+ should_request_summary=self.send_summary_instruction,
+ )
+
+ title_prefix = (
+ 'Azure DevOps PR'
+ if isinstance(self, AzureDevOpsPRComment)
+ else 'Azure DevOps Work Item'
+ )
+ start_request = AppConversationStartRequest(
+ conversation_id=conversation_id,
+ system_message_suffix=conversation_instructions or None,
+ initial_message=initial_message,
+ selected_repository=self.full_repo_name,
+ selected_branch=self._get_branch_name(),
+ git_provider=ProviderType.AZURE_DEVOPS,
+ title=f'{title_prefix} #{self.issue_number}: {self.title}',
+ trigger=ConversationTrigger.RESOLVER,
+ processors=[callback_processor],
+ )
+
+ injector_state = InjectorState()
+ azure_user_context = ResolverUserContext(
+ saas_user_auth=saas_user_auth,
+ resolver_org_id=self.resolved_org_id,
+ )
+ setattr(injector_state, USER_CONTEXT_ATTR, azure_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'[Azure DevOps] Failed to start V1 conversation: {task.detail}'
+ )
+ raise RuntimeError(
+ f'Failed to start V1 conversation: {task.detail}'
+ )
+
+
+@dataclass
+class AzureDevOpsPRComment(AzureDevOpsItem):
+ comment_id: int | None
+ comment_body: str
+ thread_id: int | None
+ branch_name: str | None
+
+ def _get_branch_name(self) -> str | None:
+ return self.branch_name
+
+ async def _load_resolver_context(self) -> None:
+ # Call PR-specific methods directly so a brand-new PR with no prior
+ # comments (empty list) never falls back to unrelated work-item discussion.
+ azure_service = AzureDevOpsServiceImpl(
+ external_auth_id=self.user_info.keycloak_user_id
+ )
+ self.previous_comments = await azure_service.get_pr_comments(
+ self.full_repo_name,
+ self.issue_number,
+ max_comments=100,
+ )
+ (
+ self.title,
+ self.description,
+ ) = await azure_service.get_issue_or_pr_title_and_body(
+ self.full_repo_name,
+ self.issue_number,
+ )
+
+ async def _get_instructions(self, jinja_env: Environment) -> tuple[str, str]:
+ await self._load_resolver_context()
+
+ user_instructions_template = jinja_env.get_template('pr_update_prompt.j2')
+ user_instructions = user_instructions_template.render(
+ pr_comment=self.comment_body
+ )
+
+ conversation_instructions_template = jinja_env.get_template(
+ 'pr_update_conversation_instructions.j2'
+ )
+ conversation_instructions = conversation_instructions_template.render(
+ pr_number=self.issue_number,
+ branch_name=self.branch_name or '',
+ pr_title=self.title,
+ pr_body=self.description,
+ comments=self.previous_comments,
+ )
+ return user_instructions, conversation_instructions
+
+
+@dataclass
+class AzureDevOpsWorkItemComment(AzureDevOpsItem):
+ comment_body: str
+
+ async def _load_resolver_context(self) -> None:
+ # Load work-item context directly; never probe PRs (a PR can share the id).
+ azure_service = AzureDevOpsServiceImpl(
+ external_auth_id=self.user_info.keycloak_user_id
+ )
+ self.previous_comments = await azure_service.get_work_item_comments(
+ self.full_repo_name,
+ self.issue_number,
+ max_comments=100,
+ )
+ (
+ self.title,
+ self.description,
+ ) = await azure_service.get_work_item_title_and_body(self.issue_number)
+
+ async def _get_instructions(self, jinja_env: Environment) -> tuple[str, str]:
+ await self._load_resolver_context()
+
+ user_instructions_template = jinja_env.get_template('issue_prompt.j2')
+ user_instructions = user_instructions_template.render(
+ issue_comment=self.comment_body,
+ issue_number=self.issue_number,
+ )
+
+ conversation_instructions_template = jinja_env.get_template(
+ 'issue_conversation_instructions.j2'
+ )
+ conversation_instructions = conversation_instructions_template.render(
+ issue_number=self.issue_number,
+ issue_title=self.title,
+ issue_body=self.description,
+ previous_comments=self.previous_comments,
+ )
+ return user_instructions, conversation_instructions
+
+
+AzureDevOpsViewType = AzureDevOpsPRComment | AzureDevOpsWorkItemComment
+
+
+class AzureDevOpsFactory:
+ @staticmethod
+ def event_key(message: Message) -> str:
+ return str(
+ message.message.get('event_key')
+ or (message.message.get('payload') or {}).get('eventType')
+ or ''
+ )
+
+ @staticmethod
+ def extract_actor(message: Message) -> dict[str, Any]:
+ payload = message.message.get('payload') or {}
+ resource = payload.get('resource') or {}
+ if AzureDevOpsFactory.event_key(message) == PR_COMMENT_EVENT:
+ return (resource.get('comment') or {}).get('author') or {}
+ if AzureDevOpsFactory.event_key(message) == WORK_ITEM_COMMENT_EVENT:
+ revised_by = resource.get('revisedBy')
+ if isinstance(revised_by, dict):
+ return revised_by
+ changed_by = (resource.get('fields') or {}).get('System.ChangedBy')
+ if isinstance(changed_by, dict):
+ return changed_by
+ if isinstance(changed_by, str):
+ return {'displayName': changed_by, 'uniqueName': changed_by}
+ return {}
+
+ @staticmethod
+ def is_pr_comment(message: Message) -> bool:
+ if AzureDevOpsFactory.event_key(message) != PR_COMMENT_EVENT:
+ return False
+ payload = message.message.get('payload') or {}
+ comment = ((payload.get('resource') or {}).get('comment') or {}).get(
+ 'content'
+ ) or ''
+ if _is_openhands_comment(comment):
+ return False
+ return has_exact_mention(comment, INLINE_OH_LABEL)
+
+ @staticmethod
+ def is_work_item_comment(message: Message) -> bool:
+ if AzureDevOpsFactory.event_key(message) != WORK_ITEM_COMMENT_EVENT:
+ return False
+ payload = message.message.get('payload') or {}
+ comment = _extract_work_item_comment(payload)
+ if _is_openhands_comment(comment):
+ return False
+ return has_exact_mention(comment, INLINE_OH_LABEL)
+
+ @staticmethod
+ async def create_azure_devops_view_from_payload(
+ message: Message,
+ keycloak_user_id: str,
+ ) -> AzureDevOpsViewType | None:
+ payload = message.message.get('payload') or {}
+ resource = payload.get('resource') or {}
+ actor = AzureDevOpsFactory.extract_actor(message)
+ username = _actor_username(actor)
+ actor_id = str(actor.get('id') or actor.get('uniqueName') or username)
+ org = _extract_org(payload)
+ if not org:
+ # Without an org, full_repo_name would be malformed ('/project/repo').
+ logger.warning(
+ '[Azure DevOps] Could not determine organization from payload; '
+ 'skipping.'
+ )
+ return None
+
+ if AzureDevOpsFactory.is_pr_comment(message):
+ pull_request = resource.get('pullRequest') or {}
+ repository = pull_request.get('repository') or {}
+ project = repository.get('project') or {}
+ project_name = project.get('name') or ''
+ project_id = str(project.get('id') or '')
+ repository_id = str(repository.get('id') or '')
+ repo_name = repository.get('name') or ''
+ pr_number = int(pull_request.get('pullRequestId') or 0)
+ comment = resource.get('comment') or {}
+ thread_href = ((comment.get('_links') or {}).get('threads') or {}).get(
+ 'href'
+ ) or ''
+ thread_match = re.search(r'/threads/(\d+)(?:$|[/?#])', thread_href)
+ full_repo_name = f'{org}/{project_name}/{repo_name}'
+ user_info = UserData(
+ user_id=actor_id,
+ username=username,
+ keycloak_user_id=keycloak_user_id,
+ )
+ return AzureDevOpsPRComment(
+ installation_id=full_repo_name,
+ issue_number=pr_number,
+ full_repo_name=full_repo_name,
+ is_public_repo=False,
+ user_info=user_info,
+ raw_payload=message,
+ conversation_id='',
+ should_extract=True,
+ send_summary_instruction=True,
+ title='',
+ description='',
+ previous_comments=[],
+ project_name=project_name,
+ project_id=project_id,
+ repository_id=repository_id,
+ comment_id=comment.get('id'),
+ comment_body=comment.get('content') or '',
+ thread_id=int(thread_match.group(1)) if thread_match else None,
+ branch_name=_strip_ref_prefix(pull_request.get('sourceRefName')),
+ )
+
+ if AzureDevOpsFactory.is_work_item_comment(message):
+ fields = resource.get('fields') or {}
+ project_name = fields.get('System.TeamProject') or ''
+ work_item_id = int(resource.get('id') or 0)
+
+ # Work items aren't tied to a repo; resolve a real one for the project
+ # instead of fabricating a project-named repo that may not exist.
+ azure_service = cast(
+ SaaSAzureDevOpsService,
+ AzureDevOpsServiceImpl(external_auth_id=keycloak_user_id),
+ )
+ repos = await azure_service.get_project_repositories(project_name)
+ repo = _select_project_repo(repos, project_name)
+ if repo is None:
+ logger.warning(
+ f'[Azure DevOps] Could not unambiguously resolve a repository '
+ f'for work item in project {org}/{project_name}; skipping.'
+ )
+ return None
+ repo_name = repo.get('name') or ''
+ repository_id = str(repo.get('id') or '')
+ project_id = str((repo.get('project') or {}).get('id') or '')
+ full_repo_name = f'{org}/{project_name}/{repo_name}'
+ user_info = UserData(
+ user_id=actor_id,
+ username=username,
+ keycloak_user_id=keycloak_user_id,
+ )
+ return AzureDevOpsWorkItemComment(
+ installation_id=full_repo_name,
+ issue_number=work_item_id,
+ full_repo_name=full_repo_name,
+ is_public_repo=False,
+ user_info=user_info,
+ raw_payload=message,
+ conversation_id='',
+ should_extract=True,
+ send_summary_instruction=True,
+ title='',
+ description='',
+ previous_comments=[],
+ project_name=project_name,
+ project_id=project_id,
+ repository_id=repository_id,
+ comment_body=_extract_work_item_comment(payload),
+ )
+
+ # Unreachable: receive_message only calls this after is_job_requested() is True.
+ raise ValueError(f'Unhandled Azure DevOps webhook event: {message}')
diff --git a/enterprise/saas_server.py b/enterprise/saas_server.py
index b694903b7d..999cbdb94c 100644
--- a/enterprise/saas_server.py
+++ b/enterprise/saas_server.py
@@ -16,6 +16,7 @@ from fastapi import Request, status # noqa: E402
from fastapi.responses import JSONResponse # noqa: E402
from server.auth.auth_error import ExpiredError, NoCredentialsError # noqa: E402
from server.auth.constants import ( # noqa: E402
+ AZURE_DEVOPS_CLIENT_ID,
BITBUCKET_APP_CLIENT_ID,
BITBUCKET_DATA_CENTER_HOST,
ENABLE_JIRA,
@@ -136,6 +137,19 @@ if BITBUCKET_APP_CLIENT_ID:
base_app.include_router(bitbucket_integration_router)
+# Add Azure DevOps integration router only if Azure DevOps OAuth is configured.
+if AZURE_DEVOPS_CLIENT_ID:
+ from integrations.azure_devops.azure_devops_v1_callback_processor import ( # noqa: E402
+ AzureDevOpsV1CallbackProcessor,
+ )
+ from server.routes.integration.azure_devops import ( # noqa: E402
+ azure_devops_integration_router,
+ )
+
+ logger.debug(f'Loaded {AzureDevOpsV1CallbackProcessor.__name__}')
+
+ base_app.include_router(azure_devops_integration_router)
+
base_app.include_router(api_keys_router) # Add routes for API key management
base_app.include_router(service_router) # Add routes for internal service API
base_app.include_router(org_router) # Add routes for organization management
diff --git a/enterprise/server/auth/constants.py b/enterprise/server/auth/constants.py
index e0ed643ccd..02370c2089 100644
--- a/enterprise/server/auth/constants.py
+++ b/enterprise/server/auth/constants.py
@@ -23,6 +23,7 @@ AZURE_DEVOPS_CLIENT_ID = os.getenv('AZURE_DEVOPS_CLIENT_ID', '').strip()
AZURE_DEVOPS_CLIENT_SECRET = os.getenv('AZURE_DEVOPS_CLIENT_SECRET', '').strip()
AZURE_DEVOPS_TENANT_ID = os.getenv('AZURE_DEVOPS_TENANT_ID', '').strip()
AZURE_DEVOPS_ORGANIZATION = os.getenv('AZURE_DEVOPS_ORGANIZATION', '').strip()
+AZURE_DEVOPS_WEBHOOK_SECRET = os.getenv('AZURE_DEVOPS_WEBHOOK_SECRET', '').strip()
AZURE_DEVOPS_SCOPE = os.getenv(
'AZURE_DEVOPS_SCOPE', 'https://app.vssps.visualstudio.com/.default'
).strip()
diff --git a/enterprise/server/routes/integration/azure_devops.py b/enterprise/server/routes/integration/azure_devops.py
new file mode 100644
index 0000000000..28b4509e88
--- /dev/null
+++ b/enterprise/server/routes/integration/azure_devops.py
@@ -0,0 +1,418 @@
+from __future__ import annotations
+
+import base64
+import hashlib
+import json
+import secrets
+from typing import Any
+
+from fastapi import (
+ APIRouter,
+ BackgroundTasks,
+ Depends,
+ Header,
+ HTTPException,
+ Request,
+ status,
+)
+from fastapi.responses import JSONResponse
+from integrations.azure_devops.azure_devops_service import SaaSAzureDevOpsService
+from integrations.models import Message, SourceType
+from integrations.utils import HOST_URL, IS_LOCAL_DEPLOYMENT
+from pydantic import BaseModel
+from server.auth.authorization import Permission, require_permission
+from server.auth.constants import AZURE_DEVOPS_WEBHOOK_SECRET
+from storage.redis import get_redis_client_async
+
+from openhands.app_server.integrations.azure_devops.service.webhooks import (
+ AZURE_DEVOPS_PR_COMMENT_EVENT,
+ AZURE_DEVOPS_WORK_ITEM_COMMENT_EVENT,
+)
+from openhands.app_server.utils.logger import openhands_logger as logger
+
+azure_devops_integration_router = APIRouter(prefix='/integration')
+
+_azure_devops_manager = None
+
+
+def azure_devops_webhook_url() -> str:
+ return f'{HOST_URL}/integration/azure-devops/events'
+
+
+class AzureDevOpsWebhookStatus(BaseModel):
+ organization: str
+ webhook_installed: bool
+ pr_webhook_installed: bool
+ work_item_webhook_installed: bool
+ pr_subscription_id: str | None
+ work_item_subscription_id: str | None
+ webhook_url: str
+ webhook_secret_set: bool
+
+
+class AzureDevOpsWebhookInstallationResult(BaseModel):
+ organization: str
+ success: bool
+ error: str | None
+ pr_subscription_id: str | None
+ work_item_subscription_id: str | None
+ webhook_url: str
+
+
+def get_azure_devops_manager():
+ global _azure_devops_manager
+ if _azure_devops_manager is None:
+ from integrations.azure_devops.azure_devops_manager import AzureDevOpsManager
+ from server.auth.token_manager import TokenManager
+
+ _azure_devops_manager = AzureDevOpsManager(TokenManager())
+ return _azure_devops_manager
+
+
+def _basic_auth_secret(authorization: str | None) -> str | None:
+ if not authorization:
+ return None
+ scheme, _, encoded = authorization.partition(' ')
+ if scheme.lower() != 'basic' or not encoded:
+ return None
+ try:
+ decoded = base64.b64decode(encoded).decode()
+ except Exception:
+ return None
+ _, _, password = decoded.partition(':')
+ return password or decoded
+
+
+def _subscription_id(subscription: dict[str, Any]) -> str | None:
+ subscription_id = subscription.get('id')
+ return str(subscription_id) if subscription_id else None
+
+
+def _subscription_consumer_url(subscription: dict[str, Any]) -> str:
+ return str((subscription.get('consumerInputs') or {}).get('url') or '')
+
+
+def _subscription_event_type(subscription: dict[str, Any]) -> str:
+ return str(subscription.get('eventType') or '')
+
+
+def _subscription_is_project_scoped(subscription: dict[str, Any]) -> bool:
+ # A projectId in publisherInputs means the hook is scoped to one project,
+ # not the org-wide resolver install.
+ return bool((subscription.get('publisherInputs') or {}).get('projectId'))
+
+
+def _subscription_is_enabled(subscription: dict[str, Any] | None) -> bool:
+ # A Service Hook can exist but be disabled/suspended and not deliver events.
+ return subscription is not None and subscription.get('status') == 'enabled'
+
+
+def _matches_pr_comment_subscription(
+ subscription: dict[str, Any],
+ *,
+ webhook_url: str,
+) -> bool:
+ # Org-wide hook = event + consumer url + no projectId (project-scoped hooks
+ # at the same url must not be mistaken for the org-wide install).
+ return (
+ _subscription_event_type(subscription) == AZURE_DEVOPS_PR_COMMENT_EVENT
+ and _subscription_consumer_url(subscription) == webhook_url
+ and not _subscription_is_project_scoped(subscription)
+ )
+
+
+def _matches_work_item_comment_subscription(
+ subscription: dict[str, Any],
+ *,
+ webhook_url: str,
+) -> bool:
+ return (
+ _subscription_event_type(subscription) == AZURE_DEVOPS_WORK_ITEM_COMMENT_EVENT
+ and _subscription_consumer_url(subscription) == webhook_url
+ and not _subscription_is_project_scoped(subscription)
+ )
+
+
+# Webhook secret for local dev only; real installs set AZURE_DEVOPS_WEBHOOK_SECRET.
+_LOCAL_DEPLOYMENT_WEBHOOK_SECRET = 'localdeploymentwebhooktesttoken'
+
+
+def _get_webhook_secret() -> str | None:
+ return (
+ _LOCAL_DEPLOYMENT_WEBHOOK_SECRET
+ if IS_LOCAL_DEPLOYMENT
+ else AZURE_DEVOPS_WEBHOOK_SECRET
+ )
+
+
+def _ensure_azure_devops_webhook_secret() -> str:
+ secret = _get_webhook_secret()
+ if not secret:
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail='Azure DevOps webhook secret is not configured.',
+ )
+ return secret
+
+
+def _ensure_azure_devops_organization(service: SaaSAzureDevOpsService) -> None:
+ if not service.organization:
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail='Azure DevOps organization is not configured.',
+ )
+
+
+async def verify_azure_devops_signature(
+ header_webhook_secret: str | None,
+ authorization: str | None,
+) -> None:
+ expected_secret = _get_webhook_secret()
+ provided_secret = header_webhook_secret or _basic_auth_secret(authorization)
+ if not expected_secret:
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail='Azure DevOps webhook secret is not configured.',
+ )
+ if not provided_secret or not secrets.compare_digest(
+ provided_secret, expected_secret
+ ):
+ raise HTTPException(status_code=403, detail="Request signatures didn't match!")
+
+
+@azure_devops_integration_router.get('/azure-devops/resources')
+async def get_azure_devops_resources(
+ user_id: str = Depends(require_permission(Permission.MANAGE_INTEGRATIONS)),
+) -> AzureDevOpsWebhookStatus:
+ """Report org-wide resolver hook installation status."""
+ try:
+ service = SaaSAzureDevOpsService(external_auth_id=user_id)
+ _ensure_azure_devops_organization(service)
+ webhook_url = azure_devops_webhook_url()
+
+ subscriptions = await service.list_service_hook_subscriptions()
+ pr_subscription = next(
+ (
+ subscription
+ for subscription in subscriptions
+ if _matches_pr_comment_subscription(
+ subscription, webhook_url=webhook_url
+ )
+ ),
+ None,
+ )
+ work_item_subscription = next(
+ (
+ subscription
+ for subscription in subscriptions
+ if _matches_work_item_comment_subscription(
+ subscription, webhook_url=webhook_url
+ )
+ ),
+ None,
+ )
+
+ # Only report installed when the hooks are enabled (a disabled/suspended
+ # hook exists but won't deliver resolver events).
+ pr_enabled = _subscription_is_enabled(pr_subscription)
+ work_item_enabled = _subscription_is_enabled(work_item_subscription)
+
+ return AzureDevOpsWebhookStatus(
+ organization=service.organization,
+ webhook_installed=pr_enabled and work_item_enabled,
+ pr_webhook_installed=pr_enabled,
+ work_item_webhook_installed=work_item_enabled,
+ pr_subscription_id=_subscription_id(pr_subscription)
+ if pr_subscription
+ else None,
+ work_item_subscription_id=_subscription_id(work_item_subscription)
+ if work_item_subscription
+ else None,
+ webhook_url=webhook_url,
+ webhook_secret_set=bool(IS_LOCAL_DEPLOYMENT or AZURE_DEVOPS_WEBHOOK_SECRET),
+ )
+
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.exception(f'Error retrieving Azure DevOps resources: {e}')
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail='Failed to retrieve Azure DevOps resources',
+ )
+
+
+@azure_devops_integration_router.post('/azure-devops/reinstall-webhook')
+async def reinstall_azure_devops_webhook(
+ user_id: str = Depends(require_permission(Permission.MANAGE_INTEGRATIONS)),
+) -> AzureDevOpsWebhookInstallationResult:
+ """Install or reinstall the org-wide Azure DevOps resolver Service Hooks."""
+ service = SaaSAzureDevOpsService(external_auth_id=user_id)
+ _ensure_azure_devops_organization(service)
+ webhook_secret = _ensure_azure_devops_webhook_secret()
+ webhook_url = azure_devops_webhook_url()
+
+ try:
+ subscriptions = await service.list_service_hook_subscriptions()
+ for subscription in subscriptions:
+ subscription_id = _subscription_id(subscription)
+ if not subscription_id:
+ continue
+ if _matches_pr_comment_subscription(
+ subscription, webhook_url=webhook_url
+ ) or _matches_work_item_comment_subscription(
+ subscription, webhook_url=webhook_url
+ ):
+ await service.delete_service_hook_subscription(subscription_id)
+
+ pr_subscription = await service.create_pr_comment_service_hook(
+ webhook_url=webhook_url,
+ webhook_secret=webhook_secret,
+ )
+ work_item_subscription = await service.create_work_item_comment_service_hook(
+ webhook_url=webhook_url,
+ webhook_secret=webhook_secret,
+ )
+
+ pr_subscription_id = _subscription_id(pr_subscription)
+ work_item_subscription_id = _subscription_id(work_item_subscription)
+
+ logger.info(
+ '[Azure DevOps] Resolver hooks installed',
+ extra={
+ 'user_id': user_id,
+ 'organization': service.organization,
+ 'pr_subscription_id': pr_subscription_id,
+ 'work_item_subscription_id': work_item_subscription_id,
+ },
+ )
+
+ return AzureDevOpsWebhookInstallationResult(
+ organization=service.organization,
+ success=True,
+ error=None,
+ pr_subscription_id=pr_subscription_id,
+ work_item_subscription_id=work_item_subscription_id,
+ webhook_url=webhook_url,
+ )
+
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.exception(f'Error installing Azure DevOps resolver hooks: {e}')
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail='Failed to install Azure DevOps resolver hooks',
+ )
+
+
+@azure_devops_integration_router.post('/azure-devops/uninstall-webhook')
+async def uninstall_azure_devops_webhook(
+ user_id: str = Depends(require_permission(Permission.MANAGE_INTEGRATIONS)),
+) -> AzureDevOpsWebhookInstallationResult:
+ """Delete the org-wide Azure DevOps resolver Service Hooks."""
+ service = SaaSAzureDevOpsService(external_auth_id=user_id)
+ _ensure_azure_devops_organization(service)
+ webhook_url = azure_devops_webhook_url()
+
+ try:
+ subscriptions = await service.list_service_hook_subscriptions()
+ deleted_pr_subscription_id: str | None = None
+ deleted_work_item_subscription_id: str | None = None
+
+ for subscription in subscriptions:
+ subscription_id = _subscription_id(subscription)
+ if not subscription_id:
+ continue
+ if _matches_pr_comment_subscription(subscription, webhook_url=webhook_url):
+ await service.delete_service_hook_subscription(subscription_id)
+ deleted_pr_subscription_id = subscription_id
+ elif _matches_work_item_comment_subscription(
+ subscription, webhook_url=webhook_url
+ ):
+ await service.delete_service_hook_subscription(subscription_id)
+ deleted_work_item_subscription_id = subscription_id
+
+ logger.info(
+ '[Azure DevOps] Resolver hooks uninstalled',
+ extra={
+ 'user_id': user_id,
+ 'organization': service.organization,
+ 'pr_subscription_id': deleted_pr_subscription_id,
+ 'work_item_subscription_id': deleted_work_item_subscription_id,
+ },
+ )
+
+ return AzureDevOpsWebhookInstallationResult(
+ organization=service.organization,
+ success=True,
+ error=None,
+ pr_subscription_id=deleted_pr_subscription_id,
+ work_item_subscription_id=deleted_work_item_subscription_id,
+ webhook_url=webhook_url,
+ )
+
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.exception(f'Error uninstalling Azure DevOps resolver hooks: {e}')
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail='Failed to uninstall Azure DevOps resolver hooks',
+ )
+
+
+@azure_devops_integration_router.post('/azure-devops/events')
+async def azure_devops_events(
+ request: Request,
+ background_tasks: BackgroundTasks,
+ x_openhands_webhook_secret: str | None = Header(None),
+ authorization: str | None = Header(None),
+):
+ try:
+ await verify_azure_devops_signature(
+ header_webhook_secret=x_openhands_webhook_secret,
+ authorization=authorization,
+ )
+
+ payload_data = await request.json()
+ # Dedup on the stable event id; notificationId changes on ADO retries,
+ # so including it would let a retried delivery start a duplicate job.
+ dedup_key = payload_data.get('id')
+ if dedup_key:
+ dedup_key = f'azure_devops_msg:{dedup_key}'
+ else:
+ dedup_json = json.dumps(payload_data, sort_keys=True)
+ dedup_hash = hashlib.sha256(dedup_json.encode()).hexdigest()
+ dedup_key = f'azure_devops_msg:{dedup_hash}'
+
+ redis = get_redis_client_async()
+ created = await redis.set(dedup_key, 1, nx=True, ex=60)
+ if not created:
+ logger.info('azure_devops_is_duplicate')
+ return JSONResponse(
+ status_code=200,
+ content={'message': 'Duplicate Azure DevOps event ignored.'},
+ )
+
+ message = Message(
+ source=SourceType.AZURE_DEVOPS,
+ message={
+ 'payload': payload_data,
+ 'event_key': payload_data.get('eventType'),
+ },
+ )
+ # Process in the background so we return 200 fast; conversation/sandbox
+ # startup can exceed Service Hooks' delivery timeout -> retries. Mirrors
+ # the Jira DC / Bitbucket DC routes. Signature is verified above.
+ background_tasks.add_task(get_azure_devops_manager().receive_message, message)
+
+ return JSONResponse(
+ status_code=200,
+ content={'message': 'Azure DevOps events endpoint reached successfully.'},
+ )
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.exception(f'Error processing Azure DevOps event: {e}')
+ return JSONResponse(status_code=400, content={'error': 'Invalid payload.'})
diff --git a/enterprise/tests/unit/integrations/azure_devops/test_azure_devops_manager.py b/enterprise/tests/unit/integrations/azure_devops/test_azure_devops_manager.py
new file mode 100644
index 0000000000..f0e108177c
--- /dev/null
+++ b/enterprise/tests/unit/integrations/azure_devops/test_azure_devops_manager.py
@@ -0,0 +1,80 @@
+"""Tests for AzureDevOpsManager.receive_message write-access gating."""
+
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from integrations.azure_devops.azure_devops_manager import AzureDevOpsManager
+from integrations.models import Message, SourceType
+
+
+def _pr_comment_message(body: str = '@openhands please fix this') -> Message:
+ return Message(
+ source=SourceType.AZURE_DEVOPS,
+ message={
+ 'event_key': 'ms.vss-code.git-pullrequest-comment-event',
+ 'payload': {
+ 'eventType': 'ms.vss-code.git-pullrequest-comment-event',
+ 'resourceContainers': {
+ 'account': {'baseUrl': 'https://dev.azure.com/alonaking/'}
+ },
+ 'resource': {
+ 'comment': {
+ 'id': 2,
+ 'author': {
+ 'id': 'ado-user-id',
+ 'displayName': 'Alice Example',
+ 'uniqueName': '[email protected]',
+ },
+ 'content': body,
+ },
+ 'pullRequest': {
+ 'pullRequestId': 7,
+ 'sourceRefName': 'refs/heads/feature/x',
+ 'repository': {
+ 'id': 'repo-1',
+ 'name': 'Repo',
+ 'project': {'id': 'proj-1', 'name': 'Project'},
+ },
+ },
+ },
+ },
+ },
+ )
+
+
+async def test_receive_message_skips_when_commenter_lacks_write_access(monkeypatch):
+ manager = AzureDevOpsManager(AsyncMock())
+ manager._resolve_mentioner_keycloak_id = AsyncMock(return_value='kc-alice') # type: ignore[method-assign]
+ manager.start_job = AsyncMock() # type: ignore[method-assign]
+
+ fake_service = MagicMock()
+ fake_service.has_contribute_access = AsyncMock(return_value=False)
+ monkeypatch.setattr(
+ 'integrations.azure_devops.azure_devops_manager.AzureDevOpsServiceImpl',
+ lambda external_auth_id: fake_service,
+ )
+
+ await manager.receive_message(_pr_comment_message())
+
+ fake_service.has_contribute_access.assert_awaited_once_with('proj-1', 'repo-1')
+ manager.start_job.assert_not_called()
+
+
+async def test_receive_message_dispatches_when_commenter_has_write_access(monkeypatch):
+ manager = AzureDevOpsManager(AsyncMock())
+ manager._resolve_mentioner_keycloak_id = AsyncMock(return_value='kc-alice') # type: ignore[method-assign]
+ manager.start_job = AsyncMock() # type: ignore[method-assign]
+
+ fake_service = MagicMock()
+ fake_service.has_contribute_access = AsyncMock(return_value=True)
+ monkeypatch.setattr(
+ 'integrations.azure_devops.azure_devops_manager.AzureDevOpsServiceImpl',
+ lambda external_auth_id: fake_service,
+ )
+
+ await manager.receive_message(_pr_comment_message())
+
+ fake_service.has_contribute_access.assert_awaited_once_with('proj-1', 'repo-1')
+ manager.start_job.assert_awaited_once()
diff --git a/enterprise/tests/unit/integrations/azure_devops/test_azure_devops_service.py b/enterprise/tests/unit/integrations/azure_devops/test_azure_devops_service.py
index 5109625ef6..383a967993 100644
--- a/enterprise/tests/unit/integrations/azure_devops/test_azure_devops_service.py
+++ b/enterprise/tests/unit/integrations/azure_devops/test_azure_devops_service.py
@@ -2,11 +2,12 @@
from unittest.mock import AsyncMock, patch
+import httpx
import pytest
from integrations.azure_devops.azure_devops_service import SaaSAzureDevOpsService
from pydantic import SecretStr
-from openhands.app_server.integrations.service_types import ProviderType
+from openhands.app_server.integrations.service_types import ProviderType, RequestMethod
@pytest.mark.asyncio
@@ -98,3 +99,170 @@ async def test_get_latest_token_leaves_cached_token_when_refresh_unavailable():
assert token is None
assert service.token.get_secret_value() == 'stored-token'
+
+
+async def test_pr_comment_urls_do_not_duplicate_organization():
+ service = SaaSAzureDevOpsService(token=SecretStr('token'), base_domain='alonaking')
+ service._make_request = AsyncMock(return_value=({'id': 1}, {})) # type: ignore[method-assign]
+
+ await service.add_pr_comment_to_thread(
+ 'alonaking/My Project/My Repo',
+ 12,
+ 5,
+ 'hello',
+ )
+
+ url = service._make_request.await_args.kwargs['url']
+ assert url.startswith(
+ 'https://dev.azure.com/alonaking/My%20Project/_apis/git/repositories/My%20Repo/'
+ )
+ assert 'alonaking/alonaking' not in url
+
+
+async def test_work_item_comment_urls_do_not_duplicate_organization():
+ service = SaaSAzureDevOpsService(token=SecretStr('token'), base_domain='alonaking')
+ service._make_request = AsyncMock(return_value=({'id': 1}, {})) # type: ignore[method-assign]
+
+ await service.add_work_item_comment(
+ 'alonaking/My Project/My Repo',
+ 42,
+ 'hello',
+ )
+
+ url = service._make_request.await_args.kwargs['url']
+ assert url.startswith(
+ 'https://dev.azure.com/alonaking/My%20Project/_apis/wit/workItems/42/'
+ )
+ assert 'alonaking/alonaking' not in url
+
+
+async def test_make_request_accepts_successful_empty_response_body():
+ service = SaaSAzureDevOpsService(token=SecretStr('token'), base_domain='alonaking')
+ request = httpx.Request('DELETE', 'https://dev.azure.com/alonaking/_apis/hooks/1')
+ response = httpx.Response(204, request=request)
+
+ with patch.object(
+ service,
+ 'execute_request',
+ new_callable=AsyncMock,
+ return_value=response,
+ ):
+ body, headers = await service._make_request(
+ url='https://dev.azure.com/alonaking/_apis/hooks/1',
+ method=RequestMethod.DELETE,
+ )
+
+ assert body == {}
+ assert headers == {}
+
+
+async def test_create_pr_comment_service_hook_posts_expected_payload():
+ service = SaaSAzureDevOpsService(token=SecretStr('token'), base_domain='alonaking')
+ service._make_request = AsyncMock( # type: ignore[method-assign]
+ return_value=({'id': 'subscription-id'}, {})
+ )
+
+ response = await service.create_pr_comment_service_hook(
+ webhook_url='https://app.example.com/integration/azure-devops/events',
+ webhook_secret='secret',
+ )
+
+ assert response == {'id': 'subscription-id'}
+ kwargs = service._make_request.await_args.kwargs
+ assert kwargs['url'] == (
+ 'https://dev.azure.com/alonaking/_apis/hooks/subscriptions?api-version=7.1'
+ )
+ assert kwargs['method'] == RequestMethod.POST
+ assert kwargs['params']['eventType'] == 'ms.vss-code.git-pullrequest-comment-event'
+ assert kwargs['params']['resourceVersion'] == '2.0'
+ assert kwargs['params']['publisherInputs'] == {}
+ assert kwargs['params']['consumerInputs']['url'] == (
+ 'https://app.example.com/integration/azure-devops/events'
+ )
+ assert kwargs['params']['consumerInputs']['basicAuthUsername'] == 'openhands'
+ assert kwargs['params']['consumerInputs']['basicAuthPassword'] == 'secret'
+
+
+async def test_has_contribute_access_posts_repo_token_and_returns_evaluation():
+ service = SaaSAzureDevOpsService(token=SecretStr('token'), base_domain='alonaking')
+ service._make_request = AsyncMock( # type: ignore[method-assign]
+ return_value=({'evaluations': [{'value': True}]}, {})
+ )
+
+ result = await service.has_contribute_access('proj-1', 'repo-1')
+
+ assert result is True
+ kwargs = service._make_request.await_args.kwargs
+ assert kwargs['url'] == (
+ 'https://dev.azure.com/alonaking/_apis/security/permissionevaluationbatch'
+ '?api-version=7.1-preview.1'
+ )
+ assert kwargs['method'] == RequestMethod.POST
+ evaluation = kwargs['params']['evaluations'][0]
+ assert evaluation['token'] == 'repoV2/proj-1/repo-1'
+ assert evaluation['permissions'] == 4
+
+
+async def test_has_contribute_access_fails_closed_on_missing_ids():
+ service = SaaSAzureDevOpsService(token=SecretStr('token'), base_domain='alonaking')
+ service._make_request = AsyncMock() # type: ignore[method-assign]
+
+ assert await service.has_contribute_access('', 'repo-1') is False
+ service._make_request.assert_not_called()
+
+
+async def test_has_contribute_access_fails_closed_on_error():
+ service = SaaSAzureDevOpsService(token=SecretStr('token'), base_domain='alonaking')
+ service._make_request = AsyncMock(side_effect=RuntimeError('boom')) # type: ignore[method-assign]
+
+ assert await service.has_contribute_access('proj-1', 'repo-1') is False
+
+
+async def test_get_project_repositories_returns_value_list():
+ service = SaaSAzureDevOpsService(token=SecretStr('token'), base_domain='alonaking')
+ service._make_request = AsyncMock( # type: ignore[method-assign]
+ return_value=({'value': [{'id': 'repo-1', 'name': 'svc'}]}, {})
+ )
+
+ repos = await service.get_project_repositories('My Project')
+
+ assert repos == [{'id': 'repo-1', 'name': 'svc'}]
+ call = service._make_request.await_args
+ url = call.kwargs.get('url') or call.args[0]
+ assert url == (
+ 'https://dev.azure.com/alonaking/My%20Project/_apis/git/repositories'
+ '?api-version=7.1'
+ )
+
+
+async def test_create_work_item_comment_service_hook_posts_expected_payload():
+ service = SaaSAzureDevOpsService(token=SecretStr('token'), base_domain='alonaking')
+ service._make_request = AsyncMock( # type: ignore[method-assign]
+ return_value=({'id': 'subscription-id'}, {})
+ )
+
+ response = await service.create_work_item_comment_service_hook(
+ webhook_url='https://app.example.com/integration/azure-devops/events',
+ webhook_secret='secret',
+ )
+
+ assert response == {'id': 'subscription-id'}
+ kwargs = service._make_request.await_args.kwargs
+ assert kwargs['url'] == (
+ 'https://dev.azure.com/alonaking/_apis/hooks/subscriptions?api-version=7.1'
+ )
+ assert kwargs['method'] == RequestMethod.POST
+ assert kwargs['params']['eventType'] == 'workitem.commented'
+ assert kwargs['params']['resourceVersion'] == '1.0'
+ assert kwargs['params']['publisherInputs'] == {}
+ assert kwargs['params']['consumerInputs']['basicAuthUsername'] == 'openhands'
+ assert kwargs['params']['consumerInputs']['basicAuthPassword'] == 'secret'
diff --git a/enterprise/tests/unit/integrations/azure_devops/test_azure_devops_view.py b/enterprise/tests/unit/integrations/azure_devops/test_azure_devops_view.py
new file mode 100644
index 0000000000..50bd42ef48
--- /dev/null
+++ b/enterprise/tests/unit/integrations/azure_devops/test_azure_devops_view.py
@@ -0,0 +1,400 @@
+from pathlib import Path
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from integrations.azure_devops.azure_devops_view import (
+ AzureDevOpsFactory,
+ AzureDevOpsPRComment,
+ AzureDevOpsWorkItemComment,
+ _select_project_repo,
+ actor_email,
+ mark_openhands_comment,
+)
+from integrations.models import Message, SourceType
+from jinja2 import Environment, FileSystemLoader
+
+
+def jinja_env() -> Environment:
+ repo_root = Path(__file__).resolve().parents[5]
+ return Environment(
+ loader=FileSystemLoader(
+ str(
+ repo_root
+ / 'openhands/app_server/integrations/templates/resolver/azure_devops'
+ )
+ )
+ )
+
+
+def _make_pr_message(body: str = '@openhands please fix this') -> Message:
+ return Message(
+ source=SourceType.AZURE_DEVOPS,
+ message={
+ 'event_key': 'ms.vss-code.git-pullrequest-comment-event',
+ 'payload': {
+ 'eventType': 'ms.vss-code.git-pullrequest-comment-event',
+ 'resourceContainers': {
+ 'account': {'baseUrl': 'https://dev.azure.com/alonaking/'}
+ },
+ 'resource': {
+ 'comment': {
+ 'id': 2,
+ 'author': {
+ 'id': 'ado-user-id',
+ 'displayName': 'Alice Example',
+ 'uniqueName': '[email protected]',
+ },
+ 'content': body,
+ '_links': {
+ 'threads': {
+ 'href': 'https://dev.azure.com/alonaking/Project/_apis/git/repositories/repo/pullRequests/7/threads/5'
+ }
+ },
+ },
+ 'pullRequest': {
+ 'pullRequestId': 7,
+ 'sourceRefName': 'refs/heads/feature/x',
+ 'repository': {
+ 'id': 'repo-1',
+ 'name': 'Repo',
+ 'project': {'id': 'proj-1', 'name': 'Project'},
+ 'remoteUrl': 'https://dev.azure.com/alonaking/Project/_git/Repo',
+ },
+ },
+ },
+ },
+ },
+ )
+
+
+def _make_work_item_message(body: str = '@openhands please fix work item') -> Message:
+ return Message(
+ source=SourceType.AZURE_DEVOPS,
+ message={
+ 'event_key': 'workitem.commented',
+ 'payload': {
+ 'eventType': 'workitem.commented',
+ 'resourceContainers': {
+ 'account': {'baseUrl': 'https://dev.azure.com/alonaking/'}
+ },
+ 'resource': {
+ 'id': 42,
+ 'revisedBy': {
+ 'id': 'ado-revised-user-id',
+ 'displayName': 'Alice Revised',
+ 'uniqueName': '[email protected]',
+ },
+ 'fields': {
+ 'System.TeamProject': 'Project',
+ 'System.ChangedBy': {
+ 'id': 'ado-user-id',
+ 'displayName': 'Alice Example',
+ 'uniqueName': '[email protected]',
+ },
+ 'System.History': body,
+ },
+ '_links': {
+ 'self': {
+ 'href': 'https://dev.azure.com/alonaking/Project/_apis/wit/workItems/42'
+ }
+ },
+ },
+ },
+ },
+ )
+
+
+def test_is_pr_comment_requires_exact_mention():
+ assert AzureDevOpsFactory.is_pr_comment(_make_pr_message()) is True
+ assert AzureDevOpsFactory.is_pr_comment(_make_pr_message('hello')) is False
+ assert (
+ AzureDevOpsFactory.is_pr_comment(
+ _make_pr_message(mark_openhands_comment('@openhands generated summary'))
+ )
+ is False
+ )
+
+
+def test_is_work_item_comment_requires_exact_mention():
+ assert AzureDevOpsFactory.is_work_item_comment(_make_work_item_message()) is True
+ assert (
+ AzureDevOpsFactory.is_work_item_comment(_make_work_item_message('hello'))
+ is False
+ )
+ assert (
+ AzureDevOpsFactory.is_work_item_comment(
+ _make_work_item_message(
+ mark_openhands_comment('@openhands generated summary')
+ )
+ )
+ is False
+ )
+
+
+async def test_factory_creates_pr_comment_view():
+ view = await AzureDevOpsFactory.create_azure_devops_view_from_payload(
+ _make_pr_message(),
+ keycloak_user_id='kc-alice',
+ )
+
+ assert isinstance(view, AzureDevOpsPRComment)
+ assert view.full_repo_name == 'alonaking/Project/Repo'
+ assert view.issue_number == 7
+ assert view.comment_id == 2
+ assert view.thread_id == 5
+ assert view.branch_name == 'feature/x'
+ assert view.user_info.user_id == 'ado-user-id'
+ assert view.user_info.keycloak_user_id == 'kc-alice'
+ assert view.project_id == 'proj-1'
+ assert view.repository_id == 'repo-1'
+
+
+async def test_factory_work_item_view_derives_real_repo(monkeypatch):
+ # System.TeamProject ('Project') matches a repo name -> use the matched repo.
+ fake_service = MagicMock()
+ fake_service.get_project_repositories = AsyncMock(
+ return_value=[
+ {'id': 'repo-9', 'name': 'service-api', 'project': {'id': 'proj-9'}},
+ {'id': 'repo-1', 'name': 'Project', 'project': {'id': 'proj-9'}},
+ ]
+ )
+ monkeypatch.setattr(
+ 'integrations.azure_devops.azure_devops_view.AzureDevOpsServiceImpl',
+ lambda external_auth_id: fake_service,
+ )
+
+ view = await AzureDevOpsFactory.create_azure_devops_view_from_payload(
+ _make_work_item_message(),
+ keycloak_user_id='kc-alice',
+ )
+
+ assert isinstance(view, AzureDevOpsWorkItemComment)
+ assert view.full_repo_name == 'alonaking/Project/Project'
+ assert view.repository_id == 'repo-1'
+ assert view.project_id == 'proj-9'
+ assert view.issue_number == 42
+ assert view.comment_body == '@openhands please fix work item'
+ assert view.user_info.user_id == 'ado-revised-user-id'
+ assert view.user_info.username == 'Alice Revised'
+
+
+async def test_factory_work_item_view_uses_sole_repo(monkeypatch):
+ # No name match but exactly one repo -> use it.
+ fake_service = MagicMock()
+ fake_service.get_project_repositories = AsyncMock(
+ return_value=[
+ {'id': 'repo-9', 'name': 'service-api', 'project': {'id': 'proj-9'}}
+ ]
+ )
+ monkeypatch.setattr(
+ 'integrations.azure_devops.azure_devops_view.AzureDevOpsServiceImpl',
+ lambda external_auth_id: fake_service,
+ )
+
+ view = await AzureDevOpsFactory.create_azure_devops_view_from_payload(
+ _make_work_item_message(),
+ keycloak_user_id='kc-alice',
+ )
+
+ assert isinstance(view, AzureDevOpsWorkItemComment)
+ assert view.full_repo_name == 'alonaking/Project/service-api'
+ assert view.repository_id == 'repo-9'
+
+
+async def test_factory_work_item_view_returns_none_when_ambiguous(monkeypatch):
+ # Multiple repos, none matching the project name -> fail closed (skip).
+ fake_service = MagicMock()
+ fake_service.get_project_repositories = AsyncMock(
+ return_value=[
+ {'id': 'repo-9', 'name': 'service-api', 'project': {'id': 'proj-9'}},
+ {'id': 'repo-2', 'name': 'docs', 'project': {'id': 'proj-9'}},
+ ]
+ )
+ monkeypatch.setattr(
+ 'integrations.azure_devops.azure_devops_view.AzureDevOpsServiceImpl',
+ lambda external_auth_id: fake_service,
+ )
+
+ view = await AzureDevOpsFactory.create_azure_devops_view_from_payload(
+ _make_work_item_message(),
+ keycloak_user_id='kc-alice',
+ )
+
+ assert view is None
+
+
+async def test_factory_work_item_view_returns_none_when_no_repos(monkeypatch):
+ fake_service = MagicMock()
+ fake_service.get_project_repositories = AsyncMock(return_value=[])
+ monkeypatch.setattr(
+ 'integrations.azure_devops.azure_devops_view.AzureDevOpsServiceImpl',
+ lambda external_auth_id: fake_service,
+ )
+
+ view = await AzureDevOpsFactory.create_azure_devops_view_from_payload(
+ _make_work_item_message(),
+ keycloak_user_id='kc-alice',
+ )
+
+ assert view is None
+
+
+def test_select_project_repo_resolution():
+ name_match = {'id': 'r1', 'name': 'Project'}
+ other = {'id': 'r2', 'name': 'docs'}
+
+ # Name match wins even among several repos.
+ assert _select_project_repo([other, name_match], 'project') is name_match
+ # Sole repo is used when nothing matches by name.
+ assert _select_project_repo([other], 'Project') is other
+ # Multiple repos with no name match -> None (ambiguous).
+ assert _select_project_repo([other, {'id': 'r3', 'name': 'api'}], 'Project') is None
+ # No repos -> None.
+ assert _select_project_repo([], 'Project') is None
+
+
+async def test_pr_comment_instructions_include_actionable_comment(jinja_env):
+ view = await AzureDevOpsFactory.create_azure_devops_view_from_payload(
+ _make_pr_message(),
+ keycloak_user_id='kc-alice',
+ )
+
+ async def _load_context():
+ view.title = 'PR title'
+ view.description = 'PR body'
+ view.previous_comments = [
+ MagicMock(author='bob', created_at='2026-01-01', body='older comment')
+ ]
+
+ view._load_resolver_context = AsyncMock(side_effect=_load_context) # type: ignore[method-assign]
+
+ user_instructions, conversation_instructions = await view._get_instructions(
+ jinja_env
+ )
+
+ assert '@openhands please fix this' in user_instructions
+ assert 'PR title' in conversation_instructions
+ assert 'PR body' in conversation_instructions
+ assert 'older comment' in conversation_instructions
+
+
+async def test_work_item_load_resolver_context_uses_work_item_not_pr(monkeypatch):
+ # Work item #42 can collide with PR #42; ensure WI context is loaded, not PR.
+ fake_service = MagicMock()
+ fake_service.get_project_repositories = AsyncMock(
+ return_value=[{'id': 'repo-1', 'name': 'Project', 'project': {'id': 'proj-9'}}]
+ )
+ fake_service.get_work_item_comments = AsyncMock(
+ return_value=[MagicMock(author='wi-user', body='work item comment')]
+ )
+ fake_service.get_work_item_title_and_body = AsyncMock(
+ return_value=('Work item title', 'Work item body')
+ )
+ fake_service.get_issue_or_pr_comments = AsyncMock(
+ return_value=[MagicMock(author='pr-user', body='pr comment')]
+ )
+ fake_service.get_issue_or_pr_title_and_body = AsyncMock(
+ return_value=('PR title', 'PR body')
+ )
+ monkeypatch.setattr(
+ 'integrations.azure_devops.azure_devops_view.AzureDevOpsServiceImpl',
+ lambda external_auth_id: fake_service,
+ )
+
+ view = await AzureDevOpsFactory.create_azure_devops_view_from_payload(
+ _make_work_item_message(),
+ keycloak_user_id='kc-alice',
+ )
+ assert isinstance(view, AzureDevOpsWorkItemComment)
+
+ await view._load_resolver_context()
+
+ assert view.title == 'Work item title'
+ assert view.description == 'Work item body'
+ assert view.previous_comments[0].body == 'work item comment'
+ fake_service.get_work_item_title_and_body.assert_awaited_once_with(42)
+ fake_service.get_work_item_comments.assert_awaited_once()
+ fake_service.get_issue_or_pr_comments.assert_not_called()
+ fake_service.get_issue_or_pr_title_and_body.assert_not_called()
+
+
+async def test_pr_comment_load_resolver_context_uses_pr_not_work_item(monkeypatch):
+ # A brand-new PR whose only comment is the @openhands mention returns an empty
+ # list from get_pr_comments. The loader must NOT fall back to work-item
+ # discussion in that case; it must stay on the PR code path.
+ fake_service = MagicMock()
+ fake_service.get_pr_comments = AsyncMock(return_value=[]) # empty — new PR
+ fake_service.get_issue_or_pr_title_and_body = AsyncMock(
+ return_value=('PR title', 'PR body')
+ )
+ fake_service.get_work_item_comments = AsyncMock(
+ return_value=[MagicMock(author='wi-user', body='work item comment')]
+ )
+ fake_service.get_issue_or_pr_comments = AsyncMock(
+ return_value=[MagicMock(author='pr-user', body='pr comment')]
+ )
+ monkeypatch.setattr(
+ 'integrations.azure_devops.azure_devops_view.AzureDevOpsServiceImpl',
+ lambda external_auth_id: fake_service,
+ )
+
+ view = await AzureDevOpsFactory.create_azure_devops_view_from_payload(
+ _make_pr_message(),
+ keycloak_user_id='kc-alice',
+ )
+ assert isinstance(view, AzureDevOpsPRComment)
+
+ await view._load_resolver_context()
+
+ assert view.title == 'PR title'
+ assert view.description == 'PR body'
+ assert view.previous_comments == [] # empty list, not work-item fallback
+ fake_service.get_pr_comments.assert_awaited_once()
+ fake_service.get_issue_or_pr_title_and_body.assert_awaited_once()
+ fake_service.get_work_item_comments.assert_not_called()
+ fake_service.get_issue_or_pr_comments.assert_not_called()
+
+
+async def test_factory_returns_none_when_org_empty(monkeypatch):
+ # No resolvable org -> skip rather than build a malformed '/project/repo'.
+ monkeypatch.setattr(
+ 'integrations.azure_devops.azure_devops_view._extract_org',
+ lambda payload: '',
+ )
+
+ view = await AzureDevOpsFactory.create_azure_devops_view_from_payload(
+ _make_pr_message(),
+ keycloak_user_id='kc-alice',
+ )
+
+ assert view is None
+
+
+async def test_pr_view_get_branch_name_returns_branch():
+ view = await AzureDevOpsFactory.create_azure_devops_view_from_payload(
+ _make_pr_message(),
+ keycloak_user_id='kc-alice',
+ )
+
+ assert isinstance(view, AzureDevOpsPRComment)
+ assert view._get_branch_name() == 'feature/x'
+
+
+def test_actor_email_extracts_email_from_unique_name_or_display_name():
+ assert actor_email({'uniqueName': '[email protected]'}) == '[email protected]'
+ assert (
+ actor_email({'displayName': 'Alice Example <[email protected]>'})
+ )
+ assert actor_email({'displayName': 'Alice Example'}) == ''
diff --git a/enterprise/tests/unit/server/routes/test_azure_devops_integration_routes.py b/enterprise/tests/unit/server/routes/test_azure_devops_integration_routes.py
new file mode 100644
index 0000000000..938c7b844d
--- /dev/null
+++ b/enterprise/tests/unit/server/routes/test_azure_devops_integration_routes.py
@@ -0,0 +1,342 @@
+import base64
+from unittest.mock import ANY, AsyncMock, MagicMock
+
+import pytest
+from fastapi import HTTPException
+from server.routes.integration import azure_devops
+
+
+async def test_verify_azure_devops_signature_accepts_header_secret(monkeypatch):
+ monkeypatch.setattr(azure_devops, 'IS_LOCAL_DEPLOYMENT', False)
+ monkeypatch.setattr(azure_devops, 'AZURE_DEVOPS_WEBHOOK_SECRET', 'expected')
+
+ await azure_devops.verify_azure_devops_signature('expected', None)
+
+
+async def test_verify_azure_devops_signature_accepts_basic_auth(monkeypatch):
+ monkeypatch.setattr(azure_devops, 'IS_LOCAL_DEPLOYMENT', False)
+ monkeypatch.setattr(azure_devops, 'AZURE_DEVOPS_WEBHOOK_SECRET', 'expected')
+ encoded = base64.b64encode(b'openhands:expected').decode()
+
+ await azure_devops.verify_azure_devops_signature(None, f'Basic {encoded}')
+
+
+async def test_verify_azure_devops_signature_rejects_bad_secret(monkeypatch):
+ monkeypatch.setattr(azure_devops, 'IS_LOCAL_DEPLOYMENT', False)
+ monkeypatch.setattr(azure_devops, 'AZURE_DEVOPS_WEBHOOK_SECRET', 'expected')
+
+ with pytest.raises(HTTPException) as exc_info:
+ await azure_devops.verify_azure_devops_signature('wrong', None)
+
+ assert exc_info.value.status_code == 403
+
+
+async def test_get_azure_devops_resources_reports_installed_status(monkeypatch):
+ monkeypatch.setattr(azure_devops, 'HOST_URL', 'https://app.example.com')
+ monkeypatch.setattr(azure_devops, 'AZURE_DEVOPS_WEBHOOK_SECRET', 'secret')
+
+ class FakeAzureDevOpsService:
+ organization = 'alonaking'
+
+ async def list_service_hook_subscriptions(self):
+ # Org-wide subscriptions carry no projectId.
+ return [
+ {
+ 'id': 'pr-subscription-id',
+ 'eventType': azure_devops.AZURE_DEVOPS_PR_COMMENT_EVENT,
+ 'publisherInputs': {},
+ 'consumerInputs': {
+ 'url': 'https://app.example.com/integration/azure-devops/events',
+ },
+ 'status': 'enabled',
+ },
+ {
+ 'id': 'work-item-subscription-id',
+ 'eventType': azure_devops.AZURE_DEVOPS_WORK_ITEM_COMMENT_EVENT,
+ 'publisherInputs': {},
+ 'consumerInputs': {
+ 'url': 'https://app.example.com/integration/azure-devops/events',
+ },
+ 'status': 'enabled',
+ },
+ ]
+
+ monkeypatch.setattr(
+ azure_devops,
+ 'SaaSAzureDevOpsService',
+ lambda external_auth_id: FakeAzureDevOpsService(),
+ )
+
+ status = await azure_devops.get_azure_devops_resources(user_id='user-id')
+
+ assert status.organization == 'alonaking'
+ assert status.webhook_installed is True
+ assert status.pr_webhook_installed is True
+ assert status.work_item_webhook_installed is True
+ assert status.pr_subscription_id == 'pr-subscription-id'
+ assert status.work_item_subscription_id == 'work-item-subscription-id'
+ assert (
+ status.webhook_url == 'https://app.example.com/integration/azure-devops/events'
+ )
+
+
+async def test_get_azure_devops_resources_reports_disabled_hook_as_not_installed(
+ monkeypatch,
+):
+ monkeypatch.setattr(azure_devops, 'HOST_URL', 'https://app.example.com')
+ monkeypatch.setattr(azure_devops, 'AZURE_DEVOPS_WEBHOOK_SECRET', 'secret')
+ url = 'https://app.example.com/integration/azure-devops/events'
+
+ class FakeAzureDevOpsService:
+ organization = 'alonaking'
+
+ async def list_service_hook_subscriptions(self):
+ return [
+ {
+ 'id': 'pr-subscription-id',
+ 'eventType': azure_devops.AZURE_DEVOPS_PR_COMMENT_EVENT,
+ 'publisherInputs': {},
+ 'consumerInputs': {'url': url},
+ 'status': 'enabled',
+ },
+ {
+ 'id': 'work-item-subscription-id',
+ 'eventType': azure_devops.AZURE_DEVOPS_WORK_ITEM_COMMENT_EVENT,
+ 'publisherInputs': {},
+ 'consumerInputs': {'url': url},
+ 'status': 'disabledByUser',
+ },
+ ]
+
+ monkeypatch.setattr(
+ azure_devops,
+ 'SaaSAzureDevOpsService',
+ lambda external_auth_id: FakeAzureDevOpsService(),
+ )
+
+ status = await azure_devops.get_azure_devops_resources(user_id='user-id')
+
+ # Disabled work-item hook -> org not fully installed, but id still surfaced.
+ assert status.webhook_installed is False
+ assert status.pr_webhook_installed is True
+ assert status.work_item_webhook_installed is False
+ assert status.work_item_subscription_id == 'work-item-subscription-id'
+
+
+def test_matchers_require_absent_project_id():
+ url = 'https://app.example.com/integration/azure-devops/events'
+ org_wide = {
+ 'eventType': azure_devops.AZURE_DEVOPS_PR_COMMENT_EVENT,
+ 'publisherInputs': {},
+ 'consumerInputs': {'url': url},
+ }
+ project_scoped = {
+ 'eventType': azure_devops.AZURE_DEVOPS_PR_COMMENT_EVENT,
+ 'publisherInputs': {'projectId': 'proj-guid'},
+ 'consumerInputs': {'url': url},
+ }
+
+ assert (
+ azure_devops._matches_pr_comment_subscription(org_wide, webhook_url=url) is True
+ )
+ assert (
+ azure_devops._matches_pr_comment_subscription(project_scoped, webhook_url=url)
+ is False
+ )
+
+
+async def test_get_azure_devops_resources_ignores_project_scoped_hooks(monkeypatch):
+ monkeypatch.setattr(azure_devops, 'HOST_URL', 'https://app.example.com')
+ monkeypatch.setattr(azure_devops, 'AZURE_DEVOPS_WEBHOOK_SECRET', 'secret')
+
+ url = 'https://app.example.com/integration/azure-devops/events'
+
+ class FakeAzureDevOpsService:
+ organization = 'alonaking'
+
+ async def list_service_hook_subscriptions(self):
+ # Same event types + url, but project-scoped (projectId set) -> must
+ # NOT be reported as the org-wide install.
+ return [
+ {
+ 'id': 'pr-project-scoped',
+ 'eventType': azure_devops.AZURE_DEVOPS_PR_COMMENT_EVENT,
+ 'publisherInputs': {'projectId': 'proj-guid'},
+ 'consumerInputs': {'url': url},
+ },
+ {
+ 'id': 'wi-project-scoped',
+ 'eventType': azure_devops.AZURE_DEVOPS_WORK_ITEM_COMMENT_EVENT,
+ 'publisherInputs': {'projectId': 'proj-guid'},
+ 'consumerInputs': {'url': url},
+ },
+ ]
+
+ monkeypatch.setattr(
+ azure_devops,
+ 'SaaSAzureDevOpsService',
+ lambda external_auth_id: FakeAzureDevOpsService(),
+ )
+
+ status = await azure_devops.get_azure_devops_resources(user_id='user-id')
+
+ assert status.webhook_installed is False
+ assert status.pr_webhook_installed is False
+ assert status.work_item_webhook_installed is False
+ assert status.pr_subscription_id is None
+ assert status.work_item_subscription_id is None
+
+
+async def test_reinstall_azure_devops_webhook_replaces_existing_hooks(monkeypatch):
+ monkeypatch.setattr(azure_devops, 'HOST_URL', 'https://app.example.com')
+ monkeypatch.setattr(azure_devops, 'IS_LOCAL_DEPLOYMENT', False)
+ monkeypatch.setattr(azure_devops, 'AZURE_DEVOPS_WEBHOOK_SECRET', 'secret')
+
+ class FakeAzureDevOpsService:
+ organization = 'alonaking'
+
+ def __init__(self):
+ self.delete_service_hook_subscription = AsyncMock()
+ self.create_pr_comment_service_hook = AsyncMock(
+ return_value={'id': 'new-pr-subscription-id'}
+ )
+ self.create_work_item_comment_service_hook = AsyncMock(
+ return_value={'id': 'new-work-item-subscription-id'}
+ )
+
+ async def list_service_hook_subscriptions(self):
+ return [
+ {
+ 'id': 'old-pr-subscription-id',
+ 'eventType': azure_devops.AZURE_DEVOPS_PR_COMMENT_EVENT,
+ 'publisherInputs': {},
+ 'consumerInputs': {
+ 'url': 'https://app.example.com/integration/azure-devops/events',
+ },
+ },
+ {
+ 'id': 'old-work-item-subscription-id',
+ 'eventType': azure_devops.AZURE_DEVOPS_WORK_ITEM_COMMENT_EVENT,
+ 'publisherInputs': {},
+ 'consumerInputs': {
+ 'url': 'https://app.example.com/integration/azure-devops/events',
+ },
+ },
+ ]
+
+ fake_service = FakeAzureDevOpsService()
+ monkeypatch.setattr(
+ azure_devops,
+ 'SaaSAzureDevOpsService',
+ lambda external_auth_id: fake_service,
+ )
+
+ response = await azure_devops.reinstall_azure_devops_webhook(user_id='user-id')
+
+ assert response.success is True
+ assert response.organization == 'alonaking'
+ assert response.pr_subscription_id == 'new-pr-subscription-id'
+ assert response.work_item_subscription_id == 'new-work-item-subscription-id'
+ fake_service.delete_service_hook_subscription.assert_any_await(
+ 'old-pr-subscription-id'
+ )
+ fake_service.delete_service_hook_subscription.assert_any_await(
+ 'old-work-item-subscription-id'
+ )
+ fake_service.create_pr_comment_service_hook.assert_awaited_once_with(
+ webhook_url='https://app.example.com/integration/azure-devops/events',
+ webhook_secret='secret',
+ )
+ fake_service.create_work_item_comment_service_hook.assert_awaited_once_with(
+ webhook_url='https://app.example.com/integration/azure-devops/events',
+ webhook_secret='secret',
+ )
+
+
+async def test_reinstall_azure_devops_webhook_requires_configured_secret(monkeypatch):
+ monkeypatch.setattr(azure_devops, 'IS_LOCAL_DEPLOYMENT', False)
+ monkeypatch.setattr(azure_devops, 'AZURE_DEVOPS_WEBHOOK_SECRET', '')
+
+ class FakeAzureDevOpsService:
+ organization = 'alonaking'
+
+ monkeypatch.setattr(
+ azure_devops,
+ 'SaaSAzureDevOpsService',
+ lambda external_auth_id: FakeAzureDevOpsService(),
+ )
+
+ with pytest.raises(HTTPException) as exc_info:
+ await azure_devops.reinstall_azure_devops_webhook(user_id='user-id')
+
+ assert exc_info.value.status_code == 503
+
+
+async def test_events_route_schedules_receive_message_in_background(monkeypatch):
+ monkeypatch.setattr(azure_devops, 'IS_LOCAL_DEPLOYMENT', False)
+ monkeypatch.setattr(azure_devops, 'AZURE_DEVOPS_WEBHOOK_SECRET', 'secret')
+
+ fake_redis = MagicMock()
+ fake_redis.set = AsyncMock(return_value=True)
+ monkeypatch.setattr(azure_devops, 'get_redis_client_async', lambda: fake_redis)
+
+ fake_manager = MagicMock()
+ fake_manager.receive_message = AsyncMock()
+ monkeypatch.setattr(azure_devops, 'get_azure_devops_manager', lambda: fake_manager)
+
+ class _FakeRequest:
+ async def json(self):
+ return {'id': 'evt-1', 'eventType': 'workitem.commented'}
+
+ background_tasks = MagicMock()
+
+ response = await azure_devops.azure_devops_events(
+ request=_FakeRequest(),
+ background_tasks=background_tasks,
+ x_openhands_webhook_secret='secret',
+ authorization=None,
+ )
+
+ assert response.status_code == 200
+ # receive_message is queued, not awaited inline (avoids Service Hooks timeout).
+ background_tasks.add_task.assert_called_once_with(fake_manager.receive_message, ANY)
+ fake_manager.receive_message.assert_not_awaited()
+
+
+async def test_events_route_skips_duplicate_without_scheduling(monkeypatch):
+ monkeypatch.setattr(azure_devops, 'IS_LOCAL_DEPLOYMENT', False)
+ monkeypatch.setattr(azure_devops, 'AZURE_DEVOPS_WEBHOOK_SECRET', 'secret')
+
+ fake_redis = MagicMock()
+ fake_redis.set = AsyncMock(return_value=False) # already seen -> duplicate
+ monkeypatch.setattr(azure_devops, 'get_redis_client_async', lambda: fake_redis)
+
+ fake_manager = MagicMock()
+ fake_manager.receive_message = AsyncMock()
+ monkeypatch.setattr(azure_devops, 'get_azure_devops_manager', lambda: fake_manager)
+
+ class _FakeRequest:
+ async def json(self):
+ return {'id': 'evt-1', 'eventType': 'workitem.commented'}
+
+ background_tasks = MagicMock()
+
+ response = await azure_devops.azure_devops_events(
+ request=_FakeRequest(),
+ background_tasks=background_tasks,
+ x_openhands_webhook_secret='secret',
+ authorization=None,
+ )
+
+ assert response.status_code == 200
+ background_tasks.add_task.assert_not_called()
diff --git a/frontend/src/api/integration-service/integration-service.api.ts b/frontend/src/api/integration-service/integration-service.api.ts
index ee7500acd9..539aa32faa 100644
--- a/frontend/src/api/integration-service/integration-service.api.ts
+++ b/frontend/src/api/integration-service/integration-service.api.ts
@@ -1,5 +1,7 @@
import { openHands } from "../open-hands-axios";
import {
+ AzureDevOpsWebhookStatus,
+ AzureDevOpsWebhookInstallationResult,
BitbucketDCResourcesResponse,
BitbucketDCWebhookEnrollmentResult,
BitbucketDCWebhookIdUpdateResult,
@@ -125,4 +127,38 @@ export const integrationService = {
);
return data;
},
+
+ /**
+ * Get the org-wide Azure DevOps resolver hook installation status.
+ */
+ getAzureDevOpsResources: async (): Promise<AzureDevOpsWebhookStatus> => {
+ const { data } = await openHands.get<AzureDevOpsWebhookStatus>(
+ "/integration/azure-devops/resources",
+ );
+ return data;
+ },
+
+ /**
+ * Install or reinstall the org-wide Azure DevOps resolver Service Hooks.
+ */
+ reinstallAzureDevOpsWebhook:
+ async (): Promise<AzureDevOpsWebhookInstallationResult> => {
+ const { data } =
+ await openHands.post<AzureDevOpsWebhookInstallationResult>(
+ "/integration/azure-devops/reinstall-webhook",
+ );
+ return data;
+ },
+
+ /**
+ * Delete the org-wide Azure DevOps resolver Service Hooks.
+ */
+ uninstallAzureDevOpsWebhook:
+ async (): Promise<AzureDevOpsWebhookInstallationResult> => {
+ const { data } =
+ await openHands.post<AzureDevOpsWebhookInstallationResult>(
+ "/integration/azure-devops/uninstall-webhook",
+ );
+ return data;
+ },
};
diff --git a/frontend/src/api/integration-service/integration-service.types.ts b/frontend/src/api/integration-service/integration-service.types.ts
index 31df81c943..b44c7983de 100644
--- a/frontend/src/api/integration-service/integration-service.types.ts
+++ b/frontend/src/api/integration-service/integration-service.types.ts
@@ -93,3 +93,23 @@ export interface BitbucketDCWebhookInstallationResult {
connection_id: number | null;
webhook_url: string | null;
}
+
+export interface AzureDevOpsWebhookStatus {
+ organization: string;
+ webhook_installed: boolean;
+ pr_webhook_installed: boolean;
+ work_item_webhook_installed: boolean;
+ pr_subscription_id: string | null;
+ work_item_subscription_id: string | null;
+ webhook_url: string;
+ webhook_secret_set: boolean;
+}
+
+export interface AzureDevOpsWebhookInstallationResult {
+ organization: string;
+ success: boolean;
+ error: string | null;
+ pr_subscription_id: string | null;
+ work_item_subscription_id: string | null;
+ webhook_url: string;
+}
diff --git a/frontend/src/components/features/settings/git-settings/azure-devops-webhook-manager.tsx b/frontend/src/components/features/settings/git-settings/azure-devops-webhook-manager.tsx
new file mode 100644
index 0000000000..76d4ecfbe4
--- /dev/null
+++ b/frontend/src/components/features/settings/git-settings/azure-devops-webhook-manager.tsx
@@ -0,0 +1,177 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import type { AzureDevOpsWebhookStatus } from "#/api/integration-service/integration-service.types";
+import { useAzureDevOpsResources } from "#/hooks/query/use-azure-devops-resources-list";
+import { useReinstallAzureDevOpsWebhook } from "#/hooks/mutation/use-reinstall-azure-devops-webhook";
+import { useUninstallAzureDevOpsWebhook } from "#/hooks/mutation/use-uninstall-azure-devops-webhook";
+import { I18nKey } from "#/i18n/declaration";
+import { cn } from "#/utils/utils";
+import { Typography } from "#/ui/typography";
+
+interface AzureDevOpsWebhookManagerProps {
+ className?: string;
+}
+
+function StatusBadge({ status }: { status: AzureDevOpsWebhookStatus }) {
+ const { t } = useTranslation();
+
+ if (!status.webhook_secret_set) {
+ return (
+ <Typography.Text className="px-2 py-1 text-xs rounded bg-red-500/20 text-red-400">
+ {t(I18nKey.AZURE_DEVOPS$WEBHOOK_STATUS_MISSING_SECRET)}
+ </Typography.Text>
+ );
+ }
+
+ if (status.webhook_installed) {
+ return (
+ <Typography.Text className="px-2 py-1 text-xs rounded bg-green-500/20 text-green-400">
+ {t(I18nKey.AZURE_DEVOPS$WEBHOOK_STATUS_INSTALLED)}
+ </Typography.Text>
+ );
+ }
+
+ if (status.pr_webhook_installed || status.work_item_webhook_installed) {
+ return (
+ <Typography.Text className="px-2 py-1 text-xs rounded bg-yellow-500/20 text-yellow-300">
+ {t(I18nKey.AZURE_DEVOPS$WEBHOOK_STATUS_PARTIAL)}
+ </Typography.Text>
+ );
+ }
+
+ return (
+ <Typography.Text className="px-2 py-1 text-xs rounded bg-gray-500/20 text-gray-400">
+ {t(I18nKey.AZURE_DEVOPS$WEBHOOK_STATUS_NOT_INSTALLED)}
+ </Typography.Text>
+ );
+}
+
+export function AzureDevOpsWebhookManager({
+ className,
+}: AzureDevOpsWebhookManagerProps) {
+ const { t } = useTranslation();
+ const [isInstalling, setIsInstalling] = useState(false);
+ const [isUninstalling, setIsUninstalling] = useState(false);
+
+ const { data: status, isLoading, isError } = useAzureDevOpsResources(true);
+ const reinstallMutation = useReinstallAzureDevOpsWebhook();
+ const uninstallMutation = useUninstallAzureDevOpsWebhook();
+
+ const handleReinstall = async () => {
+ setIsInstalling(true);
+ try {
+ await reinstallMutation.mutateAsync();
+ } finally {
+ setIsInstalling(false);
+ }
+ };
+
+ const handleUninstall = async () => {
+ setIsUninstalling(true);
+ try {
+ await uninstallMutation.mutateAsync();
+ } finally {
+ setIsUninstalling(false);
+ }
+ };
+
+ if (isLoading || isError || !status) {
+ return (
+ <div className={cn("flex flex-col gap-4", className)}>
+ <Typography.H3 className="text-lg font-medium text-white">
+ {t(I18nKey.AZURE_DEVOPS$WEBHOOK_MANAGER_TITLE)}
+ </Typography.H3>
+ <Typography.Text
+ className={cn("text-sm", isError ? "text-red-400" : "text-gray-400")}
+ >
+ {isError
+ ? t(I18nKey.AZURE_DEVOPS$WEBHOOK_MANAGER_ERROR)
+ : t(I18nKey.AZURE_DEVOPS$WEBHOOK_MANAGER_LOADING)}
+ </Typography.Text>
+ </div>
+ );
+ }
+
+ const anyMutationPending = isInstalling || isUninstalling;
+ const installDisabled = anyMutationPending || !status.webhook_secret_set;
+
+ let installLabel: string;
+ if (isInstalling) {
+ installLabel = t(I18nKey.AZURE_DEVOPS$WEBHOOK_INSTALLING);
+ } else if (status.webhook_installed) {
+ installLabel = t(I18nKey.AZURE_DEVOPS$WEBHOOK_REINSTALL);
+ } else {
+ installLabel = t(I18nKey.AZURE_DEVOPS$WEBHOOK_INSTALL);
+ }
+
+ return (
+ <div className={cn("flex flex-col gap-4", className)}>
+ <Typography.H3 className="text-lg font-medium text-white">
+ {t(I18nKey.AZURE_DEVOPS$WEBHOOK_MANAGER_TITLE)}
+ </Typography.H3>
+
+ <Typography.Text className="text-sm text-gray-400">
+ {t(I18nKey.AZURE_DEVOPS$WEBHOOK_MANAGER_DESCRIPTION)}
+ </Typography.Text>
+
+ <div className="border border-neutral-700 rounded-lg overflow-hidden">
+ <table className="w-full">
+ <thead className="bg-neutral-800">
+ <tr>
+ <th className="px-4 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">
+ {t(I18nKey.AZURE_DEVOPS$WEBHOOK_COLUMN_ORGANIZATION)}
+ </th>
+ <th className="px-4 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">
+ {t(I18nKey.AZURE_DEVOPS$WEBHOOK_COLUMN_STATUS)}
+ </th>
+ <th className="px-4 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">
+ {t(I18nKey.AZURE_DEVOPS$WEBHOOK_COLUMN_ACTION)}
+ </th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-neutral-700">
+ <tr className="hover:bg-neutral-800/50 transition-colors align-top">
+ <td className="px-4 py-3">
+ <Typography.Text className="text-sm font-medium text-white">
+ {status.organization}
+ </Typography.Text>
+ </td>
+ <td className="px-4 py-3">
+ <StatusBadge status={status} />
+ </td>
+ <td className="px-4 py-3">
+ <div className="flex gap-2">
+ <BrandButton
+ type="button"
+ variant="primary"
+ onClick={handleReinstall}
+ isDisabled={installDisabled}
+ className="cursor-pointer"
+ testId="azure-devops-install-webhook"
+ >
+ {installLabel}
+ </BrandButton>
+ {status.webhook_installed && (
+ <BrandButton
+ type="button"
+ variant="secondary"
+ onClick={handleUninstall}
+ isDisabled={anyMutationPending}
+ className="cursor-pointer"
+ testId="azure-devops-uninstall-webhook"
+ >
+ {isUninstalling
+ ? t(I18nKey.AZURE_DEVOPS$WEBHOOK_UNINSTALLING)
+ : t(I18nKey.AZURE_DEVOPS$WEBHOOK_UNINSTALL)}
+ </BrandButton>
+ )}
+ </div>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/hooks/mutation/use-reinstall-azure-devops-webhook.ts b/frontend/src/hooks/mutation/use-reinstall-azure-devops-webhook.ts
new file mode 100644
index 0000000000..08ebffd122
--- /dev/null
+++ b/frontend/src/hooks/mutation/use-reinstall-azure-devops-webhook.ts
@@ -0,0 +1,39 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { useTranslation } from "react-i18next";
+import { integrationService } from "#/api/integration-service/integration-service.api";
+import type { AzureDevOpsWebhookInstallationResult } from "#/api/integration-service/integration-service.types";
+import { I18nKey } from "#/i18n/declaration";
+import {
+ displayErrorToast,
+ displaySuccessToast,
+} from "#/utils/custom-toast-handlers";
+
+export function useReinstallAzureDevOpsWebhook() {
+ const queryClient = useQueryClient();
+ const { t } = useTranslation();
+
+ return useMutation<
+ AzureDevOpsWebhookInstallationResult,
+ Error,
+ void,
+ unknown
+ >({
+ mutationFn: () => integrationService.reinstallAzureDevOpsWebhook(),
+ onSuccess: (data) => {
+ queryClient.invalidateQueries({ queryKey: ["azure-devops-resources"] });
+
+ if (data.success) {
+ displaySuccessToast(t(I18nKey.AZURE_DEVOPS$WEBHOOK_INSTALL_SUCCESS));
+ } else if (data.error) {
+ displayErrorToast(data.error);
+ } else {
+ displayErrorToast(t(I18nKey.AZURE_DEVOPS$WEBHOOK_INSTALL_FAILED));
+ }
+ },
+ onError: (error) => {
+ displayErrorToast(
+ error?.message || t(I18nKey.AZURE_DEVOPS$WEBHOOK_INSTALL_FAILED),
+ );
+ },
+ });
+}
diff --git a/frontend/src/hooks/mutation/use-uninstall-azure-devops-webhook.ts b/frontend/src/hooks/mutation/use-uninstall-azure-devops-webhook.ts
new file mode 100644
index 0000000000..e8bf8c68af
--- /dev/null
+++ b/frontend/src/hooks/mutation/use-uninstall-azure-devops-webhook.ts
@@ -0,0 +1,39 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { useTranslation } from "react-i18next";
+import { integrationService } from "#/api/integration-service/integration-service.api";
+import type { AzureDevOpsWebhookInstallationResult } from "#/api/integration-service/integration-service.types";
+import { I18nKey } from "#/i18n/declaration";
+import {
+ displayErrorToast,
+ displaySuccessToast,
+} from "#/utils/custom-toast-handlers";
+
+export function useUninstallAzureDevOpsWebhook() {
+ const queryClient = useQueryClient();
+ const { t } = useTranslation();
+
+ return useMutation<
+ AzureDevOpsWebhookInstallationResult,
+ Error,
+ void,
+ unknown
+ >({
+ mutationFn: () => integrationService.uninstallAzureDevOpsWebhook(),
+ onSuccess: (data) => {
+ queryClient.invalidateQueries({ queryKey: ["azure-devops-resources"] });
+
+ if (data.success) {
+ displaySuccessToast(t(I18nKey.AZURE_DEVOPS$WEBHOOK_UNINSTALL_SUCCESS));
+ } else if (data.error) {
+ displayErrorToast(data.error);
+ } else {
+ displayErrorToast(t(I18nKey.AZURE_DEVOPS$WEBHOOK_UNINSTALL_FAILED));
+ }
+ },
+ onError: (error) => {
+ displayErrorToast(
+ error?.message || t(I18nKey.AZURE_DEVOPS$WEBHOOK_UNINSTALL_FAILED),
+ );
+ },
+ });
+}
diff --git a/frontend/src/hooks/query/use-azure-devops-resources-list.ts b/frontend/src/hooks/query/use-azure-devops-resources-list.ts
new file mode 100644
index 0000000000..8176ebeed1
--- /dev/null
+++ b/frontend/src/hooks/query/use-azure-devops-resources-list.ts
@@ -0,0 +1,13 @@
+import { useQuery } from "@tanstack/react-query";
+import { integrationService } from "#/api/integration-service/integration-service.api";
+import type { AzureDevOpsWebhookStatus } from "#/api/integration-service/integration-service.types";
+
+export function useAzureDevOpsResources(enabled: boolean = true) {
+ return useQuery<AzureDevOpsWebhookStatus>({
+ queryKey: ["azure-devops-resources"],
+ queryFn: () => integrationService.getAzureDevOpsResources(),
+ enabled,
+ staleTime: 1000 * 60 * 2,
+ gcTime: 1000 * 60 * 10,
+ });
+}
diff --git a/frontend/src/i18n/declaration.ts b/frontend/src/i18n/declaration.ts
index 15fca3315e..503027dc69 100644
--- a/frontend/src/i18n/declaration.ts
+++ b/frontend/src/i18n/declaration.ts
@@ -300,6 +300,26 @@ export enum I18nKey {
SETTINGS$GITHUB = "SETTINGS$GITHUB",
SETTINGS$AZURE_DEVOPS = "SETTINGS$AZURE_DEVOPS",
AZURE_DEVOPS$NOT_CONNECTED = "AZURE_DEVOPS$NOT_CONNECTED",
+ AZURE_DEVOPS$WEBHOOK_MANAGER_TITLE = "AZURE_DEVOPS$WEBHOOK_MANAGER_TITLE",
+ AZURE_DEVOPS$WEBHOOK_COLUMN_ORGANIZATION = "AZURE_DEVOPS$WEBHOOK_COLUMN_ORGANIZATION",
+ AZURE_DEVOPS$WEBHOOK_COLUMN_STATUS = "AZURE_DEVOPS$WEBHOOK_COLUMN_STATUS",
+ AZURE_DEVOPS$WEBHOOK_COLUMN_ACTION = "AZURE_DEVOPS$WEBHOOK_COLUMN_ACTION",
+ AZURE_DEVOPS$WEBHOOK_MANAGER_DESCRIPTION = "AZURE_DEVOPS$WEBHOOK_MANAGER_DESCRIPTION",
+ AZURE_DEVOPS$WEBHOOK_MANAGER_LOADING = "AZURE_DEVOPS$WEBHOOK_MANAGER_LOADING",
+ AZURE_DEVOPS$WEBHOOK_MANAGER_ERROR = "AZURE_DEVOPS$WEBHOOK_MANAGER_ERROR",
+ AZURE_DEVOPS$WEBHOOK_STATUS_INSTALLED = "AZURE_DEVOPS$WEBHOOK_STATUS_INSTALLED",
+ AZURE_DEVOPS$WEBHOOK_STATUS_NOT_INSTALLED = "AZURE_DEVOPS$WEBHOOK_STATUS_NOT_INSTALLED",
+ AZURE_DEVOPS$WEBHOOK_STATUS_PARTIAL = "AZURE_DEVOPS$WEBHOOK_STATUS_PARTIAL",
+ AZURE_DEVOPS$WEBHOOK_STATUS_MISSING_SECRET = "AZURE_DEVOPS$WEBHOOK_STATUS_MISSING_SECRET",
+ AZURE_DEVOPS$WEBHOOK_INSTALL = "AZURE_DEVOPS$WEBHOOK_INSTALL",
+ AZURE_DEVOPS$WEBHOOK_INSTALLING = "AZURE_DEVOPS$WEBHOOK_INSTALLING",
+ AZURE_DEVOPS$WEBHOOK_REINSTALL = "AZURE_DEVOPS$WEBHOOK_REINSTALL",
+ AZURE_DEVOPS$WEBHOOK_UNINSTALL = "AZURE_DEVOPS$WEBHOOK_UNINSTALL",
+ AZURE_DEVOPS$WEBHOOK_UNINSTALLING = "AZURE_DEVOPS$WEBHOOK_UNINSTALLING",
+ AZURE_DEVOPS$WEBHOOK_INSTALL_SUCCESS = "AZURE_DEVOPS$WEBHOOK_INSTALL_SUCCESS",
+ AZURE_DEVOPS$WEBHOOK_INSTALL_FAILED = "AZURE_DEVOPS$WEBHOOK_INSTALL_FAILED",
+ AZURE_DEVOPS$WEBHOOK_UNINSTALL_SUCCESS = "AZURE_DEVOPS$WEBHOOK_UNINSTALL_SUCCESS",
+ AZURE_DEVOPS$WEBHOOK_UNINSTALL_FAILED = "AZURE_DEVOPS$WEBHOOK_UNINSTALL_FAILED",
SETTINGS$SLACK = "SETTINGS$SLACK",
COMMON$STATUS = "COMMON$STATUS",
SETTINGS$GITLAB_NOT_CONNECTED = "SETTINGS$GITLAB_NOT_CONNECTED",
diff --git a/frontend/src/i18n/translation.json b/frontend/src/i18n/translation.json
index 07909c8a90..76533942e3 100644
--- a/frontend/src/i18n/translation.json
+++ b/frontend/src/i18n/translation.json
@@ -5099,6 +5099,346 @@
"uk": "Azure DevOps не підключено",
"ca": "Azure DevOps no connectat"
},
+ "AZURE_DEVOPS$WEBHOOK_MANAGER_TITLE": {
+ "en": "Azure DevOps webhooks",
+ "ja": "Azure DevOps webhooks",
+ "zh-CN": "Azure DevOps webhooks",
+ "zh-TW": "Azure DevOps webhooks",
+ "ko-KR": "Azure DevOps webhooks",
+ "no": "Azure DevOps webhooks",
+ "it": "Azure DevOps webhooks",
+ "pt": "Azure DevOps webhooks",
+ "es": "Azure DevOps webhooks",
+ "ar": "Azure DevOps webhooks",
+ "fr": "Azure DevOps webhooks",
+ "tr": "Azure DevOps webhooks",
+ "de": "Azure DevOps webhooks",
+ "uk": "Azure DevOps webhooks",
+ "ca": "Azure DevOps webhooks"
+ },
+ "AZURE_DEVOPS$WEBHOOK_COLUMN_ORGANIZATION": {
+ "en": "Organization",
+ "ja": "Organization",
+ "zh-CN": "Organization",
+ "zh-TW": "Organization",
+ "ko-KR": "Organization",
+ "no": "Organization",
+ "it": "Organization",
+ "pt": "Organization",
+ "es": "Organization",
+ "ar": "Organization",
+ "fr": "Organization",
+ "tr": "Organization",
+ "de": "Organization",
+ "uk": "Organization",
+ "ca": "Organization"
+ },
+ "AZURE_DEVOPS$WEBHOOK_COLUMN_STATUS": {
+ "en": "Status",
+ "ja": "Status",
+ "zh-CN": "Status",
+ "zh-TW": "Status",
+ "ko-KR": "Status",
+ "no": "Status",
+ "it": "Status",
+ "pt": "Status",
+ "es": "Status",
+ "ar": "Status",
+ "fr": "Status",
+ "tr": "Status",
+ "de": "Status",
+ "uk": "Status",
+ "ca": "Status"
+ },
+ "AZURE_DEVOPS$WEBHOOK_COLUMN_ACTION": {
+ "en": "Action",
+ "ja": "Action",
+ "zh-CN": "Action",
+ "zh-TW": "Action",
+ "ko-KR": "Action",
+ "no": "Action",
+ "it": "Action",
+ "pt": "Action",
+ "es": "Action",
+ "ar": "Action",
+ "fr": "Action",
+ "tr": "Action",
+ "de": "Action",
+ "uk": "Action",
+ "ca": "Action"
+ },
+ "AZURE_DEVOPS$WEBHOOK_MANAGER_DESCRIPTION": {
+ "en": "Installs an organization-wide webhook covering all projects so OpenHands can respond to Azure DevOps PR and work item mentions.",
+ "ja": "Installs an organization-wide webhook covering all projects so OpenHands can respond to Azure DevOps PR and work item mentions.",
+ "zh-CN": "Installs an organization-wide webhook covering all projects so OpenHands can respond to Azure DevOps PR and work item mentions.",
+ "zh-TW": "Installs an organization-wide webhook covering all projects so OpenHands can respond to Azure DevOps PR and work item mentions.",
+ "ko-KR": "Installs an organization-wide webhook covering all projects so OpenHands can respond to Azure DevOps PR and work item mentions.",
+ "no": "Installs an organization-wide webhook covering all projects so OpenHands can respond to Azure DevOps PR and work item mentions.",
+ "it": "Installs an organization-wide webhook covering all projects so OpenHands can respond to Azure DevOps PR and work item mentions.",
+ "pt": "Installs an organization-wide webhook covering all projects so OpenHands can respond to Azure DevOps PR and work item mentions.",
+ "es": "Installs an organization-wide webhook covering all projects so OpenHands can respond to Azure DevOps PR and work item mentions.",
+ "ar": "Installs an organization-wide webhook covering all projects so OpenHands can respond to Azure DevOps PR and work item mentions.",
+ "fr": "Installs an organization-wide webhook covering all projects so OpenHands can respond to Azure DevOps PR and work item mentions.",
+ "tr": "Installs an organization-wide webhook covering all projects so OpenHands can respond to Azure DevOps PR and work item mentions.",
+ "de": "Installs an organization-wide webhook covering all projects so OpenHands can respond to Azure DevOps PR and work item mentions.",
+ "uk": "Installs an organization-wide webhook covering all projects so OpenHands can respond to Azure DevOps PR and work item mentions.",
+ "ca": "Installs an organization-wide webhook covering all projects so OpenHands can respond to Azure DevOps PR and work item mentions."
+ },
+ "AZURE_DEVOPS$WEBHOOK_MANAGER_LOADING": {
+ "en": "Loading webhook status...",
+ "ja": "Loading webhook status...",
+ "zh-CN": "Loading webhook status...",
+ "zh-TW": "Loading webhook status...",
+ "ko-KR": "Loading webhook status...",
+ "no": "Loading webhook status...",
+ "it": "Loading webhook status...",
+ "pt": "Loading webhook status...",
+ "es": "Loading webhook status...",
+ "ar": "Loading webhook status...",
+ "fr": "Loading webhook status...",
+ "tr": "Loading webhook status...",
+ "de": "Loading webhook status...",
+ "uk": "Loading webhook status...",
+ "ca": "Loading webhook status..."
+ },
+ "AZURE_DEVOPS$WEBHOOK_MANAGER_ERROR": {
+ "en": "Failed to load Azure DevOps webhook status.",
+ "ja": "Failed to load Azure DevOps webhook status.",
+ "zh-CN": "Failed to load Azure DevOps webhook status.",
+ "zh-TW": "Failed to load Azure DevOps webhook status.",
+ "ko-KR": "Failed to load Azure DevOps webhook status.",
+ "no": "Failed to load Azure DevOps webhook status.",
+ "it": "Failed to load Azure DevOps webhook status.",
+ "pt": "Failed to load Azure DevOps webhook status.",
+ "es": "Failed to load Azure DevOps webhook status.",
+ "ar": "Failed to load Azure DevOps webhook status.",
+ "fr": "Failed to load Azure DevOps webhook status.",
+ "tr": "Failed to load Azure DevOps webhook status.",
+ "de": "Failed to load Azure DevOps webhook status.",
+ "uk": "Failed to load Azure DevOps webhook status.",
+ "ca": "Failed to load Azure DevOps webhook status."
+ },
+ "AZURE_DEVOPS$WEBHOOK_STATUS_INSTALLED": {
+ "en": "Installed",
+ "ja": "Installed",
+ "zh-CN": "Installed",
+ "zh-TW": "Installed",
+ "ko-KR": "Installed",
+ "no": "Installed",
+ "it": "Installed",
+ "pt": "Installed",
+ "es": "Installed",
+ "ar": "Installed",
+ "fr": "Installed",
+ "tr": "Installed",
+ "de": "Installed",
+ "uk": "Installed",
+ "ca": "Installed"
+ },
+ "AZURE_DEVOPS$WEBHOOK_STATUS_NOT_INSTALLED": {
+ "en": "Not installed",
+ "ja": "Not installed",
+ "zh-CN": "Not installed",
+ "zh-TW": "Not installed",
+ "ko-KR": "Not installed",
+ "no": "Not installed",
+ "it": "Not installed",
+ "pt": "Not installed",
+ "es": "Not installed",
+ "ar": "Not installed",
+ "fr": "Not installed",
+ "tr": "Not installed",
+ "de": "Not installed",
+ "uk": "Not installed",
+ "ca": "Not installed"
+ },
+ "AZURE_DEVOPS$WEBHOOK_STATUS_PARTIAL": {
+ "en": "Partial",
+ "ja": "Partial",
+ "zh-CN": "Partial",
+ "zh-TW": "Partial",
+ "ko-KR": "Partial",
+ "no": "Partial",
+ "it": "Partial",
+ "pt": "Partial",
+ "es": "Partial",
+ "ar": "Partial",
+ "fr": "Partial",
+ "tr": "Partial",
+ "de": "Partial",
+ "uk": "Partial",
+ "ca": "Partial"
+ },
+ "AZURE_DEVOPS$WEBHOOK_STATUS_MISSING_SECRET": {
+ "en": "Missing secret",
+ "ja": "Missing secret",
+ "zh-CN": "Missing secret",
+ "zh-TW": "Missing secret",
+ "ko-KR": "Missing secret",
+ "no": "Missing secret",
+ "it": "Missing secret",
+ "pt": "Missing secret",
+ "es": "Missing secret",
+ "ar": "Missing secret",
+ "fr": "Missing secret",
+ "tr": "Missing secret",
+ "de": "Missing secret",
+ "uk": "Missing secret",
+ "ca": "Missing secret"
+ },
+ "AZURE_DEVOPS$WEBHOOK_INSTALL": {
+ "en": "Install",
+ "ja": "Install",
+ "zh-CN": "Install",
+ "zh-TW": "Install",
+ "ko-KR": "Install",
+ "no": "Install",
+ "it": "Install",
+ "pt": "Install",
+ "es": "Install",
+ "ar": "Install",
+ "fr": "Install",
+ "tr": "Install",
+ "de": "Install",
+ "uk": "Install",
+ "ca": "Install"
+ },
+ "AZURE_DEVOPS$WEBHOOK_INSTALLING": {
+ "en": "Installing",
+ "ja": "Installing",
+ "zh-CN": "Installing",
+ "zh-TW": "Installing",
+ "ko-KR": "Installing",
+ "no": "Installing",
+ "it": "Installing",
+ "pt": "Installing",
+ "es": "Installing",
+ "ar": "Installing",
+ "fr": "Installing",
+ "tr": "Installing",
+ "de": "Installing",
+ "uk": "Installing",
+ "ca": "Installing"
+ },
+ "AZURE_DEVOPS$WEBHOOK_REINSTALL": {
+ "en": "Reinstall",
+ "ja": "Reinstall",
+ "zh-CN": "Reinstall",
+ "zh-TW": "Reinstall",
+ "ko-KR": "Reinstall",
+ "no": "Reinstall",
+ "it": "Reinstall",
+ "pt": "Reinstall",
+ "es": "Reinstall",
+ "ar": "Reinstall",
+ "fr": "Reinstall",
+ "tr": "Reinstall",
+ "de": "Reinstall",
+ "uk": "Reinstall",
+ "ca": "Reinstall"
+ },
+ "AZURE_DEVOPS$WEBHOOK_UNINSTALL": {
+ "en": "Uninstall",
+ "ja": "Uninstall",
+ "zh-CN": "Uninstall",
+ "zh-TW": "Uninstall",
+ "ko-KR": "Uninstall",
+ "no": "Uninstall",
+ "it": "Uninstall",
+ "pt": "Uninstall",
+ "es": "Uninstall",
+ "ar": "Uninstall",
+ "fr": "Uninstall",
+ "tr": "Uninstall",
+ "de": "Uninstall",
+ "uk": "Uninstall",
+ "ca": "Uninstall"
+ },
+ "AZURE_DEVOPS$WEBHOOK_UNINSTALLING": {
+ "en": "Uninstalling",
+ "ja": "Uninstalling",
+ "zh-CN": "Uninstalling",
+ "zh-TW": "Uninstalling",
+ "ko-KR": "Uninstalling",
+ "no": "Uninstalling",
+ "it": "Uninstalling",
+ "pt": "Uninstalling",
+ "es": "Uninstalling",
+ "ar": "Uninstalling",
+ "fr": "Uninstalling",
+ "tr": "Uninstalling",
+ "de": "Uninstalling",
+ "uk": "Uninstalling",
+ "ca": "Uninstalling"
+ },
+ "AZURE_DEVOPS$WEBHOOK_INSTALL_SUCCESS": {
+ "en": "Azure DevOps webhooks installed",
+ "ja": "Azure DevOps webhooks installed",
+ "zh-CN": "Azure DevOps webhooks installed",
+ "zh-TW": "Azure DevOps webhooks installed",
+ "ko-KR": "Azure DevOps webhooks installed",
+ "no": "Azure DevOps webhooks installed",
+ "it": "Azure DevOps webhooks installed",
+ "pt": "Azure DevOps webhooks installed",
+ "es": "Azure DevOps webhooks installed",
+ "ar": "Azure DevOps webhooks installed",
+ "fr": "Azure DevOps webhooks installed",
+ "tr": "Azure DevOps webhooks installed",
+ "de": "Azure DevOps webhooks installed",
+ "uk": "Azure DevOps webhooks installed",
+ "ca": "Azure DevOps webhooks installed"
+ },
+ "AZURE_DEVOPS$WEBHOOK_INSTALL_FAILED": {
+ "en": "Failed to install Azure DevOps webhooks",
+ "ja": "Failed to install Azure DevOps webhooks",
+ "zh-CN": "Failed to install Azure DevOps webhooks",
+ "zh-TW": "Failed to install Azure DevOps webhooks",
+ "ko-KR": "Failed to install Azure DevOps webhooks",
+ "no": "Failed to install Azure DevOps webhooks",
+ "it": "Failed to install Azure DevOps webhooks",
+ "pt": "Failed to install Azure DevOps webhooks",
+ "es": "Failed to install Azure DevOps webhooks",
+ "ar": "Failed to install Azure DevOps webhooks",
+ "fr": "Failed to install Azure DevOps webhooks",
+ "tr": "Failed to install Azure DevOps webhooks",
+ "de": "Failed to install Azure DevOps webhooks",
+ "uk": "Failed to install Azure DevOps webhooks",
+ "ca": "Failed to install Azure DevOps webhooks"
+ },
+ "AZURE_DEVOPS$WEBHOOK_UNINSTALL_SUCCESS": {
+ "en": "Azure DevOps webhooks uninstalled",
+ "ja": "Azure DevOps webhooks uninstalled",
+ "zh-CN": "Azure DevOps webhooks uninstalled",
+ "zh-TW": "Azure DevOps webhooks uninstalled",
+ "ko-KR": "Azure DevOps webhooks uninstalled",
+ "no": "Azure DevOps webhooks uninstalled",
+ "it": "Azure DevOps webhooks uninstalled",
+ "pt": "Azure DevOps webhooks uninstalled",
+ "es": "Azure DevOps webhooks uninstalled",
+ "ar": "Azure DevOps webhooks uninstalled",
+ "fr": "Azure DevOps webhooks uninstalled",
+ "tr": "Azure DevOps webhooks uninstalled",
+ "de": "Azure DevOps webhooks uninstalled",
+ "uk": "Azure DevOps webhooks uninstalled",
+ "ca": "Azure DevOps webhooks uninstalled"
+ },
+ "AZURE_DEVOPS$WEBHOOK_UNINSTALL_FAILED": {
+ "en": "Failed to uninstall Azure DevOps webhooks",
+ "ja": "Failed to uninstall Azure DevOps webhooks",
+ "zh-CN": "Failed to uninstall Azure DevOps webhooks",
+ "zh-TW": "Failed to uninstall Azure DevOps webhooks",
+ "ko-KR": "Failed to uninstall Azure DevOps webhooks",
+ "no": "Failed to uninstall Azure DevOps webhooks",
+ "it": "Failed to uninstall Azure DevOps webhooks",
+ "pt": "Failed to uninstall Azure DevOps webhooks",
+ "es": "Failed to uninstall Azure DevOps webhooks",
+ "ar": "Failed to uninstall Azure DevOps webhooks",
+ "fr": "Failed to uninstall Azure DevOps webhooks",
+ "tr": "Failed to uninstall Azure DevOps webhooks",
+ "de": "Failed to uninstall Azure DevOps webhooks",
+ "uk": "Failed to uninstall Azure DevOps webhooks",
+ "ca": "Failed to uninstall Azure DevOps webhooks"
+ },
"SETTINGS$SLACK": {
"en": "Slack",
"ja": "Slack",
diff --git a/frontend/src/routes/git-settings.tsx b/frontend/src/routes/git-settings.tsx
index 00af7a00cd..273a20d819 100644
--- a/frontend/src/routes/git-settings.tsx
+++ b/frontend/src/routes/git-settings.tsx
@@ -12,6 +12,7 @@ import { BitbucketTokenInput } from "#/components/features/settings/git-settings
import { BitbucketDCTokenInput } from "#/components/features/settings/git-settings/bitbucket-dc-token-help-input";
import { BitbucketDCWebhookManager } from "#/components/features/settings/git-settings/bitbucket-dc-webhook-manager";
import { AzureDevOpsTokenInput } from "#/components/features/settings/git-settings/azure-devops-token-input";
+import { AzureDevOpsWebhookManager } from "#/components/features/settings/git-settings/azure-devops-webhook-manager";
import { ForgejoTokenInput } from "#/components/features/settings/git-settings/forgejo-token-input";
import { ConfigureGitHubRepositoriesAnchor } from "#/components/features/settings/git-settings/configure-github-repositories-anchor";
import { ConfigureAzureDevOpsAnchor } from "#/components/features/settings/git-settings/configure-azure-devops-anchor";
@@ -330,7 +331,11 @@ function GitSettingsScreen() {
: t(I18nKey.AZURE_DEVOPS$NOT_CONNECTED)}
</Typography.Text>
</div>
- <ConfigureAzureDevOpsAnchor />
+ {isAzureDevOpsTokenSet ? (
+ <AzureDevOpsWebhookManager />
+ ) : (
+ <ConfigureAzureDevOpsAnchor />
+ )}
</div>
<div className="w-1/2 border-b border-gray-200" />
</>
diff --git a/openhands/app_server/integrations/azure_devops/azure_devops_service.py b/openhands/app_server/integrations/azure_devops/azure_devops_service.py
index b441cdb6e4..f12e0511f5 100644
--- a/openhands/app_server/integrations/azure_devops/azure_devops_service.py
+++ b/openhands/app_server/integrations/azure_devops/azure_devops_service.py
@@ -19,6 +19,9 @@ from openhands.app_server.integrations.azure_devops.service.repos import (
from openhands.app_server.integrations.azure_devops.service.resolver import (
AzureDevOpsResolverMixin,
)
+from openhands.app_server.integrations.azure_devops.service.webhooks import (
+ AzureDevOpsWebhooksMixin,
+)
from openhands.app_server.integrations.azure_devops.service.work_items import (
AzureDevOpsWorkItemsMixin,
)
@@ -40,6 +43,7 @@ class AzureDevOpsService(
AzureDevOpsPRsMixin,
AzureDevOpsWorkItemsMixin,
AzureDevOpsFeaturesMixin,
+ AzureDevOpsWebhooksMixin,
BaseGitService,
HTTPClient,
GitService,
@@ -53,6 +57,7 @@ class AzureDevOpsService(
- AzureDevOpsPRsMixin: Pull request operations
- AzureDevOpsWorkItemsMixin: Work item operations (unique to Azure DevOps)
- AzureDevOpsFeaturesMixin: Microagents, suggested tasks, user info
+ - AzureDevOpsWebhooksMixin: Service hook lifecycle operations
This is an extension point in OpenHands that allows applications to customize Azure DevOps
integration behavior. Applications can substitute their own implementation by:
@@ -201,6 +206,9 @@ class AzureDevOpsService(
if 'Link' in response.headers:
headers['Link'] = response.headers['Link']
+ if not response.content:
+ return {}, headers
+
return response.json(), headers
except httpx.HTTPStatusError as e:
diff --git a/openhands/app_server/integrations/azure_devops/service/base.py b/openhands/app_server/integrations/azure_devops/service/base.py
index 469734ade5..4b4ef7c1b4 100644
--- a/openhands/app_server/integrations/azure_devops/service/base.py
+++ b/openhands/app_server/integrations/azure_devops/service/base.py
@@ -52,7 +52,9 @@ class AzureDevOpsMixinBase(BaseGitService, HTTPClient):
def _truncate_comment(self, comment: str, max_length: int = 1000) -> str:
"""Truncate comment to max length."""
- raise NotImplementedError('Implemented in AzureDevOpsServiceImpl')
+ if len(comment) <= max_length:
+ return comment
+ return comment[:max_length] + '...'
@staticmethod
def _encode_url_component(component: str) -> str:
@@ -65,3 +67,8 @@ class AzureDevOpsMixinBase(BaseGitService, HTTPClient):
URL-encoded string with spaces and special characters properly encoded
"""
return quote(component, safe='')
+
+ def _project_base_url(self, org: str, project: str) -> str:
+ org_enc = self._encode_url_component(org)
+ project_enc = self._encode_url_component(project)
+ return f'https://dev.azure.com/{org_enc}/{project_enc}'
diff --git a/openhands/app_server/integrations/azure_devops/service/prs.py b/openhands/app_server/integrations/azure_devops/service/prs.py
index 15cd89d736..1490ce522f 100644
--- a/openhands/app_server/integrations/azure_devops/service/prs.py
+++ b/openhands/app_server/integrations/azure_devops/service/prs.py
@@ -12,12 +12,6 @@ from openhands.app_server.utils.logger import openhands_logger as logger
class AzureDevOpsPRsMixin(AzureDevOpsMixinBase):
"""Mixin for Azure DevOps pull request operations."""
- def _truncate_comment(self, comment: str, max_length: int = 1000) -> str:
- """Truncate comment to max length."""
- if len(comment) <= max_length:
- return comment
- return comment[:max_length] + '...'
-
async def add_pr_thread(
self,
repository: str,
@@ -46,15 +40,10 @@ class AzureDevOpsPRsMixin(AzureDevOpsMixinBase):
"""
org, project, repo = self._parse_repository(repository)
- # URL-encode components to handle spaces and special characters
- org_enc = self._encode_url_component(org)
- project_enc = self._encode_url_component(project)
repo_enc = self._encode_url_component(repo)
- url = f'{self.base_url}/{org_enc}/{project_enc}/_apis/git/repositories/{repo_enc}/pullrequests/{pr_number}/threads?api-version=7.1'
+ url = f'{self._project_base_url(org, project)}/_apis/git/repositories/{repo_enc}/pullrequests/{pr_number}/threads?api-version=7.1'
- # Create thread payload with a comment
- # Reference: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pull-request-threads/create
payload = {
'comments': [
{
@@ -98,12 +87,9 @@ class AzureDevOpsPRsMixin(AzureDevOpsMixinBase):
"""
org, project, repo = self._parse_repository(repository)
- # URL-encode components to handle spaces and special characters
- org_enc = self._encode_url_component(org)
- project_enc = self._encode_url_component(project)
repo_enc = self._encode_url_component(repo)
- url = f'{self.base_url}/{org_enc}/{project_enc}/_apis/git/repositories/{repo_enc}/pullrequests/{pr_number}/threads/{thread_id}/comments?api-version=7.1'
+ url = f'{self._project_base_url(org, project)}/_apis/git/repositories/{repo_enc}/pullrequests/{pr_number}/threads/{thread_id}/comments?api-version=7.1'
payload = {
'content': comment_text,
@@ -137,12 +123,9 @@ class AzureDevOpsPRsMixin(AzureDevOpsMixinBase):
"""
org, project, repo = self._parse_repository(repository)
- # URL-encode components to handle spaces and special characters
- org_enc = self._encode_url_component(org)
- project_enc = self._encode_url_component(project)
repo_enc = self._encode_url_component(repo)
- url = f'{self.base_url}/{org_enc}/{project_enc}/_apis/git/repositories/{repo_enc}/pullrequests/{pr_number}/threads?api-version=7.1'
+ url = f'{self._project_base_url(org, project)}/_apis/git/repositories/{repo_enc}/pullrequests/{pr_number}/threads?api-version=7.1'
response, _ = await self._make_request(url)
@@ -243,7 +226,6 @@ class AzureDevOpsPRsMixin(AzureDevOpsMixinBase):
project = parts[1]
repo = parts[2]
- # URL-encode components to handle spaces and special characters
org_enc = self._encode_url_component(org)
project_enc = self._encode_url_component(project)
repo_enc = self._encode_url_component(repo)
@@ -282,12 +264,9 @@ class AzureDevOpsPRsMixin(AzureDevOpsMixinBase):
"""
org, project, repo = self._parse_repository(repository)
- # URL-encode components to handle spaces and special characters
- org_enc = self._encode_url_component(org)
- project_enc = self._encode_url_component(project)
repo_enc = self._encode_url_component(repo)
- url = f'{self.base_url}/{org_enc}/{project_enc}/_apis/git/repositories/{repo_enc}/pullrequests/{pr_number}?api-version=7.1'
+ url = f'{self._project_base_url(org, project)}/_apis/git/repositories/{repo_enc}/pullrequests/{pr_number}?api-version=7.1'
response, _ = await self._make_request(url)
return response
diff --git a/openhands/app_server/integrations/azure_devops/service/resolver.py b/openhands/app_server/integrations/azure_devops/service/resolver.py
index 1bcfec6ff3..99cad98132 100644
--- a/openhands/app_server/integrations/azure_devops/service/resolver.py
+++ b/openhands/app_server/integrations/azure_devops/service/resolver.py
@@ -27,13 +27,12 @@ class AzureDevOpsResolverMixin(AzureDevOpsMixinBase):
org, project, repo = self._parse_repository(repository)
# URL-encode components to handle spaces and special characters
- org_enc = self._encode_url_component(org)
- project_enc = self._encode_url_component(project)
repo_enc = self._encode_url_component(repo)
+ project_base_url = self._project_base_url(org, project)
# Try to get as a pull request first
try:
- pr_url = f'{self.base_url}/{org_enc}/{project_enc}/_apis/git/repositories/{repo_enc}/pullrequests/{issue_number}?api-version=7.1'
+ pr_url = f'{project_base_url}/_apis/git/repositories/{repo_enc}/pullrequests/{issue_number}?api-version=7.1'
response, _ = await self._make_request(pr_url)
title = response.get('title') or ''
body = response.get('description') or ''
@@ -43,7 +42,9 @@ class AzureDevOpsResolverMixin(AzureDevOpsMixinBase):
# Fall back to work item
try:
- wi_url = f'{self.base_url}/{org_enc}/{project_enc}/_apis/wit/workitems/{issue_number}?api-version=7.1'
+ wi_url = (
+ f'{project_base_url}/_apis/wit/workitems/{issue_number}?api-version=7.1'
+ )
response, _ = await self._make_request(wi_url)
fields = response.get('fields', {})
title = fields.get('System.Title') or ''
@@ -73,7 +74,8 @@ class AzureDevOpsResolverMixin(AzureDevOpsMixinBase):
comments = await self.get_pr_comments( # type: ignore[attr-defined]
repository, issue_number, max_comments
)
- if comments:
+ # Empty list is a valid result (PR with no comments), not a miss.
+ if comments is not None:
return comments
except Exception as pr_error:
logger.debug(f'Failed to get PR comments: {pr_error}, trying work item')
@@ -111,11 +113,9 @@ class AzureDevOpsResolverMixin(AzureDevOpsMixinBase):
org, project, repo = self._parse_repository(repository)
# URL-encode components to handle spaces and special characters
- org_enc = self._encode_url_component(org)
- project_enc = self._encode_url_component(project)
repo_enc = self._encode_url_component(repo)
- url = f'{self.base_url}/{org_enc}/{project_enc}/_apis/git/repositories/{repo_enc}/pullrequests/{pr_number}/threads/{thread_id}?api-version=7.1'
+ url = f'{self._project_base_url(org, project)}/_apis/git/repositories/{repo_enc}/pullrequests/{pr_number}/threads/{thread_id}?api-version=7.1'
try:
response, _ = await self._make_request(url)
diff --git a/openhands/app_server/integrations/azure_devops/service/webhooks.py b/openhands/app_server/integrations/azure_devops/service/webhooks.py
new file mode 100644
index 0000000000..cec5603370
--- /dev/null
+++ b/openhands/app_server/integrations/azure_devops/service/webhooks.py
@@ -0,0 +1,96 @@
+"""Service hook operations for Azure DevOps integration."""
+
+from typing import Any
+
+from openhands.app_server.integrations.azure_devops.service.base import (
+ AzureDevOpsMixinBase,
+)
+from openhands.app_server.integrations.service_types import RequestMethod
+
+AZURE_DEVOPS_PR_COMMENT_EVENT = 'ms.vss-code.git-pullrequest-comment-event'
+AZURE_DEVOPS_WORK_ITEM_COMMENT_EVENT = 'workitem.commented'
+AZURE_DEVOPS_WEBHOOK_RESOURCE_VERSION = {
+ AZURE_DEVOPS_PR_COMMENT_EVENT: '2.0',
+ AZURE_DEVOPS_WORK_ITEM_COMMENT_EVENT: '1.0',
+}
+AZURE_DEVOPS_SERVICE_HOOK_API_VERSION = '7.1'
+
+
+class AzureDevOpsWebhooksMixin(AzureDevOpsMixinBase):
+ """Mixin for Azure DevOps Service Hooks operations."""
+
+ async def list_service_hook_subscriptions(self) -> list[dict[str, Any]]:
+ url = (
+ f'{self.base_url}/_apis/hooks/subscriptions'
+ f'?api-version={AZURE_DEVOPS_SERVICE_HOOK_API_VERSION}'
+ )
+ response, _ = await self._make_request(url)
+ return response.get('value', [])
+
+ async def create_pr_comment_service_hook(
+ self,
+ *,
+ webhook_url: str,
+ webhook_secret: str,
+ ) -> dict[str, Any]:
+ # Empty publisherInputs = no project filter, so it covers the whole org.
+ return await self._create_service_hook_subscription(
+ event_type=AZURE_DEVOPS_PR_COMMENT_EVENT,
+ publisher_inputs={},
+ webhook_url=webhook_url,
+ webhook_secret=webhook_secret,
+ )
+
+ async def create_work_item_comment_service_hook(
+ self,
+ *,
+ webhook_url: str,
+ webhook_secret: str,
+ ) -> dict[str, Any]:
+ # Empty publisherInputs = no project filter, so it covers the whole org.
+ return await self._create_service_hook_subscription(
+ event_type=AZURE_DEVOPS_WORK_ITEM_COMMENT_EVENT,
+ publisher_inputs={},
+ webhook_url=webhook_url,
+ webhook_secret=webhook_secret,
+ )
+
+ async def _create_service_hook_subscription(
+ self,
+ *,
+ event_type: str,
+ publisher_inputs: dict[str, str],
+ webhook_url: str,
+ webhook_secret: str,
+ ) -> dict[str, Any]:
+ url = (
+ f'{self.base_url}/_apis/hooks/subscriptions'
+ f'?api-version={AZURE_DEVOPS_SERVICE_HOOK_API_VERSION}'
+ )
+ payload = {
+ 'publisherId': 'tfs',
+ 'eventType': event_type,
+ 'resourceVersion': AZURE_DEVOPS_WEBHOOK_RESOURCE_VERSION[event_type],
+ 'consumerId': 'webHooks',
+ 'consumerActionId': 'httpRequest',
+ 'publisherInputs': publisher_inputs,
+ 'consumerInputs': {
+ 'url': webhook_url,
+ 'basicAuthUsername': 'openhands',
+ 'basicAuthPassword': webhook_secret,
+ 'resourceDetailsToSend': 'all',
+ 'messagesToSend': 'all',
+ 'detailedMessagesToSend': 'all',
+ },
+ }
+ response, _ = await self._make_request(
+ url=url, params=payload, method=RequestMethod.POST
+ )
+ return response
+
+ async def delete_service_hook_subscription(self, subscription_id: str) -> None:
+ url = (
+ f'{self.base_url}/_apis/hooks/subscriptions/{subscription_id}'
+ f'?api-version={AZURE_DEVOPS_SERVICE_HOOK_API_VERSION}'
+ )
+ await self._make_request(url=url, method=RequestMethod.DELETE)
diff --git a/openhands/app_server/integrations/azure_devops/service/work_items.py b/openhands/app_server/integrations/azure_devops/service/work_items.py
index 476f5f8aa7..435808fee6 100644
--- a/openhands/app_server/integrations/azure_devops/service/work_items.py
+++ b/openhands/app_server/integrations/azure_devops/service/work_items.py
@@ -16,12 +16,6 @@ class AzureDevOpsWorkItemsMixin(AzureDevOpsMixinBase):
in Azure Boards. This mixin provides methods to interact with work item comments.
"""
- def _truncate_comment(self, comment: str, max_length: int = 1000) -> str:
- """Truncate comment to max length."""
- if len(comment) <= max_length:
- return comment
- return comment[:max_length] + '...'
-
async def add_work_item_comment(
self, repository: str, work_item_id: int, comment_text: str
) -> dict:
@@ -43,10 +37,7 @@ class AzureDevOpsWorkItemsMixin(AzureDevOpsMixinBase):
org, project, _ = self._parse_repository(repository)
# URL-encode components to handle spaces and special characters
- org_enc = self._encode_url_component(org)
- project_enc = self._encode_url_component(project)
-
- url = f'{self.base_url}/{org_enc}/{project_enc}/_apis/wit/workItems/{work_item_id}/comments?api-version=7.1-preview.4'
+ url = f'{self._project_base_url(org, project)}/_apis/wit/workItems/{work_item_id}/comments?api-version=7.1-preview.4'
payload = {
'text': comment_text,
@@ -59,6 +50,19 @@ class AzureDevOpsWorkItemsMixin(AzureDevOpsMixinBase):
logger.info(f'Added comment to work item {work_item_id} in project {project}')
return response
+ async def get_work_item_title_and_body(self, work_item_id: int) -> tuple[str, str]:
+ """Get a work item's title and description as plain text.
+
+ Work item IDs are unique per org, so this queries at the org level.
+ """
+ url = (
+ f'{self.base_url}/_apis/wit/workitems/{work_item_id}'
+ '?fields=System.Title,System.Description&api-version=7.1'
+ )
+ response, _ = await self._make_request(url)
+ fields = response.get('fields') or {}
+ return fields.get('System.Title') or '', fields.get('System.Description') or ''
+
async def get_work_item_comments(
self, repository: str, work_item_id: int, max_comments: int = 100
) -> list[Comment]:
@@ -77,10 +81,7 @@ class AzureDevOpsWorkItemsMixin(AzureDevOpsMixinBase):
org, project, _ = self._parse_repository(repository)
# URL-encode components to handle spaces and special characters
- org_enc = self._encode_url_component(org)
- project_enc = self._encode_url_component(project)
-
- url = f'{self.base_url}/{org_enc}/{project_enc}/_apis/wit/workItems/{work_item_id}/comments?api-version=7.1-preview.4'
+ url = f'{self._project_base_url(org, project)}/_apis/wit/workItems/{work_item_id}/comments?api-version=7.1-preview.4'
response, _ = await self._make_request(url)