π OpenHands: AI-Driven Development
fix(jira-dc): more forgiving repo + mention resolution for Data Center (#15034)
Alona9a16d2750388
diff --git a/enterprise/integrations/jira_dc/jira_dc_manager.py b/enterprise/integrations/jira_dc/jira_dc_manager.pyindex 901ba11eb3..10e55c8f2d 100644--- a/enterprise/integrations/jira_dc/jira_dc_manager.py+++ b/enterprise/integrations/jira_dc/jira_dc_manager.py@@ -1,5 +1,6 @@import hashlibimport hmac+import refrom typing import Dict, Optional, Tuplefrom urllib.parse import urlparse@@ -19,10 +20,12 @@ from integrations.jira_dc.jira_dc_view import (from integrations.manager import Managerfrom integrations.models import JobContext, Messagefrom integrations.utils import (+ HOST,HOST_URL,OPENHANDS_RESOLVER_TEMPLATES_DIR,get_account_not_linked_message,get_jira_dc_relink_message,+ get_oh_labels,get_session_expired_message,get_user_not_found_message,has_exact_mention,@@ -48,6 +51,10 @@ from openhands.app_server.user_auth.user_auth import UserAuthfrom openhands.app_server.utils.http_session import httpx_verify_optionfrom openhands.app_server.utils.logger import openhands_logger as logger+# Trigger macro (label + @mention), configurable per deployment via+# OH_RESOLVER_LABEL / host inference -- matches the other integrations.+OH_LABEL, INLINE_OH_LABEL = get_oh_labels(HOST)+# Unicode codepoint of the emoji reaction posted to acknowledge an @openhands# mention via Jira's internal reactions API. 1f44d = π (thumbs up). Note:# 1f440 (π eyes) is NOT in Jira DC's reaction palette, so thumbs-up is used.@@ -66,6 +73,12 @@ JIRA_DC_WEBHOOK_EVENTS = ['comment_deleted',]+# A Jira [~id] / [~accountid:id] mention token; captures the inner identifier.+# {1,256} bounds the run so a long '[~[~...' body can't cause O(n^2) backtracking.+_JIRA_MENTION_RE = re.compile(+ r'\[~\s*(?:accountid:)?\s*([^\]\s]{1,256})\s*\]', re.IGNORECASE+)+def _extract_workspace_url(payload: Dict) -> str:"""Return a Jira URL whose host identifies the configured workspace."""@@ -106,19 +119,22 @@ def _extract_workspace_hosts(payload: Dict) -> set[str]:}-def _comment_addresses_openhands(comment: str, bot_mentions: set[str] | None) -> bool:- # Literal @openhands always triggers (works even when the bot username can't+def _comment_addresses_openhands(comment: str, bot_ids: set[str] | None) -> bool:+ # Literal @openhands always triggers (works even when the bot identity can't# be resolved). Jira's mention picker serializes a real mention as wiki- # markup [~name]/[~key], so match those too once resolved.+ # markup [~name]/[~key]/[~accountid:key]; match any token whose inner id is+ # the bot, so we don't depend on which exact form the instance emits.if not comment:return False# Boundary-aware + case-insensitive: matches @OpenHands but not an email like# [email protected] (incl. the service account's own address).- if has_exact_mention(comment, '@openhands'):+ if has_exact_mention(comment, INLINE_OH_LABEL):return True- if bot_mentions:- lowered = comment.lower()- return any(token in lowered for token in bot_mentions)+ if bot_ids:+ return any(+ m.group(1).strip().lower() in bot_ids+ for m in _JIRA_MENTION_RE.finditer(comment)+ )return False@@ -129,8 +145,8 @@ class JiraDcManager(Manager[JiraDcViewInterface]):self.jinja_env = Environment(loader=FileSystemLoader(OPENHANDS_RESOLVER_TEMPLATES_DIR + 'jira_dc'))- # Bot mention tokens ([~name]/[~key]/...) per workspace.id, resolved- # lazily from /myself for matching picker mentions.+ # Bot identifiers (username + Jira key) per workspace.id, resolved lazily+ # from /myself for matching picker mentions.self._svc_mentions_cache: dict[int, set[str]] = {}async def authenticate_user(@@ -216,7 +232,9 @@ class JiraDcManager(Manager[JiraDcViewInterface]):repo_name, is_optional=True)except Exception as e:- logger.debug(f'[Jira DC] Repo verification failed for {repo_name}: {e}')+ # INFO (not DEBUG) so the reason is visible in support bundles;+ # e carries the provider error incl. the attempted URL + status.+ logger.info(f'[Jira DC] Repo verification failed for {repo_name}: {e}')continueverified.setdefault(repo.full_name.lower(), repo)return list(verified.values())@@ -323,7 +341,7 @@ class JiraDcManager(Manager[JiraDcViewInterface]):if item.get('field') == 'labels' and 'toString' in item]- if 'openhands' not in labels:+ if OH_LABEL not in labels:return Noneissue_data = payload.get('issue', {})@@ -378,7 +396,26 @@ class JiraDcManager(Manager[JiraDcViewInterface]):job_context = self.parse_webhook(payload, bot_mentions)if not job_context:- logger.info('[Jira DC] Webhook does not match trigger conditions')+ # Log the body only for a non-matching comment that references the+ # bot itself (name 'openhands' or a resolved bot id) -- the FDE-84+ # "mention didn't fire" case. Skips unrelated comments / mentions of+ # other users on this instance-wide webhook. Truncated since bodies+ # can hold sensitive content.+ comment = (payload.get('comment') or {}).get('body', '') or ''+ lowered = comment.lower()+ refs_bot = OH_LABEL in lowered or any(+ i in lowered for i in (bot_mentions or ())+ )+ if payload.get('webhookEvent') == 'comment_created' and refs_bot:+ logger.info(+ '[Jira DC] comment references the bot but did not trigger '+ '(bot_ids_resolved=%s mention_tokens=%s) body=%r',+ bool(bot_mentions),+ _JIRA_MENTION_RE.findall(comment),+ comment[:500],+ )+ else:+ logger.info('[Jira DC] Webhook does not match trigger conditions')returnworkspace = await self.integration_store.get_workspace_by_name(@@ -507,6 +544,15 @@ class JiraDcManager(Manager[JiraDcViewInterface]):else [])+ # One INFO line that separates a parse miss (inferred=[]) from a+ # lookup miss (inferred set, verified=[]) in support bundles.+ logger.info(+ '[Jira DC] repo resolution issue=%s inferred=%s verified=%s',+ jira_dc_view.job_context.issue_key,+ mentioned_repos,+ [r.full_name for r in verified_repos],+ )+if len(verified_repos) == 1:jira_dc_view.selected_repo = verified_repos[0].full_namelogger.info(@@ -583,15 +629,16 @@ class JiraDcManager(Manager[JiraDcViewInterface]):logger.error(f'[Jira] Failed to send response message: {str(e)}')async def _resolve_service_account_mentions(self, payload: Dict) -> set[str] | None:- """Best-effort bot mention tokens ([~name]/[~key]) for a picker mention.+ """Best-effort bot identifiers (username + Jira key) for a picker mention.- Gated so only wiki-markup mentions pay a lookup; literal @openhands and- non-comment payloads short-circuit. Cached per workspace; failures are not- cached, so a later comment re-attempts resolution (this event is dropped,- not retried).+ Returns the ids a [~...] token can carry; _comment_addresses_openhands+ matches a token's inner id against these. Gated so only wiki-markup+ mentions pay a lookup; literal @openhands and non-comment payloads+ short-circuit. Cached per workspace; failures are not cached, so a later+ comment re-attempts resolution (this event is dropped, not retried)."""comment = (payload.get('comment') or {}).get('body', '') or ''- if has_exact_mention(comment, '@openhands') or '[~' not in comment:+ if has_exact_mention(comment, INLINE_OH_LABEL) or '[~' not in comment:return Nonetry:base_api_url = (@@ -613,18 +660,12 @@ class JiraDcManager(Manager[JiraDcViewInterface]):name, key = await self._fetch_service_account_identity(base_api_url, service_account.api_key)- mentions = {- token.lower()- for token in (- f'[~{name}]' if name else None,- f'[~{key}]' if key else None,- f'[~accountid:{key}]' if key else None,- )- if token- }- if mentions:- self._svc_mentions_cache[workspace.id] = mentions- return mentions or None+ # Identifiers a [~...] token may carry (username or Jira key), so we+ # match regardless of which form this instance/version emits.+ ids = {v.lower() for v in (name, key) if v}+ if ids:+ self._svc_mentions_cache[workspace.id] = ids+ return ids or Noneexcept Exception as e:logger.warning(f'[Jira DC] Could not resolve bot mentions: {str(e)}')return None@@ -982,8 +1023,8 @@ class JiraDcManager(Manager[JiraDcViewInterface]):if not mentioned_repos:comment_msg = ('Could not determine which repository to use. '- 'Please mention the repository (e.g., owner/repo) in the issue '- 'description or comment.'+ 'Please mention the repository (e.g., owner/repo or a '+ 'repository URL) in the issue description or comment.')elif len(matched_repo_names) > 1:comment_msg = (@@ -995,8 +1036,8 @@ class JiraDcManager(Manager[JiraDcViewInterface]):comment_msg = (f'Could not access any of the mentioned repositories: 'f'{", ".join(mentioned_repos)}. '- 'Please ensure your OpenHands account has access to the '- 'repository and it exists.'+ 'Please ensure the repository exists and that the Git account '+ 'linked to your OpenHands user can access it.')service_account = resolve_jira_dc_service_account(diff --git a/enterprise/integrations/jira_dc/jira_dc_view.py b/enterprise/integrations/jira_dc/jira_dc_view.pyindex b0a3ce5015..7fd8c1a109 100644--- a/enterprise/integrations/jira_dc/jira_dc_view.py+++ b/enterprise/integrations/jira_dc/jira_dc_view.py@@ -209,7 +209,13 @@ class JiraDcNewConversationView(JiraDcViewInterface):def get_response_msg(self) -> str:"""Get the response message to send back to Jira DC."""conversation_link = CONVERSATION_URL.format(self.conversation_id)- return f"I'm on it! {self.job_context.display_name} can [track my progress here|{conversation_link}]."+ # Name the resolved repo so the user can confirm we picked the right one.+ prefix = (+ f"I'm on it in {self.selected_repo}!"+ if self.selected_repo+ else "I'm on it!"+ )+ return f'{prefix} {self.job_context.display_name} can [track my progress here|{conversation_link}].'@dataclassdiff --git a/enterprise/integrations/utils.py b/enterprise/integrations/utils.pyindex 560dd2cd9c..70498c6d43 100644--- a/enterprise/integrations/utils.py+++ b/enterprise/integrations/utils.py@@ -192,10 +192,12 @@ def infer_repo_from_message(user_msg: str) -> list[str]:r'https?://[a-zA-Z0-9.-]+(?::\d+)?/(?:projects|users)/'r'([a-zA-Z0-9_~.-]+)/repos/([a-zA-Z0-9_.-]+)')- # Bitbucket Data Center clone URLs: /scm/<KEY>/<slug>(.git).+ # Bitbucket Data Center clone URLs: /scm/<KEY>/<slug>(.git). Boundary is any+ # non-slug char (not just /?#space) so a URL wrapped in Jira/markdown link+ # markup -- [url] or [text|url] -- still terminates cleanly on ] or |.bitbucket_dc_scm_pattern = (r'https?://[a-zA-Z0-9.-]+(?::\d+)?/scm/'- r'([a-zA-Z0-9_~.-]+)/([a-zA-Z0-9_.-]+?)(?:\.git)?(?=[/?#\s]|$)'+ r'([a-zA-Z0-9_~.-]+)/([a-zA-Z0-9_.-]+?)(?:\.git)?(?=[^a-zA-Z0-9_.~-]|$)')# Generic Git host (cloud or self-hosted): github.com, a GitHub Enterprise@@ -208,30 +210,37 @@ def infer_repo_from_message(user_msg: str) -> list[str]:r'(?:[/?#].*?)?(?=\s|$|[^\w.-])')- # UPDATED: allow {{ owner/repo }} in addition to existing boundaries+ # Direct 'owner/repo' mention. Right boundary also accepts ? ! ; and the+ # Jira link pipe |, so a trailing question mark or a wiki-link wrapper does+ # not drop an otherwise-valid mention. ({{ owner/repo }} stays supported.)direct_pattern = (r'(?:^|\s|{{|[\[\(\'":`])' # left boundaryr'([a-zA-Z0-9_.-]+)/([a-zA-Z0-9_.-]+)'- r'(?=\s|$|}}|[\]\)\'",.:`])' # right boundary+ r'(?=\s|$|}}|[\]\)\'",.:;!?`|])' # right boundary)+ def _clean(repo: str) -> str:+ # Greedy captures keep trailing punctuation / .git; strip both.+ return re.sub(r'\.git$', '', repo.rstrip('.,;:!?'))+# Use dict to preserve orderingmatches: dict[str, bool] = {}# Bitbucket Data Center URLs first (most specific layout)for owner, repo in re.findall(bitbucket_dc_web_pattern, normalized_msg):- matches[f'{owner}/{repo}'] = True+ matches[f'{owner}/{_clean(repo)}'] = Truefor owner, repo in re.findall(bitbucket_dc_scm_pattern, normalized_msg):- repo = re.sub(r'\.git$', '', repo)- matches[f'{owner}/{repo}'] = True+ matches[f'{owner}/{_clean(repo)}'] = True# Generic Git URLs next (highest priority among the standard layout)for owner, repo in re.findall(git_url_pattern, normalized_msg):- repo = re.sub(r'\.git$', '', repo)- matches[f'{owner}/{repo}'] = True+ matches[f'{owner}/{_clean(repo)}'] = True# Direct mentionsfor owner, repo in re.findall(direct_pattern, normalized_msg):+ repo = _clean(repo)+ if not repo:+ continuefull_match = f'{owner}/{repo}'if (@@ -303,10 +312,54 @@ def markdown_to_jira_markup(markdown_text: str) -> str:text = re.sub(r'^#{2}\s+(.*?)$', r'h2. \1', text, flags=re.MULTILINE)text = re.sub(r'^#{1}\s+(.*?)$', r'h1. \1', text, flags=re.MULTILINE)- # Convert code blocks first (before other formatting)- text = re.sub(- r'```(\w+)\n(.*?)\n```', r'{code:\1}\n\2\n{code}', text, flags=re.DOTALL- )+ # Convert code blocks first (before other formatting). Jira's {code}+ # macro only supports a fixed language set; fall back to a plain {code}+ # for anything else (e.g. ```text) so Jira doesn't show a "no+ # source-code formatter for language: X" warning.+ jira_code_langs = {+ 'actionscript',+ 'ada',+ 'applescript',+ 'bash',+ 'c',+ 'c#',+ 'c++',+ 'cpp',+ 'css',+ 'erlang',+ 'go',+ 'groovy',+ 'haskell',+ 'html',+ 'java',+ 'javascript',+ 'js',+ 'json',+ 'lua',+ 'none',+ 'nyan',+ 'objc',+ 'perl',+ 'php',+ 'python',+ 'r',+ 'rainbow',+ 'ruby',+ 'scala',+ 'sh',+ 'sql',+ 'swift',+ 'visualbasic',+ 'xml',+ 'yaml',+ }++ def _code_block(m):+ lang = m.group(1).lower()+ header = f'{{code:{lang}}}' if lang in jira_code_langs else '{code}'+ return f'{header}\n{m.group(2)}\n{{code}}'++ text = re.sub(r'```(\w+)\n(.*?)\n```', _code_block, text, flags=re.DOTALL)text = re.sub(r'```\n(.*?)\n```', r'{code}\n\1\n{code}', text, flags=re.DOTALL)# Convert inline code (`code`)diff --git a/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_manager.py b/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_manager.pyindex dbaaeb2a13..f410efe36d 100644--- a/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_manager.py+++ b/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_manager.py@@ -589,9 +589,8 @@ class TestResolveServiceAccountMentions:first = await jira_dc_manager._resolve_service_account_mentions(payload)second = await jira_dc_manager._resolve_service_account_mentions(payload)- assert '[~openhands]' in first- assert '[~jirauser1]' in first- assert '[~accountid:jirauser1]' in first+ # Returns the bot identifiers (username + Jira key), not [~...] tokens.+ assert first == {'openhands', 'jirauser1'}assert jira_dc_manager._svc_mentions_cache[1] == first# Second call served from cache -> only one /myself fetch.mock_client.get.assert_awaited_once()@@ -674,27 +673,31 @@ class TestParseWebhook:assert jira_dc_manager.parse_webhook(payload, bot_mentions=None) is not Nonedef test_parse_webhook_wiki_mention_triggers(self, jira_dc_manager):- """A picker mention [~name] triggers once the bot mentions are known."""+ """A picker mention [~name] triggers once the bot ids are known."""payload = _jdc_comment_payload('cc [~openhands] please review')- result = jira_dc_manager.parse_webhook(payload, bot_mentions={'[~openhands]'})+ result = jira_dc_manager.parse_webhook(payload, bot_mentions={'openhands'})assert result is not Nonedef test_parse_webhook_wiki_mention_case_insensitive(self, jira_dc_manager):payload = _jdc_comment_payload('cc [~OpenHands]')- result = jira_dc_manager.parse_webhook(payload, bot_mentions={'[~openhands]'})+ result = jira_dc_manager.parse_webhook(payload, bot_mentions={'openhands'})assert result is not Nonedef test_parse_webhook_wiki_mention_by_key(self, jira_dc_manager):"""The bot's Jira key form ([~JIRAUSER...]) also triggers."""payload = _jdc_comment_payload('cc [~jirauser173929] please')- result = jira_dc_manager.parse_webhook(- payload, bot_mentions={'[~jirauser173929]'}- )+ result = jira_dc_manager.parse_webhook(payload, bot_mentions={'jirauser173929'})+ assert result is not None++ def test_parse_webhook_wiki_mention_accountid_form(self, jira_dc_manager):+ """The Cloud-style [~accountid:<key>] wrapper also triggers."""+ payload = _jdc_comment_payload('cc [~accountid:JIRAUSER173929] please')+ result = jira_dc_manager.parse_webhook(payload, bot_mentions={'jirauser173929'})assert result is not Nonedef test_parse_webhook_wiki_mention_other_user_no_trigger(self, jira_dc_manager):payload = _jdc_comment_payload('cc [~someoneelse] review')- result = jira_dc_manager.parse_webhook(payload, bot_mentions={'[~openhands]'})+ result = jira_dc_manager.parse_webhook(payload, bot_mentions={'openhands'})assert result is Nonedef test_parse_webhook_wiki_mention_dropped_when_unresolved(self, jira_dc_manager):@@ -1729,7 +1732,7 @@ class TestSendRepoSelectionComment:'Could not access any of the mentioned repositories: company/repo'in call_args[0])- assert 'OpenHands account has access' in call_args[0]+ assert 'Git account linked to your OpenHands user can access it' in call_args[0]@pytest.mark.asyncioasync def test_send_repo_selection_comment_send_fails(diff --git a/enterprise/tests/unit/test_utils.py b/enterprise/tests/unit/test_utils.pyindex 5a7c69fa1e..d97b7e2c15 100644--- a/enterprise/tests/unit/test_utils.py+++ b/enterprise/tests/unit/test_utils.py@@ -55,6 +55,10 @@ def test_markdown_to_jira_markup():('# Header', 'h1. Header'),('`code`', '{{code}}'),('```python\ncode\n```', '{code:python}\ncode\n{code}'),+ # Unsupported languages (e.g. text) fall back to a plain {code} block so+ # Jira doesn't warn "no source-code formatter for language: text".+ ('```text\nplain\n```', '{code}\nplain\n{code}'),+ ('```TEXT\nx\n```', '{code}\nx\n{code}'),('[link](url)', '[link|url]'),('- item', '* item'),('1. item', '# item'),@@ -187,6 +191,23 @@ def test_infer_repo_from_message():),('https://bitbucket.mycorp.com/scm/~jdoe/tool.git', ['~jdoe/tool']),('https://git.internal:7990/scm/TEAM/app.git', ['TEAM/app']),+ # FDE-86 (1finity): trailing punctuation must not drop a mention, and a+ # Jira/markdown link-wrapped clone URL must still resolve.+ ('Is this merged into PF/meta-fnos-pf?', ['PF/meta-fnos-pf']),+ ('Please look at acme/widgets!', ['acme/widgets']),+ ('Check acme/widgets; thanks', ['acme/widgets']),+ ('The fix is in acme/widgets.', ['acme/widgets']),+ (+ 'merged into [https://bitbucket.fnc.fujitsu.com/scm/pf/meta-fnos-pf.git] ?',+ ['pf/meta-fnos-pf'],+ ),+ (+ 'see [https://bitbucket.fnc.fujitsu.com/scm/pf/meta-fnos-pf.git|'+ 'https://bitbucket.fnc.fujitsu.com/scm/pf/meta-fnos-pf.git]',+ ['pf/meta-fnos-pf'],+ ),+ # Trailing dot must not leak a date as a repo.+ ('It is due on 1/2.', []),]for message, expected in test_cases:diff --git a/openhands/app_server/integrations/provider.py b/openhands/app_server/integrations/provider.pyindex 7c64c01afc..20f99ca55a 100644--- a/openhands/app_server/integrations/provider.py+++ b/openhands/app_server/integrations/provider.py@@ -449,7 +449,10 @@ class ProviderHandler:log_fn(f'Failed to access repository {repository}: Unknown error (no providers tried, no errors recorded)')- raise AuthenticationError(f'Unable to access repo {repository}')+ # Keep the underlying provider error(s) in the message so callers can+ # log why (e.g. 404 vs 401) instead of an opaque failure.+ detail = f': {"; ".join(errors)}' if errors else ''+ raise AuthenticationError(f'Unable to access repo {repository}{detail}')async def get_branches(self,