Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Include Bitbucket DC PR comments in resolver context

Alona2afe08c89658
diff --git a/enterprise/integrations/bitbucket_data_center/bitbucket_dc_view.py b/enterprise/integrations/bitbucket_data_center/bitbucket_dc_view.py
index c77b450fe0..9d87efa13c 100644
--- a/enterprise/integrations/bitbucket_data_center/bitbucket_dc_view.py
+++ b/enterprise/integrations/bitbucket_data_center/bitbucket_dc_view.py
@@ -92,7 +92,10 @@ class BitbucketDCPR(ResolverViewInterface):
external_auth_id=self.user_info.keycloak_user_id
)
self.previous_comments = await bitbucket_service.get_pr_comments(
- self.project_key, self.repo_slug, self.issue_number
+ self.project_key,
+ self.repo_slug,
+ self.issue_number,
+ exclude_comment_id=getattr(self, 'comment_id', None),
)
(
self.title,
@@ -163,7 +166,7 @@ class BitbucketDCPR(ResolverViewInterface):
title = f'Bitbucket DC PR #{self.issue_number}: {self.title}'
start_request = AppConversationStartRequest(
conversation_id=conversation_id,
- system_message_suffix=conversation_instructions,
+ system_message_suffix=conversation_instructions or None,
initial_message=initial_message,
selected_repository=self.full_repo_name,
selected_branch=self._get_branch_name(),
@@ -195,28 +198,25 @@ class BitbucketDCPR(ResolverViewInterface):
@dataclass
class BitbucketDCPRComment(BitbucketDCPR):
+ comment_id: int | None
comment_body: str
parent_comment_id: int | None
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'
+ user_instructions_template = jinja_env.get_template(
+ 'pr_update_initial_message.j2'
)
- conversation_instructions = conversation_instructions_template.render(
+ user_instructions = user_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,
+ pr_comment=self.comment_body,
)
- return user_instructions, conversation_instructions
+ return user_instructions, ''
@dataclass
@@ -229,24 +229,20 @@ class BitbucketDCInlinePRComment(BitbucketDCPRComment):
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
+ user_instructions_template = jinja_env.get_template(
+ 'pr_update_initial_message.j2'
)
-
- conversation_instructions_template = jinja_env.get_template(
- 'pr_update_conversation_instructions.j2'
- )
- conversation_instructions = conversation_instructions_template.render(
+ user_instructions = user_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,
+ pr_comment=self.comment_body,
file_location=self.file_location,
line_number=self.line_number,
)
- return user_instructions, conversation_instructions
+ return user_instructions, ''
BitbucketDCViewType = BitbucketDCInlinePRComment | BitbucketDCPRComment | BitbucketDCPR
@@ -339,6 +335,7 @@ class BitbucketDCFactory:
)
comment = payload.get('comment') or {}
+ comment_id = comment.get('id')
comment_body = comment.get('text') or ''
parent_comment_id = (comment.get('parent') or {}).get('id')
@@ -372,6 +369,7 @@ class BitbucketDCFactory:
)
return BitbucketDCInlinePRComment(
**common_kwargs,
+ comment_id=comment_id,
comment_body=comment_body,
parent_comment_id=parent_comment_id,
file_location=anchor.get('path') or '',
@@ -387,6 +385,7 @@ class BitbucketDCFactory:
)
return BitbucketDCPRComment(
**common_kwargs,
+ comment_id=comment_id,
comment_body=comment_body,
parent_comment_id=parent_comment_id,
)
diff --git a/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_manager.py b/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_manager.py
index eb20884249..c71d4d81c4 100644
--- a/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_manager.py
+++ b/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_manager.py
@@ -68,6 +68,7 @@ def _pr_comment_view(parent_id: int | None = 42) -> BitbucketDCPRComment:
previous_comments=[],
branch_name='feature/x',
installer_keycloak_user_id='kc-installer',
+ comment_id=99,
comment_body='Hey @openhands fix',
parent_comment_id=parent_id,
)
@@ -93,6 +94,7 @@ def _inline_view() -> BitbucketDCInlinePRComment:
previous_comments=[],
branch_name='feature/x',
installer_keycloak_user_id='kc-installer',
+ comment_id=99,
comment_body='@openhands rename',
parent_comment_id=None,
file_location='src/x.py',
@@ -104,9 +106,11 @@ def _inline_view() -> BitbucketDCInlinePRComment:
@pytest.mark.asyncio
async def test_receive_message_runs_job_as_mentioner_when_linked_in_keycloak():
- """When the @-mentioning user has an OHE account, the view's
- ``user_info.keycloak_user_id`` is the mentioner and the installer's
- id is carried alongside on ``installer_keycloak_user_id``.
+ """Use the linked mentioner as the resolver user.
+
+ When the @-mentioning user has an OHE account, the view's
+ ``user_info.keycloak_user_id`` is the mentioner and the installer's id is
+ carried alongside on ``installer_keycloak_user_id``.
"""
token_manager = AsyncMock()
token_manager.get_user_id_from_idp_user_id = AsyncMock(return_value='kc-alice')
@@ -138,9 +142,11 @@ async def test_receive_message_runs_job_as_mentioner_when_linked_in_keycloak():
@pytest.mark.asyncio
async def test_receive_message_asks_unenrolled_mentioner_to_sign_up():
- """A mentioner with no OHE account is NOT run as the installer. We mirror
- the GitHub manager: refuse the job and reply asking them to sign up, so
- every job runs as (and is billed to) the actual requester.
+ """Ask unenrolled mentioners to sign up.
+
+ A mentioner with no OHE account is not run as the installer. We mirror the
+ GitHub manager: refuse the job and reply asking them to sign up, so every
+ job runs as (and is billed to) the actual requester.
"""
token_manager = AsyncMock()
token_manager.get_user_id_from_idp_user_id = AsyncMock(return_value=None)
@@ -164,9 +170,11 @@ async def test_receive_message_asks_unenrolled_mentioner_to_sign_up():
@pytest.mark.asyncio
async def test_receive_message_drops_event_when_keycloak_lookup_raises():
- """A transient Keycloak error leaves enrollment status unknown. We drop
- the event rather than guess β€” neither silently running as the installer
- nor wrongly telling a (possibly enrolled) user to sign up.
+ """Drop events when mentioner lookup fails.
+
+ A transient Keycloak error leaves enrollment status unknown. We drop the
+ event rather than guess: neither silently running as the installer nor
+ wrongly telling a possibly enrolled user to sign up.
"""
token_manager = AsyncMock()
token_manager.get_user_id_from_idp_user_id = AsyncMock(
@@ -189,7 +197,9 @@ async def test_receive_message_drops_event_when_keycloak_lookup_raises():
@pytest.mark.asyncio
async def test_send_user_not_found_message_replies_as_installer():
- """The sign-up reply is built from the payload with the installer as the
+ """Post the sign-up reply as the installer.
+
+ The sign-up reply is built from the payload with the installer as the
posting identity and carries the user-not-found copy.
"""
manager = BitbucketDCManager(AsyncMock())
@@ -287,9 +297,11 @@ def test_confirm_incoming_source_type_raises_on_wrong_source():
@pytest.mark.asyncio
async def test_send_message_uses_view_user_info_keycloak_id():
- """send_message constructs the BBDC service with the view's
- user_info.keycloak_user_id (the mentioner) rather than the
- installer, so replies post under the mentioner's BBDC account.
+ """Post replies with the view user auth id.
+
+ send_message constructs the BBDC service with the view's
+ ``user_info.keycloak_user_id`` (the mentioner) rather than the installer,
+ so replies post under the mentioner's BBDC account.
"""
manager = BitbucketDCManager(AsyncMock())
@@ -303,8 +315,10 @@ async def test_send_message_uses_view_user_info_keycloak_id():
def test_posting_service_uses_bot_token_when_set():
- """With BITBUCKET_DATA_CENTER_BOT_TOKEN set, the posting service auths as
- the bot (token=...) and does NOT fall back to the per-user token.
+ """Use the bot token when it is configured.
+
+ With ``BITBUCKET_DATA_CENTER_BOT_TOKEN`` set, the posting service auths as
+ the bot and does not fall back to the per-user token.
"""
manager = BitbucketDCManager(AsyncMock())
@@ -325,8 +339,10 @@ def test_posting_service_uses_bot_token_when_set():
def test_posting_service_falls_back_to_user_token_when_bot_unset():
- """Without a bot token, the posting service uses the per-user/installer
- OAuth token (current behavior).
+ """Use the per-user token when no bot token is configured.
+
+ Without a bot token, the posting service uses the per-user/installer OAuth
+ token.
"""
manager = BitbucketDCManager(AsyncMock())
diff --git a/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_view.py b/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_view.py
index 66d27f15ce..18531138c5 100644
--- a/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_view.py
+++ b/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_view.py
@@ -1,5 +1,8 @@
"""Tests for the Bitbucket Data Center resolver factory and view dispatch."""
+from pathlib import Path
+from unittest.mock import AsyncMock, MagicMock
+
import pytest
from integrations.bitbucket_data_center.bitbucket_dc_view import (
BitbucketDCFactory,
@@ -7,6 +10,20 @@ from integrations.bitbucket_data_center.bitbucket_dc_view import (
BitbucketDCPRComment,
)
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/bitbucket'
+ )
+ )
+ )
def _make_message(
@@ -61,6 +78,7 @@ async def test_factory_creates_pr_comment_view_for_pr_comment_added_with_mention
assert isinstance(view, BitbucketDCPRComment)
assert not isinstance(view, BitbucketDCInlinePRComment)
+ assert view.comment_id == 99
assert view.parent_comment_id == 42
assert view.full_repo_name == 'PROJ/myrepo'
assert view.branch_name == 'feature/x'
@@ -83,6 +101,7 @@ async def test_factory_creates_inline_view_when_anchor_present():
)
assert isinstance(view, BitbucketDCInlinePRComment)
+ assert view.comment_id == 99
assert view.file_location == 'src/x.py'
assert view.line_number == 12
assert view.line_type == 'ADDED'
@@ -117,9 +136,10 @@ async def test_factory_records_actor_slug_and_assigns_keycloak_user_id():
@pytest.mark.asyncio
async def test_factory_keeps_mentioner_and_installer_distinct_when_passed():
- """The mentioner runs the job; the installer's id is carried alongside
- on ``installer_keycloak_user_id`` for the bits that need elevated
- permissions (permission check, webhook lifecycle).
+ """Keep the mentioner and installer identities distinct.
+
+ The mentioner runs the job; the installer's id is carried alongside on
+ ``installer_keycloak_user_id`` for the bits that need elevated permissions.
"""
msg = _make_message(body='@openhands fix')
@@ -131,3 +151,33 @@ async def test_factory_keeps_mentioner_and_installer_distinct_when_passed():
assert view.user_info.keycloak_user_id == 'kc-alice'
assert view.installer_keycloak_user_id == 'kc-installer'
+
+
+async def test_pr_comment_instructions_include_context_and_actionable_comment(
+ jinja_env,
+):
+ msg = _make_message(body='@openhands please update the tests')
+ view = await BitbucketDCFactory.create_bitbucket_dc_view_from_payload(
+ msg, 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='old thread')
+ ]
+
+ view._load_resolver_context = AsyncMock(side_effect=_load_context) # type: ignore[method-assign]
+
+ user_instructions, conversation_instructions = await view._get_instructions(
+ jinja_env
+ )
+
+ assert conversation_instructions == ''
+ assert 'PR title' in user_instructions
+ assert 'PR body' in user_instructions
+ assert '@openhands please update the tests' in user_instructions
+ assert 'old thread' in user_instructions
+ assert 'The comment above is the actionable request' in user_instructions
diff --git a/openhands/app_server/integrations/bitbucket_data_center/service/resolver.py b/openhands/app_server/integrations/bitbucket_data_center/service/resolver.py
index 4bfd6a29a8..ce6bab28dc 100644
--- a/openhands/app_server/integrations/bitbucket_data_center/service/resolver.py
+++ b/openhands/app_server/integrations/bitbucket_data_center/service/resolver.py
@@ -33,7 +33,12 @@ class BitbucketDCResolverMixin(BitbucketDCMixinBase):
return title, body
async def get_pr_comments(
- self, owner: str, repo_slug: str, pr_id: int, max_comments: int = 10
+ self,
+ owner: str,
+ repo_slug: str,
+ pr_id: int,
+ max_comments: int = 10,
+ exclude_comment_id: int | str | None = None,
) -> list[Comment]:
"""Get comments for a pull request.
@@ -45,6 +50,8 @@ class BitbucketDCResolverMixin(BitbucketDCMixinBase):
repo_slug: Repository slug
pr_id: Pull request ID
max_comments: Maximum number of comments to retrieve
+ exclude_comment_id: Comment id to omit from the returned context,
+ usually the triggering @openhands comment.
Returns:
List of Comment objects ordered by creation date
@@ -69,14 +76,22 @@ class BitbucketDCResolverMixin(BitbucketDCMixinBase):
break
params = {'limit': 100, 'start': next_start}
- return self._process_raw_comments(all_raw, max_comments)
+ return self._process_raw_comments(all_raw, max_comments, exclude_comment_id)
def _process_raw_comments(
- self, comments: list, max_comments: int = 10
+ self,
+ comments: list,
+ max_comments: int = 10,
+ exclude_comment_id: int | str | None = None,
) -> list[Comment]:
"""Convert raw Bitbucket DC comment dicts to Comment objects."""
all_comments: list[Comment] = []
for comment_data in comments:
+ if exclude_comment_id is not None and str(comment_data.get('id')) == str(
+ exclude_comment_id
+ ):
+ continue
+
# Bitbucket DC activities use epoch milliseconds for createdDate/updatedDate
created_ms = comment_data.get('createdDate')
updated_ms = comment_data.get('updatedDate')
diff --git a/openhands/app_server/integrations/templates/resolver/bitbucket/pr_update_initial_message.j2 b/openhands/app_server/integrations/templates/resolver/bitbucket/pr_update_initial_message.j2
new file mode 100644
index 0000000000..af12e534e6
--- /dev/null
+++ b/openhands/app_server/integrations/templates/resolver/bitbucket/pr_update_initial_message.j2
@@ -0,0 +1,40 @@
+You are checked out to branch {{ branch_name }}, which has an open PR #{{ pr_number }}: "{{ pr_title }}" on Bitbucket.
+A comment on the PR has been addressed to you.
+
+# PR Description
+{{ pr_body }}
+
+{% if file_location %}
+# Comment location
+The comment is in the file `{{ file_location }}` on line #{{ line_number }}.
+{% endif %}
+
+# Comment
+{{ pr_comment }}
+
+{% if comments %}
+# Previous Comments
+Use these earlier PR comments as context only. The comment above is the actionable request.
+{% for comment in comments %}
+- @{{ comment.author }} said at {{ comment.created_at }}:
+{{ comment.body }}
+{% if not loop.last %}
+
+{% endif %}
+{% endfor %}
+{% endif %}
+
+# Steps to Handle the Comment
+
+## Understand the PR Context
+Use the Bitbucket token and Bitbucket API to:
+ 1. Retrieve the diff against the base branch to understand the changes
+ 2. Fetch the PR body and any linked issues for context
+
+## Process the Comment
+If it's a question, answer it.
+
+If it requests a code update:
+ 1. Modify the code accordingly in the current branch
+ 2. Commit your changes with a clear commit message
+ 3. Push the changes to Bitbucket to update the PR.
diff --git a/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_resolver.py b/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_resolver.py
index 97705f7d04..1028436d7b 100644
--- a/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_resolver.py
+++ b/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_resolver.py
@@ -115,6 +115,46 @@ async def test_get_pr_comments_respects_max(svc):
assert len(comments) == 3
+async def test_get_pr_comments_excludes_triggering_comment(svc):
+ activities = {
+ 'values': [
+ {
+ 'action': 'COMMENTED',
+ 'comment': {
+ 'id': 10,
+ 'text': 'older context',
+ 'author': {'slug': 'alice'},
+ 'createdDate': 1_700_000_000_000,
+ 'updatedDate': 1_700_000_000_000,
+ },
+ },
+ {
+ 'action': 'COMMENTED',
+ 'comment': {
+ 'id': 11,
+ 'text': '@openhands do this',
+ 'author': {'slug': 'bob'},
+ 'createdDate': 1_700_000_001_000,
+ 'updatedDate': 1_700_000_001_000,
+ },
+ },
+ ],
+ 'isLastPage': True,
+ }
+
+ with patch.object(svc, '_make_request', return_value=(activities, {})):
+ comments = await svc.get_pr_comments(
+ 'PROJ',
+ 'myrepo',
+ 1,
+ max_comments=10,
+ exclude_comment_id=11,
+ )
+
+ assert [comment.id for comment in comments] == ['10']
+
+
@pytest.mark.asyncio
async def test_get_pr_comments_empty(svc):
with patch.object(